-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathInternal.hs
2933 lines (2535 loc) · 131 KB
/
Internal.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiWayIf #-}
#ifdef USE_REFLEX_OPTIMIZER
{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
#endif
{-# OPTIONS_GHC -Wunused-binds #-}
-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
#if MIN_VERSION_base(4,10,0)
import Control.Applicative (liftA2)
#endif
import Control.Concurrent
import Control.Exception
import Control.Monad hiding (forM, forM_, mapM, mapM_)
import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)
import Control.Monad.Exception
import Control.Monad.Fix
import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
import Control.Monad.Primitive
import Control.Monad.Reader.Class
import Control.Monad.IO.Class
import Control.Monad.ReaderIO
import Control.Monad.Ref
import Control.Monad.Fail (MonadFail)
import qualified Control.Monad.Fail as MonadFail
import Data.Align
import Data.Coerce
import Data.Dependent.Map (DMap)
import qualified Data.Dependent.Map as DMap
import Data.Dependent.Sum (DSum (..))
import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
import qualified Data.FastMutableIntMap as FastMutableIntMap
import Data.Foldable hiding (concat, elem, sequence_)
import Data.Functor.Constant
import Data.Functor.Misc
import Data.Functor.Product
import Data.GADT.Compare
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IORef
import Data.Kind (Type)
import Data.Maybe hiding (mapMaybe)
import Data.Monoid (mempty, (<>))
import Data.Proxy
import Data.These
import Data.Traversable
import Data.Type.Equality ((:~:)(Refl))
import Data.Witherable (Filterable, mapMaybe)
import GHC.Exts hiding (toList)
import GHC.IORef (IORef (..))
import GHC.Stack
import Reflex.FastWeak
import System.IO.Unsafe
import System.Mem.Weak
import Unsafe.Coerce
#ifdef MIN_VERSION_semialign
#if MIN_VERSION_these(0,8,0)
import Data.These.Combinators (justThese)
#endif
#if MIN_VERSION_semialign(1,1,0)
import Data.Zip (Zip (..))
#endif
#endif
#ifdef DEBUG_CYCLES
import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
#endif
import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Tree (Forest, Tree (..), drawForest)
import Data.List (isPrefixOf)
import Data.FastWeakBag (FastWeakBag, FastWeakBagTicket)
import qualified Data.FastWeakBag as FastWeakBag
import Data.Reflection
import Data.Some (Some(Some))
import Data.Type.Coercion
import Data.Profunctor.Unsafe ((#.), (.#))
import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
import qualified Data.WeakBag as WeakBag
import qualified Reflex.Class
import qualified Reflex.Class as R
import qualified Reflex.Host.Class
import Reflex.NotReady.Class
import Data.Patch
import qualified Data.Patch.DMapWithMove as PatchDMapWithMove
import Reflex.PerformEvent.Base (PerformEventT)
#ifdef DEBUG_TRACE_EVENTS
import qualified Data.ByteString.Char8 as BS8
import System.IO (stderr)
import Data.List (isPrefixOf)
#endif
-- TODO stdout might not be the best channel for debug output
debugStrLn :: String -> IO ()
debugStrLn = putStrLn
#ifdef DEBUG_TRACE_EVENTS
withStackOneLine :: (BS8.ByteString -> a) -> a
withStackOneLine expr = unsafePerformIO $ do
stack <- currentCallStack
return (expr . BS8.pack . unwords . dropInternal . reverse $ stack)
where dropInternal = filterStack "Reflex.Spider.Internal"
#endif
debugPropagate :: Bool
debugInvalidateHeight :: Bool
debugInvalidate :: Bool
#ifdef DEBUG
#define DEBUG_NODEIDS
#ifdef DEBUG_TRACE_PROPAGATION
debugPropagate = True
#else
debugPropagate = False
#endif
#ifdef DEBUG_TRACE_HEIGHT
debugInvalidateHeight = True
#else
debugInvalidateHeight = False
#endif
#ifdef DEBUG_TRACE_INVALIDATION
debugInvalidate = True
#else
debugInvalidate = False
#endif
class HasNodeId a where
getNodeId :: a -> Int
instance HasNodeId (CacheSubscribed x a) where
getNodeId = _cacheSubscribed_nodeId
instance HasNodeId (FanInt x a) where
getNodeId = _fanInt_nodeId
instance HasNodeId (Hold x p) where
getNodeId = holdNodeId
instance HasNodeId (SwitchSubscribed x a) where
getNodeId = switchSubscribedNodeId
instance HasNodeId (FanSubscribed x v a) where
getNodeId = fanSubscribedNodeId
instance HasNodeId (CoincidenceSubscribed x a) where
getNodeId = coincidenceSubscribedNodeId
instance HasNodeId (RootSubscribed x a) where
getNodeId = rootSubscribedNodeId
instance HasNodeId (Pull x a) where
getNodeId = pullNodeId
{-# INLINE showNodeId #-}
showNodeId :: HasNodeId a => a -> String
showNodeId = showNodeId' . getNodeId
showNodeId' :: Int -> String
showNodeId' = ("#"<>) . show
#else
debugPropagate = False
debugInvalidateHeight = False
debugInvalidate = False
-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
{-# INLINE showNodeId #-}
showNodeId :: a -> String
showNodeId _ = ""
{-# INLINE showNodeId' #-}
showNodeId' :: Int -> String
showNodeId' _ = ""
#endif
#ifdef DEBUG_NODEIDS
{-# NOINLINE nextNodeIdRef #-}
nextNodeIdRef :: IORef Int
nextNodeIdRef = unsafePerformIO $ newIORef 1
newNodeId :: IO Int
newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
#endif
--------------------------------------------------------------------------------
-- EventSubscription
--------------------------------------------------------------------------------
--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
data EventSubscription x = EventSubscription
{ _eventSubscription_unsubscribe :: !(IO ())
, _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
}
unsubscribe :: EventSubscription x -> IO ()
unsubscribe (EventSubscription u _) = u
--------------------------------------------------------------------------------
-- Event
--------------------------------------------------------------------------------
newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
{-# INLINE subscribeAndRead #-}
subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
subscribeAndRead = unEvent
{-# RULES
"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
#-}
-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
-- caching; if the computation function is very cheap, this is (much) more
-- efficient than 'push'
{-# INLINE [1] pushCheap #-}
pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
pushCheap !f e = Event $ \sub -> do
(subscription, occ) <- subscribeAndRead e $ debugSubscriber' "push" $ sub
{ subscriberPropagate = \a -> do
mb <- f a
mapM_ (subscriberPropagate sub) mb
}
occ' <- join <$> mapM f occ
return (subscription, occ')
-- | A subscriber that never triggers other 'Event's
{-# INLINE terminalSubscriber #-}
terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
terminalSubscriber p = Subscriber
{ subscriberPropagate = p
, subscriberInvalidateHeight = \_ -> return ()
, subscriberRecalculateHeight = \_ -> return ()
}
-- | Subscribe to an Event only for the duration of one occurrence
{-# INLINE subscribeAndReadHead #-}
subscribeAndReadHead :: HasSpiderTimeline x => Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
subscribeAndReadHead e sub = do
subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
(subscription, occ) <- subscribeAndRead e $ debugSubscriber' "head" $ sub
{ subscriberPropagate = \a -> do
liftIO $ unsubscribe =<< readIORef subscriptionRef
subscriberPropagate sub a
}
liftIO $ case occ of
Nothing -> writeIORef subscriptionRef $! subscription
Just _ -> unsubscribe subscription
return (subscription, occ)
--TODO: Make this lazy in its input event
headE :: (MonadIO m, Defer (SomeMergeInit x) m, HasSpiderTimeline x) => Event x a -> m (Event x a)
headE originalE = do
parent <- liftIO $ newIORef $ Just originalE
defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
let clearParent = liftIO $ writeIORef parent Nothing
(_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ const clearParent
when (isJust occ) clearParent
return $ Event $ \sub ->
liftIO (readIORef parent) >>= \case
Nothing -> subscribeAndReadNever
Just e -> subscribeAndReadHead e sub
data CacheSubscribed x a
= CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
, _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
, _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
#ifdef DEBUG_NODEIDS
, _cacheSubscribed_nodeId :: {-# UNPACK #-} !Int
#endif
}
nowSpiderEventM :: (HasSpiderTimeline x) => EventM x (R.Event (SpiderTimeline x) ())
nowSpiderEventM =
SpiderEvent <$> now
now :: (MonadIO m, Defer (Some Clear) m, HasSpiderTimeline x
) => m (Event x ())
now = do
nowOrNot <- liftIO $ newIORef $ Just ()
scheduleClear nowOrNot
return . Event $ \_ -> do
occ <- liftIO . readIORef $ nowOrNot
return ( EventSubscription (return ()) eventSubscribedNow
, occ
)
-- | Construct an 'Event' whose value is guaranteed not to be recomputed
-- repeatedly
--
--TODO: Try a caching strategy where we subscribe directly to the parent when
--there's only one subscriber, and then build our own FastWeakBag only when a second
--subscriber joins
{-# NOINLINE [0] cacheEvent #-}
cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
cacheEvent e =
#ifdef DEBUG_TRACE_EVENTS
withStackOneLine $ \callSite -> Event $
#else
Event $
#endif
unsafePerformIO $ do
mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
<- newIORef emptyFastWeak
pure $ \sub -> {-# SCC "cacheEvent" #-} do
#ifdef DEBUG_TRACE_EVENTS
unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
#endif
subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
Just subscribedTicket -> return subscribedTicket
Nothing -> do
#ifdef DEBUG_NODEIDS
nodeId <- liftIO newNodeId
#endif
subscribers <- liftIO FastWeakBag.empty
occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
#ifdef DEBUG_NODEIDS
(parentSub, occ) <- subscribeAndRead e $ debugSubscriber' ("cacheEvent" <> showNodeId' nodeId) $ Subscriber
#else
(parentSub, occ) <- subscribeAndRead e $ Subscriber
#endif
{ subscriberPropagate = \a -> do
liftIO $ writeIORef occRef (Just a)
scheduleClear occRef
propagateFast a subscribers
, subscriberInvalidateHeight = FastWeakBag.traverse_ subscribers . invalidateSubscriberHeight
, subscriberRecalculateHeight = FastWeakBag.traverse_ subscribers . recalculateSubscriberHeight
}
when (isJust occ) $ do
liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
scheduleClear occRef
let !subscribed = CacheSubscribed
{ _cacheSubscribed_subscribers = subscribers
, _cacheSubscribed_parent = parentSub
, _cacheSubscribed_occurrence = occRef
#ifdef DEBUG_NODEIDS
, _cacheSubscribed_nodeId = nodeId
#endif
}
subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
return subscribedTicket
liftIO $ cacheSubscription sub mSubscribedRef subscribedTicket
cacheSubscription :: Subscriber x a -> IORef (FastWeak (CacheSubscribed x a))
-> FastWeakTicket (CacheSubscribed x a) -> IO (EventSubscription x, Maybe a)
cacheSubscription sub mSubscribedRef subscribedTicket = do
subscribed <- getFastWeakTicketValue subscribedTicket
ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
occ <- readIORef $ _cacheSubscribed_occurrence subscribed
let parentSub = _cacheSubscribed_parent subscribed
es = EventSubscription
{ _eventSubscription_unsubscribe = do
FastWeakBag.remove ticket
isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
when isEmpty $ do
writeIORef mSubscribedRef emptyFastWeak
unsubscribe parentSub
touch ticket
touch subscribedTicket
, _eventSubscription_subscribed = EventSubscribed
{ eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub
, eventSubscribedRetained = toAny subscribedTicket
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = return [_eventSubscription_subscribed parentSub]
, eventSubscribedHasOwnHeightRef = False
, eventSubscribedWhoCreated = whoCreatedIORef mSubscribedRef
#endif
}
}
return (es, occ)
subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
subscribe e s = fst <$> subscribeAndRead e s
{-# INLINE wrap #-}
wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
wrap tag getSpecificSubscribed sub = do
(sln, subd, occ) <- getSpecificSubscribed sub
let es = tag subd
return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
eventRoot :: (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Event x a
eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
subscribeAndReadNever :: EventM x (EventSubscription x, Maybe a)
subscribeAndReadNever = return (EventSubscription (return ()) eventSubscribedNever, Nothing)
eventNever :: Event x a
eventNever = Event $ const subscribeAndReadNever
eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
eventHold :: Hold x p -> Event x p
eventHold !h = Event $ subscribeHoldEvent h
eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
{-# INLINE subscribeCoincidenceInner #-}
subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
(subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
let height = max innerHeight outerHeight
defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
return (innerOcc, height, innerSubd)
--------------------------------------------------------------------------------
-- Subscriber
--------------------------------------------------------------------------------
data Subscriber x a = Subscriber
{ subscriberPropagate :: !(a -> EventM x ())
, subscriberInvalidateHeight :: !(Height -> IO ())
, subscriberRecalculateHeight :: !(Height -> IO ())
}
newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
newSubscriberHold h = return $ Subscriber
{ subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
, subscriberInvalidateHeight = \_ -> return ()
, subscriberRecalculateHeight = \_ -> return ()
}
newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
newSubscriberFan subscribed = debugSubscriber ("SubscriberFan " <> showNodeId subscribed) $ Subscriber
{ subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
tracePropagate (Proxy :: Proxy x) $ show (DMap.size subs) <> " keys subscribed, " <> show (DMap.size a) <> " keys firing"
liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
scheduleClear $ fanSubscribedOccurrence subscribed
let f _ (Pair v subsubs) = do
propagate v $ _fanSubscribedChildren_list subsubs
return $ Constant ()
_ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
return ()
, subscriberInvalidateHeight = \old -> do
subscribers <- readIORef $ fanSubscribedSubscribers subscribed
forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
, subscriberRecalculateHeight = \new -> do
subscribers <- readIORef $ fanSubscribedSubscribers subscribed
forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
}
newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
newSubscriberSwitch subscribed = debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $ Subscriber
{ subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
scheduleClear $ switchSubscribedOccurrence subscribed
propagate a $ switchSubscribedSubscribers subscribed
, subscriberInvalidateHeight = \_ -> do
oldHeight <- readIORef $ switchSubscribedHeight subscribed
when (oldHeight /= invalidHeight) $ do
writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
, subscriberRecalculateHeight = (`updateSwitchHeight` subscribed)
}
newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
newSubscriberCoincidenceOuter subscribed = debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $ Subscriber
{ subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
(occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
scheduleClear $ coincidenceSubscribedInnerParent subscribed
case occ of
Nothing ->
when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
Just o -> do -- Since it's already firing, no need to adjust height
liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
scheduleClear $ coincidenceSubscribedOccurrence subscribed
propagate o $ coincidenceSubscribedSubscribers subscribed
, subscriberInvalidateHeight = \_ -> invalidateCoincidenceHeight subscribed
, subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed
}
newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
newSubscriberCoincidenceInner subscribed = debugSubscriber ("SubscriberCoincidenceInner" <> showNodeId subscribed) $ Subscriber
{ subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
case occ of
Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
Nothing -> do
liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
scheduleClear $ coincidenceSubscribedOccurrence subscribed
propagate a $ coincidenceSubscribedSubscribers subscribed
, subscriberInvalidateHeight = \_ -> invalidateCoincidenceHeight subscribed
, subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed
}
invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
invalidateSubscriberHeight = flip subscriberInvalidateHeight
recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
recalculateSubscriberHeight = flip subscriberRecalculateHeight
-- | Propagate everything at the current height
propagate :: forall x a. HasSpiderTimeline x => a -> WeakBag (Subscriber x a) -> EventM x ()
propagate a subscribers = withIncreasedDepth (Proxy::Proxy x) $
-- 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
--TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
-- | Propagate everything at the current height
propagateFast :: forall x a. HasSpiderTimeline x => a -> FastWeakBag (Subscriber x a) -> EventM x ()
propagateFast a subscribers = withIncreasedDepth (Proxy::Proxy x) $
-- 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
--TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
--------------------------------------------------------------------------------
-- EventSubscribed
--------------------------------------------------------------------------------
toAny :: a -> Any
toAny = unsafeCoerce
-- Why do we use Any here, instead of just giving eventSubscribedRetained an
-- existential type? Sadly, GHC does not currently know how to unbox types
-- with existentially quantified fields. So instead we just coerce values
-- to type Any on the way in. Since we never coerce them back, this is
-- perfectly safe.
data EventSubscribed x = EventSubscribed
{ eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
, eventSubscribedRetained :: {-# NOUNPACK #-} !Any
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents :: !(IO [EventSubscribed x]) -- For debugging loops
, eventSubscribedHasOwnHeightRef :: !Bool
, eventSubscribedWhoCreated :: !(IO [String])
#endif
}
eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
eventSubscribedRoot !r = EventSubscribed
{ eventSubscribedHeightRef = zeroRef
, eventSubscribedRetained = toAny r
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = return []
, eventSubscribedHasOwnHeightRef = False
, eventSubscribedWhoCreated = return ["root"]
#endif
}
eventSubscribedNever :: EventSubscribed x
eventSubscribedNever = EventSubscribed
{ eventSubscribedHeightRef = zeroRef
, eventSubscribedRetained = toAny ()
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = return []
, eventSubscribedHasOwnHeightRef = False
, eventSubscribedWhoCreated = return ["never"]
#endif
}
eventSubscribedNow :: EventSubscribed x
eventSubscribedNow = EventSubscribed
{ eventSubscribedHeightRef = zeroRef
, eventSubscribedRetained = toAny ()
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = return []
, eventSubscribedHasOwnHeightRef = False
, eventSubscribedWhoCreated = return ["now"]
#endif
}
eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
eventSubscribedFan !subscribed = EventSubscribed
{ eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
, eventSubscribedRetained = toAny subscribed
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = return [_eventSubscription_subscribed $ fanSubscribedParent subscribed]
, eventSubscribedHasOwnHeightRef = False
, eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
#endif
}
eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
eventSubscribedSwitch !subscribed = EventSubscribed
{ eventSubscribedHeightRef = switchSubscribedHeight subscribed
, eventSubscribedRetained = toAny subscribed
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = do
s <- readIORef $ switchSubscribedCurrentParent subscribed
return [_eventSubscription_subscribed s]
, eventSubscribedHasOwnHeightRef = True
, eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
#endif
}
eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
eventSubscribedCoincidence !subscribed = EventSubscribed
{ eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
, eventSubscribedRetained = toAny subscribed
#ifdef DEBUG_CYCLES
, eventSubscribedGetParents = do
innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
let outerParent = _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
innerParents = maybeToList $ innerSubscription
return $ outerParent : innerParents
, eventSubscribedHasOwnHeightRef = True
, eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
#endif
}
getEventSubscribedHeight :: EventSubscribed x -> IO Height
getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
#ifdef DEBUG_CYCLES
whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
whoCreatedEventSubscribed = eventSubscribedWhoCreated
walkInvalidHeightParents :: EventSubscribed x -> IO [EventSubscribed x]
walkInvalidHeightParents s0 = do
subscribers <- flip execStateT mempty $ ($ s0) $ fix $ \loop s -> do
h <- liftIO $ readIORef $ eventSubscribedHeightRef s
when (h == invalidHeight) $ do
when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
modify (s :)
mapM_ loop =<< liftIO (eventSubscribedGetParents s)
forM_ subscribers $ \s -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
return subscribers
#endif
{-# INLINE subscribeHoldEvent #-}
subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
subscribeHoldEvent = subscribeAndRead . holdEvent
--------------------------------------------------------------------------------
-- Behavior
--------------------------------------------------------------------------------
newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
behaviorHold !h = Behavior $ readHoldTracked h
behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
behaviorHoldIdentity = behaviorHold
behaviorConst :: a -> Behavior x a
behaviorConst !a = Behavior $ return a
behaviorPull :: Pull x a -> Behavior x a
behaviorPull !p = Behavior $ do
val <- liftIO $ readIORef $ pullValue p
case val of
Just subscribed -> do
askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
return $ pullSubscribedValue subscribed
Nothing -> do
i <- liftIO $ newInvalidatorPull p
wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
parentsRef <- liftIO $ newIORef []
holdInits <- askBehaviorHoldInits
a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
parents <- liftIO $ readIORef parentsRef
let subscribed = PullSubscribed
{ pullSubscribedValue = a
, pullSubscribedInvalidators = invsRef
, pullSubscribedOwnInvalidator = i
, pullSubscribedParents = parents
}
liftIO $ writeIORef (pullValue p) $ Just subscribed
askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
return a
behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
{-# INLINE readHoldTracked #-}
readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
readHoldTracked h = do
result <- liftIO $ readIORef $ holdValue h
askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
return result
{-# INLINABLE readBehaviorUntracked #-}
readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
readBehaviorUntracked b = do
holdInits <- getDeferralQueue
liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
--------------------------------------------------------------------------------
-- Dynamic
--------------------------------------------------------------------------------
type DynamicS x p = Dynamic x (PatchTarget p) p
data Dynamic x target p = Dynamic
{ dynamicCurrent :: !(Behavior x target)
, dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
}
deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
dynamicHold :: Hold x p -> DynamicS x p
dynamicHold !h = Dynamic
{ dynamicCurrent = behaviorHold h
, dynamicUpdated = eventHold h
}
dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
dynamicHoldIdentity = dynamicHold
dynamicConst :: PatchTarget p -> DynamicS x p
dynamicConst !a = Dynamic
{ dynamicCurrent = behaviorConst a
, dynamicUpdated = eventNever
}
dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
dynamicDyn !d = Dynamic
{ dynamicCurrent = behaviorDyn d
, dynamicUpdated = eventDyn d
}
dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
dynamicDynIdentity = dynamicDyn
--------------------------------------------------------------------------------
-- Combinators
--------------------------------------------------------------------------------
--type role Hold representational
data Hold x p
= Hold { holdValue :: !(IORef (PatchTarget p))
, holdInvalidators :: !(IORef [Weak (Invalidator x)])
, holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
, holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
#ifdef DEBUG_NODEIDS
, holdNodeId :: Int
#endif
}
-- | A statically allocated 'SpiderTimeline'
data Global
{-# NOINLINE globalSpiderTimelineEnv #-}
globalSpiderTimelineEnv :: SpiderTimelineEnv Global
globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
-- | Stores all global data relevant to a particular Spider timeline; only one
-- value should exist for each type @x@
newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
-- We implement SpiderTimelineEnv with a newtype wrapper so
-- we can get the coercions we want safely.
type role SpiderTimelineEnv nominal
data SpiderTimelineEnv' x = SpiderTimelineEnv
{ _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
, _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
#ifdef DEBUG
, _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
#endif
}
type role SpiderTimelineEnv' phantom
instance Eq (SpiderTimelineEnv x) where
_ == _ = True -- Since only one exists of each type
instance GEq SpiderTimelineEnv where
a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
else Nothing
data EventEnv x
= EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
, eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
, eventEnvDynInits :: !(IORef [SomeDynInit x])
, eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
, eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
, eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
, eventEnvIntClears :: !(IORef [Some IntClear])
, eventEnvRootClears :: !(IORef [Some RootClear])
, eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
, eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
, eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
}
{-# INLINE runEventM #-}
runEventM :: EventM x a -> IO a
runEventM = unEventM
asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
class MonadIO m => Defer a m where
getDeferralQueue :: m (IORef [a])
{-# INLINE defer #-}
defer :: Defer a m => a -> m ()
defer a = do
q <- getDeferralQueue
liftIO $ modifyIORef' q (a:)
instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvAssignments
instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvHoldInits
instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvDynInits
instance Defer (SomeHoldInit x) (BehaviorM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = BehaviorM $ asks snd
instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvMergeUpdates
instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvMergeInits
class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
getCurrentHeight :: m Height
scheduleMerge :: Height -> EventM x () -> m ()
instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
{-# INLINE getCurrentHeight #-}
getCurrentHeight = do
heightRef <- asksEventEnv eventEnvCurrentHeight
liftIO $ readIORef heightRef
{-# INLINE scheduleMerge #-}
scheduleMerge height subscribed = do
delayedRef <- asksEventEnv eventEnvDelayedMerges
liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
class HasSpiderTimeline x where
-- | Retrieve the current SpiderTimelineEnv
spiderTimeline :: SpiderTimelineEnv x
instance HasSpiderTimeline Global where
spiderTimeline = globalSpiderTimelineEnv
putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
putCurrentHeight h = do
heightRef <- asksEventEnv eventEnvCurrentHeight
liftIO $ writeIORef heightRef $! h
instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvClears
{-# INLINE scheduleClear #-}
scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
scheduleClear r = defer $ Some $ Clear r
instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvIntClears
{-# INLINE scheduleIntClear #-}
scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
scheduleIntClear r = defer $ Some $ IntClear r
instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvRootClears
{-# INLINE scheduleRootClear #-}
scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
scheduleRootClear r = defer $ Some $ RootClear r
instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
{-# INLINE getDeferralQueue #-}
getDeferralQueue = asksEventEnv eventEnvResetCoincidences
-- Note: hold cannot examine its event until after the phase is over
{-# INLINE [1] hold #-}
hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
hold v0 e = do
valRef <- liftIO $ newIORef v0
invsRef <- liftIO $ newIORef []
parentRef <- liftIO $ newIORef Nothing
#ifdef DEBUG_NODEIDS
nodeId <- liftIO newNodeId
#endif
let h = Hold
{ holdValue = valRef
, holdInvalidators = invsRef
, holdEvent = e
, holdParent = parentRef
#ifdef DEBUG_NODEIDS
, holdNodeId = nodeId
#endif
}
defer $ SomeHoldInit h
return h
{-# INLINE getHoldEventSubscription #-}
getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
getHoldEventSubscription h = do
ep <- liftIO $ readIORef $ holdParent h
case ep of
Just subd -> return subd
Nothing -> do
let e = holdEvent h
subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
(subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
liftIO $ writeIORef subscriptionRef $! subscription
case occ of
Nothing -> return ()
Just o -> do
old <- liftIO $ readIORef $ holdValue h
case apply o old of
Nothing -> return ()
Just new -> do
-- Need to evaluate these so that we don't retain the Hold itself
v <- liftIO $ evaluate $ holdValue h
i <- liftIO $ evaluate $ holdInvalidators h
defer $ SomeAssignment v i new
liftIO $ writeIORef (holdParent h) $ Just subscription
return subscription
type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
-- BehaviorM can sample behaviors
newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
instance Monad (BehaviorM x) where
{-# INLINE (>>=) #-}
BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
{-# INLINE (>>) #-}
BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
{-# INLINE return #-}
return x = BehaviorM $ return x
#if !MIN_VERSION_base(4,13,0)
{-# INLINE fail #-}