on develop help sign in
90 files changed+1495−13892
since splitsnapshots
unifiedsplit
.github/workflows/haskell.yml+47 CONTRIBUTING.md+11−2 ChangeLog.md+54−15 Quickref.md−311 README.md+42−14 bench/Main.hs−110 bench/RunAll.hs−157 cabal.project+1 default.nix−40 dep/reflex-platform/default.nix+8 dep/reflex-platform/github.json+8 hydra.json−29 jobsets.nix−70 patch.cabal+100 reflex-platform.nix−8 reflex.cabal−370 release.nix+47−7 src/Data/AppendMap.hs−80 src/Data/FastMutableIntMap.hs−93 src/Data/FastWeakBag.hs−156 src/Data/Functor/Misc.hs+4−9 src/Data/Map/Misc.hs−71 src/Data/Monoid/DecidablyEmpty.hs+115 src/Data/Patch.hs+95 src/Reflex/Patch/Class.hs → src/Data/Patch/Class.hs+14−3 src/Reflex/Patch/DMap.hs → src/Data/Patch/DMap.hs+16−5 src/Reflex/Patch/DMapWithMove.hs → src/Data/Patch/DMapWithMove.hs+22−17 src/Reflex/Patch/IntMap.hs → src/Data/Patch/IntMap.hs+30−21 src/Reflex/Patch/Map.hs → src/Data/Patch/Map.hs+37−28 src/Data/Patch/MapWithMove.hs+312 src/Data/Patch/MapWithPatchingMove.hs+432 src/Data/Semigroup/Additive.hs+54 src/Data/WeakBag.hs−121 src/Reflex.hs−35 src/Reflex/Adjustable/Class.hs−140 src/Reflex/BehaviorWriter/Base.hs−202 src/Reflex/BehaviorWriter/Class.hs−26 src/Reflex/Class.hs−1591 src/Reflex/Collection.hs−218 src/Reflex/Dynamic.hs−530 src/Reflex/Dynamic/TH.hs−106 src/Reflex/Dynamic/Uniq.hs−105 src/Reflex/DynamicWriter.hs−7 src/Reflex/DynamicWriter/Base.hs−237 src/Reflex/DynamicWriter/Class.hs−30 src/Reflex/EventWriter.hs−7 src/Reflex/EventWriter/Base.hs−306 src/Reflex/EventWriter/Class.hs−27 src/Reflex/FastWeak.hs−200 src/Reflex/FunctorMaybe.hs−47 src/Reflex/Host/Class.hs−280 src/Reflex/Network.hs−45 src/Reflex/NotReady/Class.hs−78 src/Reflex/Optimizer.hs−65 src/Reflex/Patch.hs−50 src/Reflex/Patch/MapWithMove.hs−270 src/Reflex/Patch/MapWithMove2.hs−245 src/Reflex/PerformEvent/Base.hs−179 src/Reflex/PerformEvent/Class.hs−64 src/Reflex/PostBuild/Base.hs−197 src/Reflex/PostBuild/Class.hs−42 src/Reflex/Profiled.hs−219 src/Reflex/Pure.hs−208 src/Reflex/Query/Base.hs−342 src/Reflex/Query/Class.hs−119 src/Reflex/Requester/Base.hs−538 src/Reflex/Requester/Class.hs−73 src/Reflex/Spider.hs−20 src/Reflex/Spider/Internal.hs−2641 src/Reflex/Time.hs−384 src/Reflex/TriggerEvent/Base.hs−148 src/Reflex/TriggerEvent/Class.hs−50 src/Reflex/Widget/Basic.hs−44 src/Reflex/Workflow.hs−50 test/EventWriterT.hs−132 test/GC.hs−100 test/QueryT.hs−138 test/Reflex/Bench/Focused.hs−369 test/Reflex/Plan/Pure.hs−72 test/Reflex/Plan/Reflex.hs−135 test/Reflex/Test.hs−66 test/Reflex/Test/CrossImpl.hs−257 test/Reflex/Test/Micro.hs−346 test/Reflex/TestPlan.hs−52 test/RequesterT.hs−169 test/Test/Run.hs−74 test/hlint.hs+3−8 test/rootCleanup.hs−25 test/semantics.hs−47 test/tests.hs+43
.github/workflows/haskell.ymlnew file+47
@@ -0,0 +1,47 @@
1+name: github-action
2+
3+on: [push, pull_request]
4+
5+jobs:
6+ build:
7+ strategy:
8+ matrix:
9+ ghc: ['8.0.2', '8.2.2', '8.4.4', '8.6.5', '8.8.4', '8.10.2']
10+ os: ['ubuntu-latest', 'macos-latest']
11+ exclude:
12+ # There are some linker warnings in 802 on darwin that
13+ # cause compilation to fail
14+ # See https://github.com/NixOS/nixpkgs/issues/25139
15+ - ghc: '8.0.2'
16+ os: 'macos-latest'
17+ runs-on: ${{ matrix.os }}
18+
19+ name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20+ steps:
21+ - uses: actions/checkout@v2
22+ - uses: actions/setup-haskell@v1
23+ with:
24+ ghc-version: ${{ matrix.ghc }}
25+ - name: Cache
26+ uses: actions/cache@v1
27+ env:
28+ cache-name: cache-cabal
29+ with:
30+ path: ~/.cabal
31+ key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32+ restore-keys: |
33+ ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34+ ${{ runner.os }}-${{ matrix.ghc }}-build-
35+ ${{ runner.os }}-${{ matrix.ghc }}-
36+ ${{ runner.os }}
37+
38+ - name: Install dependencies
39+ run: |
40+ cabal update
41+ cabal build --only-dependencies --enable-tests --enable-benchmarks
42+ - name: Build
43+ run: cabal build --enable-tests --enable-benchmarks all
44+ - name: Run tests
45+ run: cabal test --enable-tests all
46+ - name: Build Docs
47+ run: cabal haddock
CONTRIBUTING.md+11−2
@@ -5,6 +5,7 @@ Contributions and issue reports are encouraged and appreciated!
55- [Opening Issues](#opening-issues)
66- [Submitting Changes](#submitting-changes)
77 - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
8+ - [Guidelines for Pull Requests](#guidelines-for-pull-requests)
89 - [Code Quality](#code-quality)
910 - [Documentation](#documentation)
1011
@@ -14,8 +15,8 @@ Before opening an issue, please check whether your issue has already been report
1415
1516* Describe the issue you're encountering or the suggestion you're making
1617* Include any relevant steps to reproduce or code samples you can. It's always easier for us to debug if we have something that demonstrates the error.
17−* Let us know what version of reflex you were using. If you're using a github checkout, provide the git hash.
18−* Describe how you're building reflex (i.e., via reflex-platform, cabal install, stack, obelisk, etc.). If you're using reflex-platform or obelisk, provide the git hash of your checkout.
18+* Let us know what version of patch you were using. If you're using a github checkout, provide the git hash.
19+* Describe how you're building patch (i.e., via reflex-platform, cabal install, stack, obelisk, etc.). If you're using reflex-platform or obelisk, provide the git hash of your checkout.
1920
2021## Submitting Changes
2122
@@ -30,6 +31,10 @@ One way to think about it is that your commit message should be able to complete
3031#### Body
3132For breaking changes, new features, refactors, or other major changes, the body of the commit message should describe the motivation behind the change in greater detail and may include references to the issue tracker. The body shouldn't repeat code/comments from the diff.
3233
34+### Guidelines for Pull Requests
35+
36+Wherever possible, pull requests should add a single feature or fix a single bug. Pull requests should not bundle several unrelated changes.
37+
3338### Code Quality
3439
3540#### Warnings
@@ -40,6 +45,10 @@ Your pull request should add no new warnings to the project. It should also gene
4045
4146Make sure the project builds and that the tests pass! This will generally also be checked by CI before merge, but trying it yourself first means you'll catch problems earlier and your contribution can be merged that much sooner!
4247
48+#### Dependencies
49+
50+Include version bounds whenever adding a dependency to the library stanza of the cabal file. Note that libraries added to patch.cabal also need to be added to default.nix.
51+
4352### Documentation
4453
4554#### In the code
ChangeLog.md+54−15
@@ -1,22 +1,61 @@
1−# Revision history for reflex
1+# Revision history for patch
22
33## Unreleased
44
5−* Fix `holdDyn` so that it is lazy in its event argument
6−* Add `Reflex.Query.Base.mapQueryT`. See that module for documentation
5+* New dep of `data-orphans` for old GHC to get instances honestly instead of
6+ via `monoidal-containers`.
77
8−## 0.6.1.0
8+## 0.0.5.0 - 2021-12-17
99
10−* Re-export all of `Data.Map.Monoidal`
11−* Fix `QueryT` and `RequesterT` tests
10+* `Additive` now lives in `Data.Semigroup.Additive`, but is still reexported
11+ from `Data.Patch` for compatability.
1212
13−## 0.6.0.0 -- 2019-03-20
13+* Rewrite `PatchMapWithMove` in terms of `PatchMapWithPatchingMove`.
14+ Care is taken to make this not a breaking change.
15+ In particular, `PatchMapWithMove` is a newtype of `PatchMapWithPatchingMove`, as is the `NodeInfo` and `From` of `PatchMapWithPatchingMove`'s versions of those.
16+ There are complete constructor and field patterns too, and everything is
17+ exported under the newtype as real constructors and fields would be.
1418
15−* Deprecate `FunctorMaybe` in favor of `Data.Witherable.Filterable`. We still export `fmapMaybe`, `ffilter`, etc., but they all rely on `Filterable` now.
16−* Rename `MonadDynamicWriter` to `DynamicWriter` and add a deprecation for the old name.
17−* Remove many deprecated functions.
18−* Add a `Num` instance for `Dynamic`.
19−* Add `matchRequestsWithResponses` to make it easier to use `Requester` with protocols that don't do this matching for you.
20−* Add `withRequesterT` to map functions over the request and response of a `RequesterT`.
21−* Suppress nil patches in `QueryT` as an optimization. The `Query` type must now have an `Eq` instance.
22−* Add `throttleBatchWithLag` to `Reflex.Time`. See that module for details.
19+## 0.0.4.0 - 2021-04-20
20+
21+* Enable PolyKinds
22+
23+## 0.0.3.2 - 2020-11-06
24+
25+* Update version bounds
26+
27+## 0.0.3.1 - 2020-02-05
28+
29+* Replace `fromJust` with something easier to debug.
30+
31+## 0.0.3.0 - 2020-02-05
32+
33+* Create `PatchMapWithPatchingMove` variant which supports moves with a patch.
34+
35+* Create `DecidablyEmpty` subclass of `Monoid`.
36+
37+## 0.0.2.0 - 2020-01-17
38+
39+* Consistently provide:
40+
41+ - `Wrapped` instances
42+
43+ - `*WithIndex` instances
44+
45+ - `un*` newtype unwrappers
46+
47+ for `PatchMap`, `PatchIntMap`, and `PatchMapWithMove`.
48+
49+## 0.0.1.0 - 2020-01-09
50+
51+* Support older GHCs with `split-these` flag.
52+
53+* Additional instances for the `Group` class for basic types.
54+
55+## 0.0.0.1 - 2020-01-08
56+
57+* Remove unneeded dependencies
58+
59+## 0.0.0.0 - 2020-01-08
60+
61+* Extract patching functionality from Reflex.
Quickref.mddeleted−311
@@ -1,311 +0,0 @@
1−# Reflex Quick(ish) Reference
2−
3−## Typeclasses
4−
5−Many Reflex functions operate in monadic context `m a`, where the monad 'm' supports various additional typeclasses such as MonadWidget, MonadHold, or MonadSample in addition to Monad itself. The actual 'm' in use will be determined by the top-level entry point of the FRP host (such as Reflex-Dom -- see the bottom of the Reflex-Dom quick reference for details).
6−
7−The function signatures here have been simplified by removing many typeclass constraints and adding simple annotations to each function. Also the ubiquitous 't' type parameter has been removed.
8−
9−Some of these functions are *pure*: They operate on Events, Behaviors, or Dynamics uniformly without regard to the "current time". Other functions must operate in some monadic context, because they produce a result "as of now" (e.g., any function that takes an "initial" value, or returns a "current" value). Annotations are used to distinguish these cases:
10−
11−```haskell
12−[ ] -- Pure function
13−[S] -- Function runs in any monad supporting MonadSample
14−[H] -- Function runs in any monad supporting MonadHold
15−```
16−Since MonadHold depends on MonadSample, any [S] function also runs in [H] context.
17−
18−## Functions producing Event
19−
20−```haskell
21−-- Trivial Event
22−[ ] never :: Event a
23−
24−-- Extract Event from Dynamic
25−[ ] updated :: Dynamic a -> Event a
26−
27−-- Transform Event to Event using function
28−[ ] fmap :: (a -> b) -> Event a -> Event b
29−[ ] fmapMaybe :: (a -> Maybe b) -> Event a -> Event b
30−[ ] ffilter :: (a -> Bool) -> Event a -> Event a
31−[ ] ffor :: Event a -> (a -> b) -> Event b
32−[ ] fforMaybe :: Event a -> (a -> Maybe b) -> Event b
33−[ ] <$ :: a -> Event b -> Event a
34−
35−-- Event to identical Event with debug trace. (Only prints if Event is ultimately used.)
36−[ ] traceEvent :: Show a => String -> Event a -> Event a
37−[ ] traceEventWith :: (a -> String) -> Event a -> Event a
38−
39−-- Transform Event to Event by sampling Behavior or Dynamic
40−[ ] gate :: Behavior Bool -> Event a -> Event a
41−[ ] tag :: Behavior a -> Event b -> Event a
42−[ ] tagPromptlyDyn :: Dynamic a -> Event b -> Event a
43−[ ] attach :: Behavior a -> Event b -> Event (a, b)
44−[ ] attachPromptlyDyn :: Dynamic a -> Event b -> Event (a, b)
45−[ ] attachWith :: (a -> b -> c) -> Behavior a -> Event b -> Event c
46−[ ] attachPromptlyDynWith :: (a -> b -> c) -> Dynamic a -> Event b -> Event c
47−[ ] attachWithMaybe :: (a -> b -> Maybe c) -> Behavior a -> Event b -> Event c
48−[ ] attachPromptlyDynWithMaybe :: (a -> b -> Maybe c) -> Dynamic a -> Event b -> Event c
49−[ ] <@> :: Behavior (a -> b) -> Event a -> Event b
50−[ ] <@ :: Behavior a -> Event b -> Event a
51−
52−-- Combine multiple Events
53−[ ] <> :: Semigroup a => Event a -> Event a -> Event a
54−[ ] difference :: Event a -> Event b -> Event a
55−[ ] align :: Event a -> Event b -> Event (These a b)
56−[ ] alignWith :: (These a b -> c) -> Event a -> Event b -> Event c
57−[ ] mergeWith :: (a -> a -> a) -> [Event a] -> Event a
58−[ ] leftmost :: [Event a] -> Event a
59−[ ] mergeList :: [Event a] -> Event (NonEmpty a)
60−[ ] merge :: GCompare k => DMap k Event -> Event (DMap k Identity)
61−[ ] mergeMap :: Ord k => Map k (Event a) -> Event (Map k a)
62−
63−-- Efficient one-to-many fanout
64−[ ] fanMap :: Ord k => Event (Map k a) -> EventSelector (Const2 k a)
65−[ ] fan :: GCompare k => Event (DMap k Identity) -> EventSelector k
66−[ ] select :: EventSelector k -> k a -> Event a
67−[ ] fanEither :: Event (Either a b) -> (Event a, Event b)
68−[ ] fanThese :: Event (These a b) -> (Event a, Event b)
69−
70−-- Event to Event via function that can sample current values
71−[ ] push :: (a -> m (Maybe b)) -> Event a -> Event b
72−[ ] pushAlways :: (a -> m b ) -> Event a -> Event b
73− -- Note supplied function operates in [H] context
74−
75−-- Split Event into next occurrence and all other future occurrences, as of now.
76−[H] headE :: Event a -> m (Event a)
77−[H] tailE :: Event a -> m (Event a)
78−[H] headTailE :: Event a -> m (Event a, Event a)
79−```
80−
81−## Functions producing Behavior
82−
83−```haskell
84−-- Trivial Behavior
85−[ ] constant :: a -> Behavior a
86−
87−-- Extract Behavior from Dynamic
88−[ ] current :: Dynamic a -> Behavior a
89−
90−-- Create Behavior with given initial value, updated when the Event fires.
91−[H] hold :: a -> Event a -> m (Behavior a)
92−
93−-- Transform Behavior to Behavior using function
94−[ ] fmap :: (a -> b) -> Behavior a -> Behavior b
95−[ ] ffor :: Behavior a -> (a -> b) -> Behavior b
96−[ ] <*> :: Behavior (a -> b) -> Behavior a -> Behavior b
97−[ ] >>= :: Behavior a -> (a -> Behavior b) -> Behavior b
98−[ ] <> :: Monoid a => Behavior a -> Behavior a -> Behavior a
99−-- ... plus many more due to typeclass membership
100−
101−-- Combine multiple behaviors via applicative instance
102−[ ] ffor2 :: Behavior a -> Behavior b -> (a -> b -> c) -> Behavior c
103−[ ] ffor3 :: Behavior a -> Behavior b -> Behavior c -> (a -> b -> c -> d) -> Behavior d
104−
105−-- Behavior to Behavior by sampling current values
106−[S] sample :: Behavior a -> m a
107−[ ] pull :: m a -> Behavior a
108− -- Note supplied value is in [S] context
109−```
110−
111−## Functions producing Dynamic
112−
113−```haskell
114−-- Trivial Dynamic
115−[ ] constDyn :: a -> Dynamic a
116−
117−-- Create Dynamic with given initial value, updated (various ways) when the Event fires.
118−[H] holdDyn :: a -> Event a -> m (Dynamic a)
119−[H] foldDyn :: (a -> b -> b ) -> b -> Event a -> m (Dynamic b)
120−[H] foldDynMaybe :: (a -> b -> Maybe b ) -> b -> Event a -> m (Dynamic b)
121−[H] foldDynM :: (a -> b -> m' b ) -> b -> Event a -> m (Dynamic b)
122−[H] foldDynMaybeM :: (a -> b -> m' (Maybe b)) -> b -> Event a -> m (Dynamic b)
123− -- Note m' supplies [H] context
124−
125−-- Initial value is 0; counts Event firings from now.
126−[H] count :: Num b => Event a -> m (Dynamic b)
127−-- Initial Bool value is supplied; toggles at each Event firing.
128−[H] toggle :: Bool -> Event a -> m (Dynamic Bool)
129−
130−-- Transform Dynamic to Dynamic using function
131−[ ] ffor :: Dynamic a -> (a -> b) -> Dynamic b
132−[ ] fmap :: (a -> b) -> Dynamic a -> Dynamic b
133−[ ] splitDynPure :: Dynamic (a, b) -> (Dynamic a, Dynamic b)
134−
135−-- Combine multiple Dynamics
136−[ ] mconcat :: Monoid a => [Dynamic a] -> Dynamic a
137−[ ] distributeDMapOverDynPure :: GCompare k => DMap (WrapArg Dynamic k) -> Dynamic (DMap k)
138−[ ] <*> :: Dynamic (a -> b) -> Dynamic a -> Dynamic b
139−[ ] >>= :: Dynamic a -> (a -> Dynamic b) -> Dynamic b
140−[ ] zipDynWith :: (a -> b -> c) -> Dynamic a -> Dynamic b -> Dynamic c
141−
142−-- Combine multiple dynamics via applicative instance
143−[ ] ffor2 :: Dynamic a -> Dynamic b -> (a -> b -> c) -> Dynamic c
144−[ ] ffor3 :: Dynamic a -> Dynamic b -> Dynamic c -> (a -> b -> c -> d) -> Dynamic d
145−
146−-- Efficient one-to-many fanout
147−[ ] demux :: Ord k => Dynamic k -> Demux k
148−[ ] demuxed :: Eq k => Demux k -> k -> Dynamic Bool
149−
150−-- Dynamic to Dynamic, removing updates w/o value change
151−[H] holdUniqDyn :: Eq a => Dynamic a -> m (Dynamic a)
152−[H] holdUniqDynBy :: (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
153−
154−-- Dynamic to identical Dynamic with debug trace. (Only prints if Dynamic is ultimately used.)
155−[ ] traceDyn :: Show a => String -> Dynamic a -> Dynamic a
156−[ ] traceDynWith :: (a -> String) -> Dynamic a -> Dynamic a
157−```
158−
159−## Flattening functions
160−
161−These functions flatten nested types such as Event-of-Event, Behavior-of-Event, Event-of-Behavior etc, removing the outer wrapper.
162−
163−For Events, the returned Event fires whenever the latest Event supplied by the wrapper fires. There are differences in how the functions handle *coincidences* -- situations where the old or new Event fires at the same instant that we switch from old to new. In some cases, the output Event tracks the old Event at the instant of switchover, while in other cases it tracks the new Event.
164−
165−```haskell
166−-- Flatten Behavior-of-Event to Event. Old Event is used during switchover.
167−[ ] switch :: Behavior (Event a) -> Event a
168−
169−-- Flatten Dynamic-of-Event to Event. New Event is used immediately.
170−[ ] switchDyn :: Dynamic (Event a) -> Event a
171−
172−-- Flatten Event-of-Event to Event that fires when both wrapper AND new Event fire.
173−[ ] coincidence :: Event (Event a) -> Event a
174−
175−-- Flatten Behavior-of-Behavior to Behavior. Behavior is an instance of Monad,
176−-- so the 'join' function from 'Control.Monad' suffices. The output of 'join' is
177−-- a Behavior whose value is equal to the current value of the current value of
178−-- the input.
179−[ ] join :: Behavior (Behavior a) -> Behavior a
180−
181−
182−-- Flatten Dynamic-of-Dynamic to Dynamic. New Dynamic is used immediately.
183−-- Output updated whenever inner OR outer Dynamic updates.
184−[ ] join :: Dynamic (Dynamic a) -> Dynamic a
185−[ ] joinDynThroughMap :: Ord k => Dynamic (Map k (Dynamic a)) -> Dynamic (Map k a)
186−
187−-- Analogous to 'hold': Create a Behavior that is initially identical to the
188−-- supplied Behavior. Updated to track a new Behavior whenever the Event fires.
189−[H] switcher :: Behavior a -> Event (Behavior a) -> m (Behavior a)
190−
191−-- Similar to above, for Events. Created Event initially tracks the first argument.
192−-- At switchover, the output Event immediately tracks the new Event.
193−[H] switchHold :: Event a -> Event (Event a) -> m (Event a)
194−```
195−
196−## Typeclasses to introspect and modify an FRP network.
197−
198−The functions mentioned above are used to create a static FRP network.
199−There are additional typeclasses that can be used to modify the FRP network, to have it interact with IO action, or to introspect the building of the network.
200−
201−Th typeclasses and their associated annotations include:
202−
203−- `PostBuild`
204− Fire an Event when an FRP network has been set up.
205− ```haskell
206− [B] -- Function runs in any monad supporting PostBuild
207− ```
208−
209−- `Adjustable`
210− Use Events to add or remove pieces of an FRP network.
211− ```haskell
212− [A] -- Function runs in any monad supporting Adjustable
213− ```
214−
215−- `TriggerEvent`
216− Create new externally-fired Events from within an FRP network.
217− ```haskell
218− [T] -- Function runs in any monad supporting TriggerEvent
219− ```
220−
221−- `PerformEvent`
222− Use Events to trigger IO actions and to collect their results.
223− ```haskell
224− [P] -- Function runs in any monad supporting PerformEvent
225− ```
226−
227−## Startup
228−
229−```haskell
230−-- One-shot Event that is triggered once the FRP network has been built
231−[B] getPostBuild :: m (Event ())
232−```
233−
234−## Collection management functions
235−
236−```haskell
237−-- Turn a Dynamic key/value map into a set of dynamically-changing widgets.
238−[H,A,B] listWithKey :: Ord k =>
239− Dynamic (Map k v) -> (k -> Dynamic v -> m a ) -> m (Dynamic (Map k a))
240−
241−-- Same as above where the widget constructor doesn't care about the key.
242−[H,A,B] list :: Ord k =>
243− Dynamic (Map k v) -> ( Dynamic v -> m a ) -> m (Dynamic (Map k a))
244−
245−-- Even simpler version where there are no keys and we just use a list.
246−[H,A,B] simpleList ::
247− Dynamic [v] -> ( Dynamic v -> m a ) -> m (Dynamic [a])
248−
249−-- Like listWithKey specialized for widgets returning (Event a).
250−[H,A,B] listViewWithKey :: Ord k =>
251− Dynamic (Map k v) -> (k -> Dynamic v -> m (Event a)) -> m (Event (Map k a))
252−
253−-- Create a dynamically-changing set of widgets, one of which is selected at any time.
254−[H,A,B] selectViewListWithKey_ :: Ord k => Dynamic k ->
255− Dynamic (Map k v) -> (k -> Dynamic v -> Dynamic Bool -> m (Event a)) -> m (Event k)
256−
257−-- Same as listWithKey, but takes initial values and an updates Event instead of a Dynamic.
258−[H,A] listWithKeyShallowDiff :: Ord k =>
259− Map k v -> Event (Map k (Maybe v)) -> (k -> v -> Event v -> m a) -> m (Dynamic (Map k a))
260−```
261−
262−## Creating new events from within an FRP network.
263−
264−```haskell
265−-- Create a new Event and a function that will cause the Event to fire, from within an FRP network
266−[T] newTriggerEvent :: m (Event a, a -> IO ())
267−```
268−
269−## Connecting to the real world (I/O)
270−
271−```haskell
272−-- Run side-effecting actions in Event when it occurs; returned Event contains
273−-- results. Side effects run in the (Performable m) monad which is associated with
274−-- the (PerformEvent t m) typeclass constraint.
275−-- This allows for working with IO when a ((MonadIO (Performable m)) constraint is available.
276−[P] performEvent :: Event (Performable m a ) -> m (Event a)
277−
278−-- Just run side-effects; no return Event
279−[P] performEvent_ :: Event (Performable m ()) -> m ()
280−
281−-- Actions run asynchronously; actions are given a callback to send return values
282−[P,T] performEventAsync :: Event ((a -> IO ()) -> Performable m ()) -> m (Event a)
283−```
284−
285−### Time
286−
287−```haskell
288−-- Create Event at given interval with given basis time.
289−[P,T] tickLossy :: NominalDiffTime -> UTCTime -> m (Event t TickInfo)
290−
291−-- Delay an Event's occurrences by a given amount in seconds.
292−[P,T] delay :: NominalDiffTime -> Event t a -> m (Event t a)
293−```
294−
295−## Networks
296−
297−```haskell
298−-- Functions from Reflex.Network used to deal with Dynamics/Events carrying (m a)
299−
300−-- Given a Dynamic of network-creating actions, create a network that is recreated whenever the Dynamic updates.
301−-- The returned Event of network results occurs when the Dynamic does. Note: Often, the type a is an Event,
302−-- in which case the return value is an Event-of-Events that would typically be flattened (via switchHold).
303−[P,A] networkView :: Dynamic (m a) -> m (Event a)
304−
305−-- Given an initial network and an Event of network-creating actions, create a network that is recreated whenever the
306−-- Event fires. The returned Dynamic of network results occurs when the Event does. Note: Often, the type a is an
307−-- Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
308−[H,A] networkHold :: m a -> Event (m a) -> m (Dynamic a)
309−
310−-- Render a placeholder network to be shown while another network is not yet done building
311−[P,A] untilReady :: m a -> m b -> m (a, Event b)
README.md+42−14
@@ -1,24 +1,52 @@
1−## [Reflex](https://reflex-frp.org/)
2−### Practical Functional Reactive Programming
1+# patch
32
4−Reflex is a fully-deterministic, higher-order Functional Reactive Programming (FRP) interface and an engine that efficiently implements that interface.
3+[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/patch.svg)](https://hackage.haskell.org/package/patch) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/patch/badge)](https://matrix.hackage.haskell.org/#/package/patch) [![Travis CI](https://api.travis-ci.org/reflex-frp/patch.svg?branch=develop)](https://travis-ci.org/reflex-frp/patch) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/reflex-frp/patch/LICENSE)
54
6−[Reflex-DOM](https://github.com/reflex-frp/reflex-dom) is a framework built on Reflex that facilitates the development of web pages, including highly-interactive single-page apps.
5+Data structures for describing changes to other data structures.
76
8−A summary of Reflex functions is available in the [quick reference](Quickref.md).
7+A `Patch` type represents a kind of change made to a data structure.
98
10−**Visit https://reflex-frp.org/ for more information, tutorials, documentation and [examples](https://examples.reflex-frp.org/).**
9+```haskell
10+class Patch p where
11+ type PatchTarget p :: *
12+ -- | Apply the patch p a to the value a. If no change is needed, return
13+ -- 'Nothing'.
14+ apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
15+```
1116
12−### Resources
13−[Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
17+## Patching Maps
18+For example, `Data.Patch.Map` defines the `PatchMap` type which can be used to patch `Map`s. A `PatchMap` represents updates to a `Map` that can insert, remove, or replace items in the `Map`. In this example, the `Map` is the `PatchTarget` and the `PatchMap` is the `Patch`. Keep in mind that there are many other possible `Patch`es that can be applied to a `Map` (i.e., `Map` can be the `PatchTarget` for many different `Patch` instances).
1419
15−[/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
20+`PatchMap` is defined as:
1621
17−[hackage](https://hackage.haskell.org/package/reflex)
22+```haskell
23+newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
24+```
1825
19−[irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
26+The `Maybe` around the value is used to represent insertion/updates or deletion of the element at a given key.
2027
21−### Hacking
28+Its `Patch` instance begins with:
2229
23−Use the `./scripts/hack-on reflex` script in [Reflex Platform](https://github.com/reflex-frp/reflex-platform) to checkout the source code of `reflex` locally in `reflex-platform/reflex` directory.
24−Then do modifications to the source in place, and use the `./try-reflex` or `./scripts/work-on` scripts to create the shell to test your changes.
30+```haskell
31+instance Ord k => Patch (PatchMap k v) where
32+ type PatchTarget (PatchMap k v) = Map k v
33+ ...
34+```
35+
36+When a `PatchMap` is applied to its `PatchTarget`, the following changes can occur:
37+
38+- If the key is present in the `Patch` and the `PatchTarget`...
39+
40+ - And the `Patch` value at that key is `Nothing`: delete that key from the `PatchTarget`.
41+
42+ - And the `Patch` value at that key is `Just x`: update the value at that key in the `PatchTarget` to `x`.
43+
44+- If the key is present in the `Patch` and not present in the `PatchTarget`...
45+
46+ - And the `Patch` value at that key is `Nothing`: do nothing because we're trying to delete a key that doesn't exist in the target in the first place.
47+
48+ - And the `Patch` value at that key is `Just x`: insert the key and the value `x` into the `PatchTarget`
49+
50+- If the key is *not* present in the `Patch` but present in the `PatchTarget`: do nothing.
51+
52+There are, of course, more complicated ways of patching maps involving, for example, moving values from one key to another. You can find the code for that in `Data.Patch.PatchMapWithMove`. Note that the `PatchTarget` type associated with the `PatchMapWithMove` patch instance is still `Map k v`!
bench/Main.hsdeleted−110
@@ -1,110 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−{-# LANGUAGE TupleSections #-}
5−{-# LANGUAGE TypeFamilies #-}
6−
7−-- The instance for NFData (TVar a) is an orphan, but necessary here
8−{-# OPTIONS_GHC -fno-warn-orphans #-}
9−
10−module Main where
11−
12−import Control.Concurrent.STM
13−import Control.DeepSeq
14−import Control.Exception (evaluate)
15−import Control.Monad.Identity
16−import Control.Monad.IO.Class
17−import Criterion.Main
18−import Data.Dependent.Map (DMap)
19−import qualified Data.Dependent.Map as DMap
20−import Data.Dependent.Sum
21−import Data.Functor.Misc
22−import Data.IORef
23−import Data.Maybe (fromJust)
24−import Reflex
25−import Reflex.Host.Class
26−
27−main :: IO ()
28−main = defaultMain
29− [ bgroup "micro" micros ]
30−
31−#if !(MIN_VERSION_deepseq(1,4,2))
32−instance NFData (IORef a) where
33− rnf x = seq x ()
34−#endif
35−
36−instance NFData (TVar a) where
37− rnf x = seq x ()
38−
39−newtype WHNF a = WHNF a
40−instance NFData (WHNF a) where
41− rnf (WHNF a) = seq a ()
42−
43−withSetup :: NFData b => String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
44−withSetup name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
45− bench name . nfIO $ runSpiderHost (action a)
46−
47−withSetupWHNF :: String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
48−withSetupWHNF name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
49− bench name . whnfIO $ runSpiderHost (action a)
50−
51−micros :: [Benchmark]
52−micros =
53− [ bench "newIORef" $ whnfIO $ void $ newIORef ()
54− , env (newIORef (42 :: Int)) (bench "readIORef" . whnfIO . readIORef)
55− , bench "newTVar" $ whnfIO $ void $ newTVarIO ()
56− , env (newTVarIO (42 :: Int)) (bench "readTVar" . whnfIO . readTVarIO)
57− , bench "newEventWithTrigger" $ whnfIO . void $ runSpiderHost $ newEventWithTrigger $
58− \trigger -> return () <$ evaluate trigger
59− , bench "newEventWithTriggerRef" $ whnfIO . void $ runSpiderHost newEventWithTriggerRef
60− , withSetupWHNF "subscribeEvent" newEventWithTriggerRef $ subscribeEvent . fst
61− , withSetupWHNF "subscribeSwitch"
62− (join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)
63− (subscribeEvent . switch)
64− , withSetupWHNF "subscribeMerge(1)" (setupMerge 1) $ \(ev,_) -> subscribeEvent ev
65− , withSetupWHNF "subscribeMerge(100)" (setupMerge 100) (subscribeEvent . fst)
66− , withSetupWHNF "subscribeMerge(10000)" (setupMerge 10000) (subscribeEvent . fst)
67− , bench "runHostFrame" $ whnfIO $ runSpiderHost $ runHostFrame $ return ()
68− , withSetupWHNF "fireEventsAndRead(single/single)"
69− (newEventWithTriggerRef >>= subscribePair)
70− (\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)
71− , withSetupWHNF "fireEventsOnly"
72− (newEventWithTriggerRef >>= subscribePair)
73− (\(_, trigger) -> do
74− key <- fromJust <$> liftIO (readIORef trigger)
75− fireEvents [key :=> Identity (42 :: Int)])
76− , withSetupWHNF "fireEventsAndRead(head/merge1)"
77− (setupMerge 1 >>= subscribePair)
78− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
79− , withSetupWHNF "fireEventsAndRead(head/merge100)"
80− (setupMerge 100 >>= subscribePair)
81− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
82− , withSetupWHNF "fireEventsAndRead(head/merge10000)"
83− (setupMerge 10000 >>= subscribePair)
84− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
85− , withSetupWHNF "fireEventsOnly(head/merge100)"
86− (setupMerge 100 >>= subscribePair)
87− (\(_, t:_) -> do
88− key <- fromJust <$> liftIO (readIORef t)
89− fireEvents [key :=> Identity (42 :: Int)])
90− , withSetupWHNF "hold" newEventWithTriggerRef $ \(ev, _) -> hold (42 :: Int) ev
91− , withSetupWHNF "sample" (newEventWithTriggerRef >>= hold (42 :: Int) . fst) sample
92− ]
93−
94−setupMerge :: Int
95− -> SpiderHost Global ( Event (SpiderTimeline Global) (DMap (Const2 Int a) Identity)
96− , [IORef (Maybe (EventTrigger Spider a))]
97− )
98−setupMerge num = do
99− (evs, triggers) <- unzip <$> replicateM num newEventWithTriggerRef
100− let !m = DMap.fromList [Const2 i :=> v | (i,v) <- zip [0..] evs]
101− pure (merge m, triggers)
102−
103−subscribePair :: (Event (SpiderTimeline Global) a, b) -> SpiderHost Global (EventHandle (SpiderTimeline Global) a, b)
104−subscribePair (ev, b) = (,b) <$> subscribeEvent ev
105−
106−fireAndRead :: IORef (Maybe (EventTrigger (SpiderTimeline Global) a)) -> a -> EventHandle (SpiderTimeline Global) b
107− -> SpiderHost Global (Maybe b)
108−fireAndRead trigger val subd = do
109− key <- fromJust <$> liftIO (readIORef trigger)
110− fireEventsAndRead [key :=> Identity val] $ readEvent subd >>= sequence
bench/RunAll.hsdeleted−157
@@ -1,157 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE ForeignFunctionInterface #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE PatternSynonyms #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TemplateHaskell #-}
13−{-# LANGUAGE TupleSections #-}
14−{-# LANGUAGE TypeSynonymInstances #-}
15−{-# LANGUAGE ViewPatterns #-}
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−
18−module Main where
19−
20−import Criterion.Main
21−import Criterion.Types
22−
23−import Reflex
24−import Reflex.Host.Class
25−
26−import Reflex.Plan.Reflex
27−import Reflex.TestPlan
28−
29−import qualified Reflex.Bench.Focused as Focused
30−import Reflex.Spider.Internal (SpiderEventHandle)
31−
32−import Control.Applicative
33−import Control.DeepSeq (NFData (..))
34−
35−import Prelude
36−import System.IO
37−import System.Mem
38−
39−import Control.Arrow
40−import Control.Concurrent
41−import Control.Concurrent.STM
42−import Control.Exception
43−import Control.Monad
44−import Control.Monad.Trans
45−import Data.Bool
46−import Data.Function
47−import Data.Int
48−import Data.IORef
49−import Data.Monoid
50−import Data.Time.Clock
51−import Debug.Trace.LocationTH
52−import GHC.Stats
53−import System.Environment
54−import System.Mem.Weak
55−import System.Process
56−import Text.Read
57−
58−import Unsafe.Coerce
59−
60−import Data.Map (Map)
61−import qualified Data.Map as Map
62−
63−type MonadReflexHost' t m = (MonadReflexHost t m, MonadIORef m, MonadIORef (HostFrame t))
64−
65−
66−setupFiring :: (MonadReflexHost t m, MonadIORef m) => Plan t (Event t a) -> m (EventHandle t a, Schedule t)
67−setupFiring p = do
68− (e, s) <- runPlan p
69− h <- subscribeEvent e
70− return (h, s)
71−
72−-- Hack to avoid the NFData constraint for EventHandle which is a synonym
73−newtype Ignore a = Ignore a
74−instance NFData (Ignore a) where
75− rnf !_ = ()
76−
77−instance NFData (SpiderEventHandle x a) where
78− rnf !_ = ()
79−
80−instance NFData (Behavior t a) where
81− rnf !_ = ()
82−
83−instance NFData (Firing t) where
84− rnf !_ = ()
85−
86−-- Measure the running time
87−benchFiring :: forall t m. (MonadReflexHost' t m, MonadSample t m) => (forall a. m a -> IO a) -> TestCase -> Int -> IO ()
88−benchFiring runHost tc n = runHost $ do
89− let runIterations :: m a -> m ()
90− runIterations test = replicateM_ (10*n) $ do
91− result <- test
92− liftIO $ evaluate result
93− case tc of
94− TestE p -> do
95− (h, s) <- setupFiring p
96− runIterations $ readSchedule_ s $ readEvent' h
97− TestB p -> do
98− (b, s) <- runPlan p
99− runIterations $ readSchedule_ (makeDense s) $ sample b
100−
101−waitForFinalizers :: IO ()
102−waitForFinalizers = do
103− performGC
104− x <- getCurrentTime
105− isFinalized <- newIORef False
106− mkWeakPtr x $ Just $ writeIORef isFinalized True
107− performGC
108− fix $ \loop -> do
109− f <- readIORef isFinalized
110− unless f $ do
111− threadDelay 1
112− loop
113−
114−benchmarks :: [(String, Int -> IO ())]
115−benchmarks = implGroup "spider" runSpiderHost cases
116− where
117− implGroup :: (MonadReflexHost' t m, MonadSample t m) => String -> (forall a. m a -> IO a) -> [(String, TestCase)] -> [(String, Int -> IO ())]
118− implGroup name runHost = group name . fmap (second (benchFiring runHost))
119− group name = fmap $ first ((name <> "/") <>)
120− sub n frames = group ("subscribing " ++ show (n, frames)) $ Focused.subscribing n frames
121− firing n = group ("firing " <> show n) $ Focused.firing n
122− merging n = group ("merging " <> show n) $ Focused.merging n
123− dynamics n = group ("dynamics " <> show n) $ Focused.dynamics n
124− cases = concat
125− [ sub 100 40
126− , dynamics 100
127− , dynamics 1000
128− , firing 1000
129− , firing 10000
130− , merging 10
131− , merging 50
132− , merging 100
133− , merging 200
134− ]
135−
136−pattern RunTestCaseFlag = "--run-test-case"
137−
138−spawnBenchmark :: String -> Benchmark
139−spawnBenchmark name = bench name . toBenchmarkable $ \n -> do
140− self <- getExecutablePath
141− callProcess self [RunTestCaseFlag, name, show n, "+RTS", "-N1"]
142−
143−foreign import ccall unsafe "myCapabilityHasOtherRunnableThreads" myCapabilityHasOtherRunnableThreads :: IO Bool
144−
145−main :: IO ()
146−main = do
147− args <- getArgs
148− case args of
149− RunTestCaseFlag : t -> case t of
150− [name, readMaybe -> Just count] -> do
151− case lookup name benchmarks of
152− Just testCase -> testCase count
153− performGC
154− fix $ \loop -> bool (return ()) (yield >> loop) =<< myCapabilityHasOtherRunnableThreads
155− return ()
156− _ -> $failure "--run-test-case: expected test name and iteration count to follow"
157− _ -> defaultMainWith (defaultConfig { timeLimit = 20, csvFile = Just "dmap-original.csv", reportFile = Just "report.html" }) $ fmap (spawnBenchmark . fst) benchmarks
cabal.projectnew file+1
@@ -0,0 +1 @@
1+packages: .
default.nixdeleted−40
@@ -1,40 +0,0 @@
1−{ mkDerivation, ghc, base, bifunctors, containers, deepseq
2−, dependent-map, dependent-sum, exception-transformers
3−, haskell-src-exts, haskell-src-meta, hlint, lens, MemoTrie
4−, monad-control, mtl, primitive, random, ref-tf
5−, semigroupoids , semigroups, split, stdenv, stm, syb
6−, template-haskell , these, time, transformers
7−, transformers-compat, unbounded-delays, prim-uniq
8−, data-default, filepath, directory, filemanip, ghcjs-base
9−, monoidal-containers, witherable, constraints-extras
10−, useTemplateHaskell ? true
11−}:
12−mkDerivation {
13− pname = "reflex";
14− version = "0.6.1";
15− src = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [ ".git" "dist" ])) ./.;
16− libraryHaskellDepends = [
17− base bifunctors containers dependent-map dependent-sum
18− exception-transformers lens
19− MemoTrie monad-control mtl primitive ref-tf semigroupoids
20− semigroups stm syb template-haskell these transformers
21− transformers-compat prim-uniq
22− base bifunctors containers deepseq dependent-map dependent-sum
23− mtl ref-tf split transformers data-default
24− random time unbounded-delays monoidal-containers witherable
25− constraints-extras
26− ] ++ (if ghc.isGhcjs or false then [
27− ghcjs-base
28− ] else []) ++ (if !useTemplateHaskell then [] else [
29− haskell-src-exts haskell-src-meta
30− ]);
31− testHaskellDepends = if ghc.isGhcjs or false then [] else [
32− hlint filepath directory filemanip
33− ];
34− configureFlags = if useTemplateHaskell then [] else [
35− "-f-use-template-haskell"
36− ];
37− homepage = "https://github.com/reflex-frp/reflex";
38− description = "Higher-order Functional Reactive Programming";
39− license = stdenv.lib.licenses.bsd3;
40−}
dep/reflex-platform/default.nixnew file+8
@@ -0,0 +1,8 @@
1+# DO NOT HAND-EDIT THIS FILE
2+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3+ if !fetchSubmodules && !private then builtins.fetchTarball {
4+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5+ } else (import <nixpkgs> {}).fetchFromGitHub {
6+ inherit owner repo rev sha256 fetchSubmodules private;
7+ };
8+in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))
dep/reflex-platform/github.jsonnew file+8
@@ -0,0 +1,8 @@
1+{
2+ "owner": "reflex-frp",
3+ "repo": "reflex-platform",
4+ "branch": "master",
5+ "private": false,
6+ "rev": "c9d11db1b98855fe8ab24a3ff6a5dbe0ad902ad9",
7+ "sha256": "0sfzkqdvyah5mwvmli0wq1nl0b8cvk2cmfgfy4rz57wv42x3099y"
8+}
hydra.jsondeleted−29
@@ -1,29 +0,0 @@
1−{
2− "enabled": 1,
3− "hidden": true,
4− "description": "Jobsets",
5− "nixexprinput": "src",
6− "nixexprpath": "jobsets.nix",
7− "checkinterval": 300,
8− "schedulingshares": 100,
9− "enableemail": false,
10− "emailoverride": "",
11− "keepnr": 10,
12− "inputs": {
13− "src": {
14− "type": "git",
15− "value": "https://github.com/reflex-frp/reflex.git develop",
16− "emailresponsible": false
17− },
18− "nixpkgs": {
19− "type": "git",
20− "value": "https://github.com/NixOS/nixpkgs-channels nixos-unstable",
21− "emailresponsible": false
22− },
23− "prs": {
24− "type": "githubpulls",
25− "value": "reflex-frp reflex",
26− "emailresponsible": false
27− }
28− }
29−}
jobsets.nixdeleted−70
@@ -1,70 +0,0 @@
1−{ prs }:
2−
3−let
4− pkgs = (import ./reflex-platform.nix {}).nixpkgs;
5− mkFetchGithub = value: {
6− inherit value;
7− type = "git";
8− emailresponsible = false;
9− };
10−in
11−with pkgs.lib;
12−let
13− defaults = jobs: {
14− inherit (jobs) description;
15− enabled = 1;
16− hidden = false;
17− keepnr = 10;
18− schedulingshares = 100;
19− checkinterval = 120;
20− enableemail = false;
21− emailoverride = "";
22− nixexprinput = "reflex";
23− nixexprpath = "release.nix";
24− inputs = jobs.inputs // {
25− nixpkgs = {
26− type = "git";
27− value = "https://github.com/NixOS/nixpkgs-channels nixos-unstable";
28− emailresponsible = false;
29− };
30− config = {
31− type = "nix";
32− value = "{ android_sdk.accept_license = true; }";
33− emailresponsible = false;
34− };
35− };
36− };
37− branchJobset = branch: defaults {
38− description = "reflex-${branch}";
39− inputs = {
40− reflex = {
41− value = "https://github.com/reflex-frp/reflex ${branch}";
42− type = "git";
43− emailresponsible = false;
44− };
45− };
46− };
47− makePr = num: info: {
48− name = "reflex-pr-${num}";
49− value = defaults {
50− description = "#${num}: ${info.title}";
51− inputs = {
52− reflex = {
53− #NOTE: This should really use "pull/${num}/merge"; however, GitHub's
54− #status checks only operate on PR heads. This creates a race
55− #condition, which can currently only be solved by requiring PRs to be
56− #up to date before they're merged. See
57− #https://github.com/isaacs/github/issues/1002
58− value = "https://github.com/reflex-frp/reflex pull/${num}/head";
59− type = "git";
60− emailresponsible = false;
61− };
62− };
63− };
64− };
65− processedPrs = mapAttrs' makePr (builtins.fromJSON (builtins.readFile prs));
66− jobsetsAttrs = processedPrs //
67− genAttrs ["develop"] branchJobset;
68−in {
69− jobsets = pkgs.writeText "spec.json" (builtins.toJSON jobsetsAttrs);
70−}
patch.cabalnew file+100
@@ -0,0 +1,100 @@
1+Name: patch
2+Version: 0.0.5.0
3+Synopsis: Data structures for describing changes to other data structures.
4+Description:
5+ Data structures for describing changes to other data structures.
6+ .
7+ In this library, a patch is something which can be applied, analogous to a
8+ function, and which distinguishes returning the argument it was provided from
9+ returning something else.
10+License: BSD3
11+License-file: LICENSE
12+Author: Ryan Trinkle
13+Maintainer: maintainer@obsidian.systems
14+Stability: Experimental
15+Category: FRP
16+Build-type: Simple
17+Cabal-version: >=1.10
18+homepage: https://obsidian.systems
19+bug-reports: https://github.com/reflex-frp/patch/issues
20+extra-source-files:
21+ README.md
22+ ChangeLog.md
23+
24+tested-with:
25+ GHC ==8.0.2 || ==8.2.2 || ==8.4.4 || ==8.6.5 || ==8.8.1
26+ GHCJS ==8.4
27+
28+flag split-these
29+ description: Use split these/semialign packages
30+ manual: False
31+ default: True
32+
33+library
34+ hs-source-dirs: src
35+ default-language: Haskell2010
36+ build-depends: base >= 4.9 && < 4.15
37+ , constraints-extras >= 0.3 && < 0.4
38+ , containers >= 0.6 && < 0.7
39+ , dependent-map >= 0.3 && < 0.5
40+ , dependent-sum >= 0.6 && < 0.8
41+ , lens >= 4.7 && < 5
42+ , semigroupoids >= 4.0 && < 6
43+ , transformers >= 0.5.6.0 && < 0.6
44+ , witherable >= 0.3 && < 0.5
45+
46+ if impl(ghc < 8.6) -- really, if base < 8.12
47+ build-depends: base-orphans >= 0.8 && < 0.9
48+
49+ exposed-modules: Data.Functor.Misc
50+ , Data.Monoid.DecidablyEmpty
51+ , Data.Patch
52+ , Data.Patch.Class
53+ , Data.Patch.DMap
54+ , Data.Patch.DMapWithMove
55+ , Data.Patch.IntMap
56+ , Data.Patch.Map
57+ , Data.Patch.MapWithMove
58+ , Data.Patch.MapWithPatchingMove
59+ , Data.Semigroup.Additive
60+
61+ ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs
62+ default-extensions: PolyKinds
63+
64+ if flag(split-these)
65+ build-depends: these >= 1 && <1.2
66+ , semialign >=1 && <1.2
67+ , monoidal-containers >= 0.6 && < 0.7
68+ else
69+ build-depends: these >= 0.4 && <0.9
70+ , monoidal-containers == 0.4.0.0
71+
72+test-suite tests
73+ default-language: Haskell2010
74+ type: exitcode-stdio-1.0
75+ main-is: tests.hs
76+ hs-source-dirs: test
77+ build-depends: base
78+ , patch
79+ , containers
80+ , hedgehog
81+ , HUnit
82+ if impl(ghcjs)
83+ buildable: False
84+
85+test-suite hlint
86+ default-language: Haskell2010
87+ type: exitcode-stdio-1.0
88+ main-is: hlint.hs
89+ hs-source-dirs: test
90+ build-depends: base
91+ , directory
92+ , filepath
93+ , filemanip
94+ , hlint (< 2.1 || >= 2.2.2) && < 3.3
95+ if impl(ghcjs)
96+ buildable: False
97+
98+source-repository head
99+ type: git
100+ location: https://github.com/reflex-frp/patch
reflex-platform.nixdeleted−8
@@ -1,8 +0,0 @@
1−let
2− reflex-platform-src = (import <nixpkgs> {}).fetchFromGitHub {
3− owner = "reflex-frp";
4− repo = "reflex-platform";
5− rev = "384cd850f3adf1d404bced2424b5f6efb0f415f2";
6− sha256 = "1ws77prqx8khmp8j6br1ij4k2v4dlgv170r9fmg0p1jivfbn8y9d";
7− };
8−in import reflex-platform-src
reflex.cabaldeleted−370
@@ -1,370 +0,0 @@
1−Name: reflex
2−Version: 0.6.1
3−Synopsis: Higher-order Functional Reactive Programming
4−Description: Reflex is a high-performance, deterministic, higher-order Functional Reactive Programming system
5−License: BSD3
6−License-file: LICENSE
7−Author: Ryan Trinkle
8−Maintainer: ryan.trinkle@gmail.com
9−Stability: Experimental
10−Category: FRP
11−Build-type: Simple
12−Cabal-version: >=1.9.2
13−homepage: https://reflex-frp.org
14−bug-reports: https://github.com/reflex-frp/reflex/issues
15−extra-source-files:
16− README.md
17− Quickref.md
18− ChangeLog.md
19−
20−flag use-reflex-optimizer
21− description: Use the GHC plugin Reflex.Optimizer on some of the modules in the package. This is still experimental.
22− default: False
23− manual: True
24−
25−flag use-template-haskell
26− description: Use template haskell to generate lenses
27− default: True
28− manual: True
29−
30−flag debug-trace-events
31− description: Add instrumentation that outputs the stack trace of the definition of an event whenever it is subscribed to. Warning: It is very slow!
32− default: False
33− manual: True
34−
35−flag fast-weak
36− description: Use the primitive implementation of FastWeak in GHCJS; note that this requires GHCJS to be built with FastWeak and FastWeakBag present in the RTS, which is not the default
37− default: False
38− manual: True
39−
40−library
41− hs-source-dirs: src
42− build-depends:
43− MemoTrie == 0.6.*,
44− base >= 4.9 && < 4.13,
45− bifunctors >= 5.2 && < 5.6,
46− comonad,
47− constraints-extras,
48− containers >= 0.5 && < 0.7,
49− data-default >= 0.5 && < 0.8,
50− dependent-map >= 0.2.4 && < 0.4,
51− exception-transformers == 0.4.*,
52− lens >= 4.7 && < 5,
53− monad-control >= 1.0.1 && < 1.1,
54− monoidal-containers == 0.4.*,
55− mtl >= 2.1 && < 2.3,
56− prim-uniq >= 0.1.0.1 && < 0.2,
57− primitive >= 0.5 && < 0.7,
58− random == 1.1.*,
59− ref-tf == 0.4.*,
60− reflection == 2.1.*,
61− semigroupoids >= 4.0 && < 6,
62− semigroups >= 0.16 && < 0.19,
63− stm >= 2.4 && < 2.6,
64− syb >= 0.5 && < 0.8,
65− these >= 0.4 && < 0.9,
66− time >= 1.4 && < 1.9,
67− transformers >= 0.2,
68− transformers-compat >= 0.3,
69− unbounded-delays >= 0.1.0.0 && < 0.2,
70− witherable >= 0.2 && < 0.4
71−
72− exposed-modules:
73− Data.AppendMap,
74− Data.FastMutableIntMap,
75− Data.FastWeakBag,
76− Data.Functor.Misc,
77− Data.Map.Misc,
78− Data.WeakBag,
79− Reflex,
80− Reflex.Class,
81− Reflex.Adjustable.Class,
82− Reflex.BehaviorWriter.Base,
83− Reflex.BehaviorWriter.Class,
84− Reflex.Collection,
85− Reflex.Dynamic,
86− Reflex.Dynamic.Uniq,
87− Reflex.DynamicWriter,
88− Reflex.DynamicWriter.Base,
89− Reflex.DynamicWriter.Class,
90− Reflex.EventWriter,
91− Reflex.EventWriter.Base,
92− Reflex.EventWriter.Class,
93− Reflex.FastWeak,
94− Reflex.FunctorMaybe,
95− Reflex.Host.Class,
96− Reflex.Network,
97− Reflex.NotReady.Class,
98− Reflex.Patch,
99− Reflex.Patch.Class,
100− Reflex.Patch.DMap,
101− Reflex.Patch.DMapWithMove,
102− Reflex.Patch.IntMap,
103− Reflex.Patch.Map,
104− Reflex.Patch.MapWithMove,
105− Reflex.Patch.MapWithMove2,
106− Reflex.PerformEvent.Base,
107− Reflex.PerformEvent.Class,
108− Reflex.PostBuild.Base,
109− Reflex.PostBuild.Class,
110− Reflex.Profiled,
111− Reflex.Pure,
112− Reflex.Query.Base,
113− Reflex.Query.Class,
114− Reflex.Requester.Base,
115− Reflex.Requester.Class,
116− Reflex.Spider,
117− Reflex.Spider.Internal,
118− Reflex.Time,
119− Reflex.TriggerEvent.Base,
120− Reflex.TriggerEvent.Class,
121− Reflex.Widget.Basic,
122− Reflex.Workflow
123−
124− ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs -funbox-strict-fields -O2 -fspecialise-aggressively
125−
126− if flag(debug-trace-events)
127− cpp-options: -DDEBUG_TRACE_EVENTS
128− build-depends: bytestring
129−
130− if flag(use-reflex-optimizer)
131− cpp-options: -DUSE_REFLEX_OPTIMIZER
132− build-depends: ghc
133− exposed-modules: Reflex.Optimizer
134−
135− if flag(use-template-haskell)
136− cpp-options: -DUSE_TEMPLATE_HASKELL
137− build-depends:
138− dependent-sum >= 0.3 && < 0.7,
139− haskell-src-exts >= 1.16 && < 1.21,
140− haskell-src-meta >= 0.6 && < 0.9,
141− template-haskell >= 2.9 && < 2.15
142− exposed-modules:
143− Reflex.Dynamic.TH
144− other-extensions: TemplateHaskell
145− else
146− build-depends:
147− dependent-sum >= 0.4 && < 0.7
148−
149− if flag(fast-weak) && impl(ghcjs)
150− cpp-options: -DGHCJS_FAST_WEAK
151−
152− if impl(ghcjs)
153− build-depends: ghcjs-base
154−
155−test-suite semantics
156− type: exitcode-stdio-1.0
157− main-is: semantics.hs
158− hs-source-dirs: test
159− ghc-options: -O2 -Wall -rtsopts
160− build-depends:
161− base,
162− bifunctors,
163− containers,
164− deepseq >= 1.3 && < 1.5,
165− dependent-map,
166− dependent-sum,
167− mtl,
168− ref-tf,
169− reflex,
170− split,
171− transformers >= 0.3
172− other-modules:
173− Reflex.Bench.Focused
174− Reflex.Plan.Pure
175− Reflex.Plan.Reflex
176− Reflex.Test
177− Reflex.Test.Micro
178− Reflex.TestPlan
179−
180−test-suite CrossImpl
181− type: exitcode-stdio-1.0
182− main-is: Reflex/Test/CrossImpl.hs
183− hs-source-dirs: test
184− ghc-options: -O2 -Wall -rtsopts
185− build-depends:
186− base,
187− containers,
188− dependent-map,
189− dependent-sum,
190− deepseq >= 1.3 && < 1.5,
191− mtl,
192− transformers,
193− ref-tf,
194− reflex
195− other-modules:
196− Reflex.Test
197− Reflex.TestPlan
198− Reflex.Plan.Reflex
199− Reflex.Plan.Pure
200−
201−test-suite hlint
202− type: exitcode-stdio-1.0
203− main-is: hlint.hs
204− hs-source-dirs: test
205− build-depends: base
206− , directory
207− , filepath
208− , filemanip
209− , hlint
210− if impl(ghcjs)
211− buildable: False
212−
213−test-suite EventWriterT
214− type: exitcode-stdio-1.0
215− main-is: EventWriterT.hs
216− hs-source-dirs: test
217− build-depends: base
218− , containers
219− , deepseq >= 1.3 && < 1.5
220− , dependent-map
221− , dependent-sum
222− , lens
223− , mtl
224− , these
225− , transformers
226− , reflex
227− , ref-tf
228− other-modules:
229− Reflex.Test
230− Reflex.TestPlan
231− Reflex.Plan.Reflex
232− Reflex.Plan.Pure
233− Test.Run
234−
235−test-suite RequesterT
236− type: exitcode-stdio-1.0
237− main-is: RequesterT.hs
238− hs-source-dirs: test
239− build-depends: base
240− , containers
241− , deepseq >= 1.3 && < 1.5
242− , dependent-sum
243− , dependent-map
244− , lens
245− , mtl
246− , these
247− , transformers
248− , reflex
249− , ref-tf
250− other-modules:
251− Reflex.TestPlan
252− Reflex.Plan.Pure
253−
254−test-suite QueryT
255− type: exitcode-stdio-1.0
256− main-is: QueryT.hs
257− hs-source-dirs: test
258− build-depends: base
259− , containers
260− , dependent-map
261− , dependent-sum
262− , deepseq >= 1.3 && < 1.5
263− , lens
264− , monoidal-containers
265− , mtl
266− , ref-tf
267− , reflex
268− , semigroups
269− , these
270− , transformers
271− other-modules:
272− Test.Run
273− Reflex.TestPlan
274− Reflex.Plan.Reflex
275− Reflex.Plan.Pure
276−
277−test-suite GC-Semantics
278− type: exitcode-stdio-1.0
279− main-is: GC.hs
280− hs-source-dirs: test
281− build-depends: base
282− , containers
283− , dependent-sum
284− , dependent-map
285− , deepseq >= 1.3 && < 1.5
286− , mtl
287− , these
288− , transformers
289− , reflex
290− , ref-tf
291− if impl(ghc < 8)
292− build-depends: semigroups
293− other-modules:
294− Reflex.Plan.Pure
295− Reflex.Plan.Reflex
296− Reflex.TestPlan
297− Test.Run
298−
299−test-suite rootCleanup
300− type: exitcode-stdio-1.0
301− main-is: rootCleanup.hs
302− hs-source-dirs: test
303− build-depends: base
304− , containers
305− , deepseq >= 1.3 && < 1.5
306− , dependent-sum
307− , mtl
308− , reflex
309− , ref-tf
310− , these
311− other-modules:
312− Reflex.Plan.Pure
313− Reflex.TestPlan
314− Test.Run
315−
316−benchmark spider-bench
317− type: exitcode-stdio-1.0
318− hs-source-dirs: bench test
319− main-is: Main.hs
320− ghc-options: -Wall -O2 -rtsopts
321− build-depends:
322− base,
323− containers,
324− criterion >= 1.1 && < 1.6,
325− deepseq >= 1.3 && < 1.5,
326− dependent-map,
327− dependent-sum,
328− ref-tf,
329− mtl,
330− primitive,
331− reflex,
332− split,
333− stm,
334− transformers >= 0.3
335− other-modules:
336− Reflex.TestPlan
337− Reflex.Plan.Reflex
338− Reflex.Bench.Focused
339−
340−benchmark saulzar-bench
341− type: exitcode-stdio-1.0
342− hs-source-dirs: bench test
343− c-sources: bench-cbits/checkCapability.c
344− main-is: RunAll.hs
345− ghc-options: -Wall -O2 -rtsopts -threaded
346− build-depends:
347− base,
348− containers >= 0.5 && < 0.7,
349− criterion >= 1.1 && < 1.6,
350− deepseq >= 1.3 && < 1.5,
351− dependent-map,
352− dependent-sum,
353− loch-th,
354− mtl,
355− primitive,
356− process,
357− ref-tf,
358− reflex,
359− split,
360− stm,
361− time,
362− transformers >= 0.3
363− other-modules:
364− Reflex.TestPlan
365− Reflex.Plan.Reflex
366− Reflex.Bench.Focused
367−
368−source-repository head
369− type: git
370− location: https://github.com/reflex-frp/reflex
release.nix+47−7
@@ -1,9 +1,49 @@
1−{ rp ? import ./reflex-platform.nix {}
1+{ reflex-platform-fun ? import ./dep/reflex-platform
22}:
3+
34let
4− inherit (rp.nixpkgs) lib;
5− compilers = ["ghc8_4" "ghc8_0" "ghcjs8_4" "ghcjs8_0"];
6−in lib.genAttrs compilers (ghc: {
7− reflex-useTemplateHaskell = rp.${ghc}.callPackage ./. { useTemplateHaskell = true; };
8− reflex = rp.${ghc}.callPackage ./. { useTemplateHaskell = false; };
9−})
5+ native-reflex-platform = reflex-platform-fun {};
6+ inherit (native-reflex-platform.nixpkgs) lib;
7+ systems = ["x86_64-linux" "x86_64-darwin"];
8+
9+ perPlatform = lib.genAttrs systems (system: let
10+ reflex-platform = reflex-platform-fun { inherit system; };
11+ compilers = [
12+ "ghc"
13+ "ghcjs"
14+ ] ++ lib.optionals (reflex-platform.androidSupport) [
15+ "ghcAndroidAarch64"
16+ "ghcAndroidAarch32"
17+ ] ++ lib.optionals (reflex-platform.iosSupport) [
18+ "ghcIosAarch64"
19+ ];
20+ compilerPkgs = lib.genAttrs compilers (ghc: let
21+ reflex-platform = reflex-platform-fun {
22+ inherit system;
23+ haskellOverlays = [
24+ # Use this package's source for reflex
25+ (self: super: {
26+ _dep = super._dep // {
27+ patch = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
28+ "release.nix"
29+ ".git"
30+ "dist"
31+ "dist-newstyle"
32+ "cabal.haskell-ci"
33+ "cabal.project"
34+ ".travis.yml"
35+ ])) ./.;
36+ };
37+ })
38+ ];
39+ };
40+ in reflex-platform.${ghc}.patch);
41+ in compilerPkgs // {
42+ cache = reflex-platform.pinBuildInputs "patch-${system}"
43+ (builtins.attrValues compilerPkgs);
44+ });
45+
46+ metaCache = native-reflex-platform.pinBuildInputs "patch-everywhere"
47+ (map (a: a.cache) (builtins.attrValues perPlatform));
48+
49+in perPlatform // { inherit metaCache; }
src/Data/AppendMap.hsdeleted−80
@@ -1,80 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE PatternSynonyms #-}
6−{-# LANGUAGE RoleAnnotations #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# OPTIONS_GHC -fno-warn-orphans #-}
10−-- |
11−-- Module:
12−-- Data.AppendMap
13−-- Description:
14−-- Instances and convenience functions for 'Data.Map.Monoidal'. We use
15−-- monoidal-containers to take advantage of its better monoid instance.
16−-- 'Data.Map' has @mappend = union@, which is left-biased. 'MonoidalMap'
17−-- has @mappend = unionWith mappend@ instead.
18−module Data.AppendMap
19− ( module Data.AppendMap
20− , module Data.Map.Monoidal
21− ) where
22−
23−import Prelude hiding (map, null)
24−
25−import Data.Coerce
26−import Data.Default
27−import Data.Map (Map)
28−#if MIN_VERSION_containers(0,5,11)
29−import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith)
30−#else
31−import qualified Data.Map as Map (showTree, showTreeWith)
32−#endif
33−import qualified Data.Witherable as W
34−import Data.Map.Monoidal
35−
36−{-# DEPRECATED AppendMap "Use 'MonoidalMap' instead" #-}
37−-- | AppendMap is a synonym for 'Data.Map.Monoidal.MonoidalMap'
38−type AppendMap = MonoidalMap
39−
40−{-# DEPRECATED _unAppendMap "Use 'getMonoidalMap' instead" #-}
41−-- | A synonym for 'getMonoidalMap'
42−_unAppendMap :: MonoidalMap k v -> Map k v
43−_unAppendMap = getMonoidalMap
44−
45−-- | Pattern synonym for 'MonoidalMap'
46−pattern AppendMap :: Map k v -> MonoidalMap k v
47−pattern AppendMap m = MonoidalMap m
48−
49−instance W.Filterable (MonoidalMap k) where
50− mapMaybe = mapMaybe
51−
52−-- | Deletes a key, returning 'Nothing' if the result is empty.
53−nonEmptyDelete :: Ord k => k -> MonoidalMap k a -> Maybe (MonoidalMap k a)
54−nonEmptyDelete k vs =
55− let deleted = delete k vs
56− in if null deleted
57− then Nothing
58− else Just deleted
59−
60−-- | Like 'mapMaybe' but indicates whether the resulting container is empty
61−mapMaybeNoNull :: (a -> Maybe b)
62− -> MonoidalMap token a
63− -> Maybe (MonoidalMap token b)
64−mapMaybeNoNull f as =
65− let bs = mapMaybe f as
66− in if null bs
67− then Nothing
68− else Just bs
69−
70−-- TODO: Move instances to `Reflex.Patch`
71−-- | Displays a 'MonoidalMap' as a tree. See 'Data.Map.Lazy.showTree' for details.
72−showTree :: forall k a. (Show k, Show a) => MonoidalMap k a -> String
73−showTree = coerce (Map.showTree :: Map k a -> String)
74−
75−-- | Displays a 'MonoidalMap' as a tree, using the supplied function to convert nodes to string.
76−showTreeWith :: forall k a. (k -> a -> String) -> Bool -> Bool -> MonoidalMap k a -> String
77−showTreeWith = coerce (Map.showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String)
78−
79−instance Default (MonoidalMap k a) where
80− def = empty
src/Data/FastMutableIntMap.hsdeleted−93
@@ -1,93 +0,0 @@
1−{-# LANGUAGE TypeFamilies #-}
2−-- |
3−-- Module:
4−-- Data.FastMutableIntMap
5−-- Description:
6−-- A mutable version of 'IntMap'
7−module Data.FastMutableIntMap
8− ( FastMutableIntMap
9− , new
10− , newEmpty
11− , insert
12− , isEmpty
13− , getFrozenAndClear
14− , size
15− , applyPatch
16− , PatchIntMap (..)
17− , traverseIntMapPatchWithKey
18− , lookup
19− , forIntersectionWithImmutable_
20− , for_
21− , patchIntMapNewElements
22− , patchIntMapNewElementsMap
23− , getDeletions
24− ) where
25−
26−--TODO: Pure JS version
27−--TODO: Fast copy to FastIntMap
28−--TODO: Fast patch type
29−
30−import Prelude hiding (lookup)
31−
32−import Control.Monad.IO.Class
33−import Data.Foldable (traverse_)
34−import Data.IntMap.Strict (IntMap)
35−import qualified Data.IntMap.Strict as IntMap
36−import Data.IORef
37−import Reflex.Patch.Class
38−import Reflex.Patch.IntMap
39−
40−-- | A 'FastMutableIntMap' holds a map of values of type @a@ and allows low-overhead modifications via IO.
41−-- Operations on 'FastMutableIntMap' run in IO.
42−newtype FastMutableIntMap a = FastMutableIntMap (IORef (IntMap a))
43−
44−-- | Create a new 'FastMutableIntMap' out of an 'IntMap'
45−new :: IntMap a -> IO (FastMutableIntMap a)
46−new m = FastMutableIntMap <$> newIORef m
47−
48−-- | Create a new empty 'FastMutableIntMap'
49−newEmpty :: IO (FastMutableIntMap a)
50−newEmpty = FastMutableIntMap <$> newIORef IntMap.empty
51−
52−-- | Insert an element into a 'FastMutableIntMap' at the given key
53−insert :: FastMutableIntMap a -> Int -> a -> IO ()
54−insert (FastMutableIntMap r) k v = modifyIORef' r $ IntMap.insert k v
55−
56−-- | Attempt to lookup an element by key in a 'FastMutableIntMap'
57−lookup :: FastMutableIntMap a -> Int -> IO (Maybe a)
58−lookup (FastMutableIntMap r) k = IntMap.lookup k <$> readIORef r
59−
60−-- | Runs the provided action over the intersection of a 'FastMutableIntMap' and an 'IntMap'
61−forIntersectionWithImmutable_ :: MonadIO m => FastMutableIntMap a -> IntMap b -> (a -> b -> m ()) -> m ()
62−forIntersectionWithImmutable_ (FastMutableIntMap r) b f = do
63− a <- liftIO $ readIORef r
64− traverse_ (uncurry f) $ IntMap.intersectionWith (,) a b
65−
66−-- | Runs the provided action over the values of a 'FastMutableIntMap'
67−for_ :: MonadIO m => FastMutableIntMap a -> (a -> m ()) -> m ()
68−for_ (FastMutableIntMap r) f = do
69− a <- liftIO $ readIORef r
70− traverse_ f a
71−
72−-- | Checks whether a 'FastMutableIntMap' is empty
73−isEmpty :: FastMutableIntMap a -> IO Bool
74−isEmpty (FastMutableIntMap r) = IntMap.null <$> readIORef r
75−
76−-- | Retrieves the size of a 'FastMutableIntMap'
77−size :: FastMutableIntMap a -> IO Int
78−size (FastMutableIntMap r) = IntMap.size <$> readIORef r
79−
80−-- | Make an immutable snapshot of the datastructure and clear it
81−getFrozenAndClear :: FastMutableIntMap a -> IO (IntMap a)
82−getFrozenAndClear (FastMutableIntMap r) = do
83− result <- readIORef r
84− writeIORef r IntMap.empty
85− return result
86−
87−-- | Updates the value of a 'FastMutableIntMap' with the given patch (see 'Reflex.Patch.IntMap'),
88−-- and returns an 'IntMap' with the modified keys and values.
89−applyPatch :: FastMutableIntMap a -> PatchIntMap a -> IO (IntMap a)
90−applyPatch (FastMutableIntMap r) p@(PatchIntMap m) = do
91− v <- readIORef r
92− writeIORef r $! applyAlways p v
93− return $ IntMap.intersection v m
src/Data/FastWeakBag.hsdeleted−156
@@ -1,156 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−#ifdef USE_REFLEX_OPTIMIZER
4−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5−#endif
6−#ifdef GHCJS_FAST_WEAK
7−{-# LANGUAGE ForeignFunctionInterface #-}
8−{-# LANGUAGE JavaScriptFFI #-}
9−#endif
10−-- | This module defines the 'FastWeakBag' type, which represents a mutable
11−-- collection of items that does not cause the items to be retained in memory.
12−-- This is useful for situations where a value needs to be inspected or modified
13−-- if it is still alive, but can be ignored if it is dead.
14−module Data.FastWeakBag
15− ( FastWeakBag
16− , FastWeakBagTicket
17− , empty
18− , isEmpty
19− , insert
20− , traverse
21− , remove
22− -- * Internal functions
23− -- These will not always be available.
24−#ifndef GHCJS_FAST_WEAK
25− , _weakBag_children --TODO: Don't export this
26−#endif
27− ) where
28−
29−import Prelude hiding (traverse)
30−
31−import Control.Monad
32−import Control.Monad.IO.Class
33−
34−#ifdef GHCJS_FAST_WEAK
35−import GHCJS.Types
36−import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)
37−#else
38−import Control.Exception
39−import Data.IntMap.Strict (IntMap)
40−import qualified Data.IntMap.Strict as IntMap
41−import Data.IORef
42−import System.Mem.Weak
43−#endif
44−
45−-- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them -
46−-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
47−-- alive, the 'FastWeakBag' will continue to refer to them.
48−#ifdef GHCJS_FAST_WEAK
49−newtype FastWeakBag a = FastWeakBag JSVal
50−#else
51−data FastWeakBag a = FastWeakBag
52− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
53− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'
54− }
55−#endif
56−
57−-- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned. If
58−-- the caller retains the ticket, the item is guranteed to stay in memory (and
59−-- thus in the 'FastWeakBag'). The ticket can also be used to remove the item from
60−-- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.
61−#ifdef GHCJS_FAST_WEAK
62−newtype FastWeakBagTicket a = FastWeakBagTicket JSVal
63−#else
64−data FastWeakBagTicket a = FastWeakBagTicket
65− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
66− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
67− }
68−#endif
69−
70−-- | Insert an item into a 'FastWeakBag'.
71−{-# INLINE insert #-}
72−insert :: a -- ^ The item
73− -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into
74− -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item
75− -- is retained and allows the item to be removed.
76−#ifdef GHCJS_FAST_WEAK
77−insert a wb = js_insert (unsafeToRawJSVal a) wb
78−foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)
79−#else
80−insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do
81− a' <- evaluate a
82− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
83− let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())
84− wa <- mkWeakPtr a' $ Just cleanup
85− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
86− return $ FastWeakBagTicket
87− { _weakBagTicket_weakItem = wa
88− , _weakBagTicket_item = a'
89− }
90−#endif
91−
92−-- | Create an empty 'FastWeakBag'.
93−{-# INLINE empty #-}
94−empty :: IO (FastWeakBag a)
95−#ifdef GHCJS_FAST_WEAK
96−empty = js_empty
97−foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)
98−#else
99−empty = {-# SCC "empty" #-} do
100− nextId <- newIORef 1
101− children <- newIORef IntMap.empty
102− let bag = FastWeakBag
103− { _weakBag_nextId = nextId
104− , _weakBag_children = children
105− }
106− return bag
107−#endif
108−
109−-- | Check whether a 'FastWeakBag' is empty.
110−{-# INLINE isEmpty #-}
111−isEmpty :: FastWeakBag a -> IO Bool
112−#ifdef GHCJS_FAST_WEAK
113−isEmpty = js_isEmpty
114−foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time
115−#else
116−isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)
117−#endif
118−
119−{-# INLINE traverse #-}
120−-- | Visit every node in the given list. If new nodes are appended during the
121−-- traversal, they will not be visited. Every live node that was in the list
122−-- when the traversal began will be visited exactly once; however, no guarantee
123−-- is made about the order of the traversal.
124−traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
125−#ifdef GHCJS_FAST_WEAK
126−traverse wb f = do
127− let go cursor = when (not $ js_isNull cursor) $ do
128− val <- liftIO $ js_getTicketValue cursor
129− f $ unsafeFromRawJSVal val
130− go =<< liftIO (js_getNext (FastWeakBagTicket cursor))
131− go =<< liftIO (js_getInitial wb)
132−foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
133−foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal
134−--TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag
135−foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
136−#else
137−traverse (FastWeakBag _ children) f = {-# SCC "traverse" #-} do
138− cs <- liftIO $ readIORef children
139− forM_ cs $ \c -> do
140− ma <- liftIO $ deRefWeak c
141− mapM_ f ma
142−#endif
143−
144−-- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times
145−-- on the same 'FastWeakBagTicket'.
146−{-# INLINE remove #-}
147−remove :: FastWeakBagTicket a -> IO ()
148−#ifdef GHCJS_FAST_WEAK
149−remove = js_remove
150−foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here
151−#else
152−remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w
153−#endif
154−--TODO: Should 'remove' also drop the reference to the item?
155−
156−--TODO: can/should we provide a null FastWeakBagTicket?
src/Data/Functor/Misc.hs+4−9
@@ -4,17 +4,12 @@
44{-# LANGUAGE FlexibleContexts #-}
55{-# LANGUAGE FlexibleInstances #-}
66{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE KindSignatures #-}
87{-# LANGUAGE LambdaCase #-}
98{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE PatternSynonyms #-}
119{-# LANGUAGE PolyKinds #-}
1210{-# LANGUAGE RankNTypes #-}
1311{-# LANGUAGE ScopedTypeVariables #-}
1412{-# LANGUAGE StandaloneDeriving #-}
15−#ifdef USE_REFLEX_OPTIMIZER
16−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
17−#endif
1813-- | This module provides types and functions with no particular theme, but
1914-- which are relevant to the use of 'Functor'-based datastructures like
2015-- 'Data.Dependent.Map.DMap'.
@@ -42,19 +37,19 @@ module Data.Functor.Misc
4237 ) where
4338
4439import Control.Applicative ((<$>))
45−import Control.Monad.Identity
4640import Data.Dependent.Map (DMap)
4741import qualified Data.Dependent.Map as DMap
4842import Data.Dependent.Sum
43+import Data.Functor.Identity
4944import Data.GADT.Compare
5045import Data.GADT.Show
5146import Data.IntMap (IntMap)
5247import qualified Data.IntMap as IntMap
5348import Data.Map (Map)
5449import qualified Data.Map as Map
55−import Data.Some (Some)
56−import qualified Data.Some as Some
50+import Data.Some (Some, mkSome)
5751import Data.These
52+import Data.Type.Equality ((:~:)(Refl))
5853import Data.Typeable hiding (Refl)
5954
6055--------------------------------------------------------------------------------
@@ -121,7 +116,7 @@ intMapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=
121116-- | Convert a 'DMap' to a regular 'Map' by forgetting the types associated with
122117-- the keys, using a function to remove the wrapping 'Functor'
123118weakenDMapWith :: (forall a. v a -> v') -> DMap k v -> Map (Some k) v'
124−weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (Some.This k, f v)) . DMap.toAscList
119+weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (mkSome k, f v)) . DMap.toAscList
125120
126121--------------------------------------------------------------------------------
127122-- WrapArg
src/Data/Map/Misc.hsdeleted−71
@@ -1,71 +0,0 @@
1−{-# LANGUAGE LambdaCase #-}
2−-- | Additional functions for manipulating 'Map's.
3−module Data.Map.Misc
4− (
5− -- * Working with Maps
6− diffMapNoEq
7− , diffMap
8− , applyMap
9− , mapPartitionEithers
10− , applyMapKeysSet
11− ) where
12−
13−import Data.Align
14−import Data.Map (Map)
15−import qualified Data.Map as Map
16−import Data.Maybe
17−import Data.Set (Set)
18−import qualified Data.Set as Set
19−import Data.These
20−
21−-- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new@ respectively. @Just@ represents an association present in @new@ and @Nothing@
22−-- represents an association only present in @old@ but no longer present in @new@.
23−--
24−-- Similar to 'diffMap' but doesn't require 'Eq' on the values, thus can't tell if a value has changed or not.
25−diffMapNoEq :: (Ord k) => Map k v -> Map k v -> Map k (Maybe v)
26−diffMapNoEq olds news = flip Map.mapMaybe (align olds news) $ \case
27− This _ -> Just Nothing
28− These _ new -> Just $ Just new
29− That new -> Just $ Just new
30−
31−-- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new respectively. @Just@ represents an association present in @new@ and either not
32−-- present in @old@ or where the value has changed. @Nothing@ represents an association only present in @old@ but no longer present in @new@.
33−--
34−-- See also 'diffMapNoEq' for a similar but weaker version which does not require 'Eq' on the values but thus can't indicated a value not changing between
35−-- @old@ and @new@ with @Nothing@.
36−diffMap :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (Maybe v)
37−diffMap olds news = flip Map.mapMaybe (align olds news) $ \case
38− This _ -> Just Nothing
39− These old new
40− | old == new -> Nothing
41− | otherwise -> Just $ Just new
42− That new -> Just $ Just new
43−
44−-- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new map from the given input @'Map' k v@.
45−--
46−-- See also 'Reflex.Patch.Map' and 'Reflex.Patch.MapWithMove'.
47−applyMap :: Ord k => Map k (Maybe v) -> Map k v -> Map k v
48−applyMap patch old = insertions `Map.union` (old `Map.difference` deletions)
49− where (deletions, insertions) = Map.mapEither maybeToEither patch
50− maybeToEither = \case
51− Nothing -> Left ()
52− Just r -> Right r
53−
54−-- |Split a @'Map' k (Either a b)@ into @Map k a@ and @Map k b@, equivalent to @'Map.mapEither' id@
55−{-# DEPRECATED mapPartitionEithers "Use 'mapEither' instead" #-}
56−mapPartitionEithers :: Map k (Either a b) -> (Map k a, Map k b)
57−mapPartitionEithers = Map.mapEither id
58−
59−-- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new @'Set' k@ from the given input set.
60−--
61−-- Equivalent to:
62−--
63−-- @
64−-- applyMapKeysSet patch ('Map.keysSet' m) == 'Map.keysSet' ('applyMap' patch m)
65−-- @
66−--
67−-- but avoids the intervening @Map@ and needs no values.
68−applyMapKeysSet :: Ord k => Map k (Maybe v) -> Set k -> Set k
69−applyMapKeysSet patch old = Map.keysSet insertions `Set.union` (old `Set.difference` Map.keysSet deletions)
70− where (insertions, deletions) = Map.partition isJust patch
71−
src/Data/Monoid/DecidablyEmpty.hsnew file+115
@@ -0,0 +1,115 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DefaultSignatures #-}
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE StandaloneDeriving #-}
5+{-# LANGUAGE TypeOperators #-}
6+
7+-- TODO upstream somwhere else?
8+module Data.Monoid.DecidablyEmpty where
9+
10+import Data.Functor.Identity
11+import Data.Functor.Const
12+import Data.Monoid
13+import Data.Maybe (isNothing)
14+#if MIN_VERSION_base(4,11,0)
15+import Data.Ord
16+#endif
17+import Data.Proxy
18+import Data.Semigroup hiding (First, Last)
19+#if MIN_VERSION_base(4,12,0)
20+import GHC.Generics
21+#endif
22+
23+import qualified Data.IntSet as IntSet
24+import qualified Data.IntMap as IntMap
25+import qualified Data.Map as Map
26+import qualified Data.Sequence as Seq
27+import qualified Data.Set as Set
28+
29+import Data.GADT.Compare
30+import qualified Data.Dependent.Map as DMap
31+
32+-- | A 'DecidablyEmpty' is one where it can be computed whether or not an
33+-- arbitrary value is 'mempty'.
34+--
35+-- By using this class rather than 'Eq', we avoid unnecessary constraining the
36+-- contents of 'Functor's. This makes it possible to efficiently combine and/or
37+-- nest patch maps with 'Eq'-lacking values (e.g. functions) at the leaves.
38+class Monoid a => DecidablyEmpty a where
39+ isEmpty :: a -> Bool
40+ default isEmpty :: Eq a => a -> Bool
41+ isEmpty = (==) mempty
42+
43+-- base
44+
45+instance DecidablyEmpty Ordering
46+instance DecidablyEmpty ()
47+instance DecidablyEmpty Any
48+instance DecidablyEmpty All
49+-- instance DecidablyEmpty Lifetime
50+-- instance DecidablyEmpty Event
51+instance DecidablyEmpty [a] where
52+ isEmpty = null
53+instance
54+#if MIN_VERSION_base(4,11,0)
55+ Semigroup a
56+#else
57+ Monoid a
58+#endif
59+ => DecidablyEmpty (Maybe a) where
60+ isEmpty = isNothing
61+deriving instance (Num a, DecidablyEmpty a) => DecidablyEmpty (Product a)
62+deriving instance (DecidablyEmpty a, Num a) => DecidablyEmpty (Sum a)
63+deriving instance DecidablyEmpty a => DecidablyEmpty (Dual a)
64+instance DecidablyEmpty (First a) where
65+ isEmpty (First a) = isNothing a
66+instance DecidablyEmpty (Last a) where
67+ isEmpty (Last a) = isNothing a
68+deriving instance DecidablyEmpty a => DecidablyEmpty (Identity a)
69+instance Semigroup a => DecidablyEmpty (Option a) where
70+ isEmpty (Option a) = isNothing a
71+deriving instance DecidablyEmpty m => DecidablyEmpty (WrappedMonoid m)
72+instance (Ord a, Bounded a) => DecidablyEmpty (Max a)
73+instance (Ord a, Bounded a) => DecidablyEmpty (Min a)
74+instance DecidablyEmpty (Proxy s)
75+deriving instance DecidablyEmpty a => DecidablyEmpty (Const a b)
76+#if MIN_VERSION_base(4,11,0)
77+deriving instance DecidablyEmpty a => DecidablyEmpty (Down a)
78+#endif
79+#if MIN_VERSION_base(4,12,0)
80+deriving instance DecidablyEmpty p => DecidablyEmpty (Par1 p)
81+instance DecidablyEmpty (U1 p)
82+deriving instance DecidablyEmpty (f p) => DecidablyEmpty (Rec1 f p)
83+deriving instance DecidablyEmpty (f p) => DecidablyEmpty (M1 i c f p)
84+deriving instance DecidablyEmpty c => DecidablyEmpty (K1 i c p)
85+instance (DecidablyEmpty (f p), DecidablyEmpty (g p)) => DecidablyEmpty ((f :*: g) p) where
86+ isEmpty (x :*: y) = isEmpty x && isEmpty y
87+deriving instance DecidablyEmpty (f (g p)) => DecidablyEmpty ((f :.: g) p)
88+#endif
89+
90+instance (DecidablyEmpty a, DecidablyEmpty b) => DecidablyEmpty (a, b) where
91+ isEmpty (a, b) = isEmpty a && isEmpty b
92+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c) => DecidablyEmpty (a, b, c) where
93+ isEmpty (a, b, c) = isEmpty a && isEmpty b && isEmpty c
94+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d) => DecidablyEmpty (a, b, c, d) where
95+ isEmpty (a, b, c, d) = isEmpty a && isEmpty b && isEmpty c && isEmpty d
96+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d, DecidablyEmpty e) => DecidablyEmpty (a, b, c, d, e) where
97+ isEmpty (a, b, c, d, e) = isEmpty a && isEmpty b && isEmpty c && isEmpty d && isEmpty e
98+
99+-- containers
100+
101+instance DecidablyEmpty IntSet.IntSet where
102+ isEmpty = IntSet.null
103+instance DecidablyEmpty (IntMap.IntMap v) where
104+ isEmpty = IntMap.null
105+instance Ord k => DecidablyEmpty (Map.Map k v) where
106+ isEmpty = Map.null
107+instance DecidablyEmpty (Seq.Seq v) where
108+ isEmpty = Seq.null
109+instance Ord k => DecidablyEmpty (Set.Set k) where
110+ isEmpty = Set.null
111+
112+-- dependent-map
113+
114+instance GCompare k => DecidablyEmpty (DMap.DMap k v) where
115+ isEmpty = DMap.null
src/Data/Patch.hsnew file+95
@@ -0,0 +1,95 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE StandaloneDeriving #-}
4+{-# LANGUAGE TypeFamilies #-}
5+{-# LANGUAGE TypeOperators #-}
6+-- |
7+-- Module:
8+-- Data.Patch
9+-- Description:
10+-- This module defines the 'Patch' class.
11+module Data.Patch
12+ ( module Data.Patch
13+ , module X
14+ ) where
15+
16+import Control.Applicative
17+import Data.Functor.Const (Const (..))
18+import Data.Functor.Identity
19+import Data.Map.Monoidal (MonoidalMap)
20+import Data.Proxy
21+#if !MIN_VERSION_base(4,11,0)
22+import Data.Semigroup (Semigroup (..))
23+#endif
24+import GHC.Generics
25+
26+import Data.Semigroup.Additive as X
27+import Data.Patch.Class as X
28+import Data.Patch.DMap as X hiding (getDeletions)
29+import Data.Patch.DMapWithMove as X
30+ ( PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove
31+ , patchDMapWithMoveToPatchMapWithMoveWith
32+ , traversePatchDMapWithMoveWithKey, unPatchDMapWithMove
33+ , unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith
34+ )
35+import Data.Patch.IntMap as X hiding (getDeletions)
36+import Data.Patch.Map as X
37+import Data.Patch.MapWithMove as X
38+ ( PatchMapWithMove, patchMapWithMoveNewElements
39+ , patchMapWithMoveNewElementsMap, unPatchMapWithMove
40+ , unsafePatchMapWithMove
41+ )
42+
43+-- | A 'Group' is a 'Monoid' where every element has an inverse.
44+class (Semigroup q, Monoid q) => Group q where
45+ negateG :: q -> q
46+ (~~) :: q -> q -> q
47+ r ~~ s = r <> negateG s
48+
49+-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
50+newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
51+
52+instance Additive p => Patch (AdditivePatch p) where
53+ type PatchTarget (AdditivePatch p) = p
54+ apply (AdditivePatch p) q = Just $ p <> q
55+
56+instance (Ord k, Group q) => Group (MonoidalMap k q) where
57+ negateG = fmap negateG
58+
59+-- | Trivial group.
60+instance Group () where
61+ negateG _ = ()
62+ _ ~~ _ = ()
63+
64+-- | Product group. A Pair of groups gives rise to a group
65+instance (Group a, Group b) => Group (a, b) where
66+ negateG (a, b) = (negateG a, negateG b)
67+ (a, b) ~~ (c, d) = (a ~~ c, b ~~ d)
68+
69+-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
70+-- Base does not define Monoid (Compose f g a) so this is the best we can
71+-- really do for functor composition.
72+instance Group (f (g a)) => Group ((f :.: g) a) where
73+ negateG (Comp1 xs) = Comp1 (negateG xs)
74+ Comp1 xs ~~ Comp1 ys = Comp1 (xs ~~ ys)
75+
76+-- | Product of groups, Functor style.
77+instance (Group (f a), Group (g a)) => Group ((f :*: g) a) where
78+ negateG (a :*: b) = negateG a :*: negateG b
79+ (a :*: b) ~~ (c :*: d) = (a ~~ c) :*: (b ~~ d)
80+
81+-- | Trivial group, Functor style
82+instance Group (Proxy x) where
83+ negateG _ = Proxy
84+ _ ~~ _ = Proxy
85+
86+-- | Const lifts groups into a functor.
87+deriving instance Group a => Group (Const a x)
88+
89+-- | Identity lifts groups pointwise (at only one point)
90+deriving instance Group a => Group (Identity a)
91+
92+-- | Functions lift groups pointwise.
93+instance Group b => Group (a -> b) where
94+ negateG f = negateG . f
95+ (~~) = liftA2 (~~)
src/Reflex/Patch/Class.hs → src/Data/Patch/Class.hsrenamed+14−3
@@ -1,17 +1,23 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
13{-# LANGUAGE TypeFamilies #-}
24-- | The interface for types which represent changes made to other types
3−module Reflex.Patch.Class where
5+module Data.Patch.Class where
46
5−import Control.Monad.Identity
7+import Data.Functor.Identity
8+import Data.Kind (Type)
69import Data.Maybe
10+#if !MIN_VERSION_base(4,11,0)
711import Data.Semigroup (Semigroup(..))
12+#endif
13+import Data.Proxy
814
915-- | A 'Patch' type represents a kind of change made to a datastructure.
1016--
1117-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
1218-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
1319class Patch p where
14− type PatchTarget p :: *
20+ type PatchTarget p :: Type
1521 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
1622 -- 'Nothing'.
1723 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
@@ -25,6 +31,11 @@ instance Patch (Identity a) where
2531 type PatchTarget (Identity a) = a
2632 apply (Identity a) _ = Just a
2733
34+-- | 'Proxy' can be used as a 'Patch' that does nothing.
35+instance forall (a :: Type). Patch (Proxy a) where
36+ type PatchTarget (Proxy a) = a
37+ apply ~Proxy _ = Nothing
38+
2839-- | Like '(.)', but composes functions that return patches rather than
2940-- functions that return new values. The Semigroup instance for patches must
3041-- apply patches right-to-left, like '(.)'.
src/Reflex/Patch/DMap.hs → src/Data/Patch/DMap.hsrenamed+16−5
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE GeneralizedNewtypeDeriving #-}
23{-# LANGUAGE LambdaCase #-}
34{-# LANGUAGE PolyKinds #-}
@@ -5,20 +6,26 @@
56{-# LANGUAGE ScopedTypeVariables #-}
67{-# LANGUAGE StandaloneDeriving #-}
78{-# LANGUAGE TypeFamilies #-}
9+
810-- | 'Patch'es on 'DMap' that consist only of insertions (or overwrites) and deletions.
9−module Reflex.Patch.DMap where
11+module Data.Patch.DMap where
1012
11−import Reflex.Patch.Class
12−import Reflex.Patch.IntMap
13−import Reflex.Patch.Map
13+import Data.Patch.Class
14+import Data.Patch.IntMap
15+import Data.Patch.Map
1416
15−import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
17+import Data.Dependent.Map (DMap)
18+import Data.Dependent.Sum (DSum (..))
19+import Data.GADT.Compare (GCompare (..))
1620import qualified Data.Dependent.Map as DMap
1721import Data.Functor.Constant
1822import Data.Functor.Misc
1923import qualified Data.IntMap as IntMap
2024import qualified Data.Map as Map
25+import Data.Monoid.DecidablyEmpty
26+#if !MIN_VERSION_base(4,11,0)
2127import Data.Semigroup (Semigroup (..))
28+#endif
2229import Data.Some (Some)
2330
2431-- | A set of changes to a 'DMap'. Any element may be inserted/updated or deleted.
@@ -30,6 +37,10 @@ deriving instance GCompare k => Semigroup (PatchDMap k v)
3037
3138deriving instance GCompare k => Monoid (PatchDMap k v)
3239
40+-- It won't let me derive for some reason
41+instance GCompare k => DecidablyEmpty (PatchDMap k v) where
42+ isEmpty (PatchDMap m) = DMap.null m
43+
3344-- | Apply the insertions or deletions to a given 'DMap'.
3445instance GCompare k => Patch (PatchDMap k v) where
3546 type PatchTarget (PatchDMap k v) = DMap k v
src/Reflex/Patch/DMapWithMove.hs → src/Data/Patch/DMapWithMove.hsrenamed+22−17
@@ -13,26 +13,28 @@
1313
1414-- |Module containing @'PatchDMapWithMove' k v@ and associated functions, which represents a 'Patch' to a @'DMap' k v@ which can insert, update, delete, and
1515-- move values between keys.
16−module Reflex.Patch.DMapWithMove where
16+module Data.Patch.DMapWithMove where
1717
18−import Reflex.Patch.Class
19−import Reflex.Patch.MapWithMove (PatchMapWithMove (..))
20−import qualified Reflex.Patch.MapWithMove as MapWithMove
18+import Data.Patch.Class
19+import Data.Patch.MapWithMove (PatchMapWithMove (..))
20+import qualified Data.Patch.MapWithMove as MapWithMove
2121
2222import Data.Constraint.Extras
23−import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
23+import Data.Dependent.Map (DMap)
24+import Data.Dependent.Sum (DSum (..))
2425import qualified Data.Dependent.Map as DMap
25−import Data.Dependent.Sum (EqTag (..))
2626import Data.Functor.Constant
2727import Data.Functor.Misc
2828import Data.Functor.Product
29−import Data.GADT.Compare (GEq (..))
29+import Data.GADT.Compare (GEq (..), GCompare (..))
3030import Data.GADT.Show (GShow, gshow)
3131import qualified Data.Map as Map
3232import Data.Maybe
33−import Data.Semigroup (Semigroup (..), (<>))
34−import Data.Some (Some)
35−import qualified Data.Some as Some
33+import Data.Monoid.DecidablyEmpty
34+#if !MIN_VERSION_base(4,11,0)
35+import Data.Semigroup (Semigroup (..))
36+#endif
37+import Data.Some (Some, mkSome)
3638import Data.These
3739
3840-- | Like 'PatchMapWithMove', but for 'DMap'. Each key carries a 'NodeInfo' which describes how it will be changed by the patch and connects move sources and
@@ -44,6 +46,10 @@ import Data.These
4446-- * A move should always be represented with both the destination key (as a 'From_Move') and the source key (as a @'ComposeMaybe' ('Just' destination)@)
4547newtype PatchDMapWithMove k v = PatchDMapWithMove (DMap k (NodeInfo k v))
4648
49+-- It won't let me derive for some reason
50+instance GCompare k => DecidablyEmpty (PatchDMapWithMove k v) where
51+ isEmpty (PatchDMapWithMove m) = DMap.null m
52+
4753-- |Structure which represents what changes apply to a particular key. @_nodeInfo_from@ specifies what happens to this key, and in particular what other key
4854-- the current key is moving from, while @_nodeInfo_to@ specifies what key the current key is moving to if involved in a move.
4955data NodeInfo k v a = NodeInfo
@@ -106,9 +112,8 @@ validationErrorsForPatchDMapWithMove m =
106112 unbalancedMove _ = Nothing
107113
108114-- |Test whether two @'PatchDMapWithMove' k v@ contain the same patch operations.
109−-- TODO: Get rid of EqTag constraint once dependent-map > 0.2.4.0, which drops this requirement, is released
110−instance (GEq k, Has' Eq k (NodeInfo k v), EqTag k (NodeInfo k v)) => Eq (PatchDMapWithMove k v) where
111− PatchDMapWithMove a == PatchDMapWithMove b = a == b
115+instance (GEq k, Has' Eq k (NodeInfo k v)) => Eq (PatchDMapWithMove k v) where
116+ PatchDMapWithMove a == PatchDMapWithMove b = a == b
112117
113118-- |Higher kinded 2-tuple, identical to @Data.Functor.Product@ from base ≥ 4.9
114119data Pair1 f g a = Pair1 (f a) (g a)
@@ -215,8 +220,8 @@ moveDMapKey src dst = case src `geq` dst of
215220-- @
216221-- let aMay = DMap.lookup a dmap
217222-- bMay = DMap.lookup b dmap
218−-- in maybe id (DMap.insert a) (bMay `mplus` aMay)
219−-- . maybe id (DMap.insert b) (aMay `mplus` bMay)
223+-- in maybe id (DMap.insert a) (bMay <> aMay)
224+-- . maybe id (DMap.insert b) (aMay <> bMay)
220225-- . DMap.delete a . DMap.delete b $ dmap
221226-- @
222227swapDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
@@ -313,8 +318,8 @@ weakenPatchDMapWithMoveWith f (PatchDMapWithMove p) = PatchMapWithMove $ weakenD
313318 { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
314319 From_Insert v -> MapWithMove.From_Insert $ f v
315320 From_Delete -> MapWithMove.From_Delete
316− From_Move k -> MapWithMove.From_Move $ Some.This k
317− , MapWithMove._nodeInfo_to = Some.This <$> getComposeMaybe (_nodeInfo_to ni)
321+ From_Move k -> MapWithMove.From_Move $ mkSome k
322+ , MapWithMove._nodeInfo_to = mkSome <$> getComposeMaybe (_nodeInfo_to ni)
318323 }
319324
320325-- |"Weaken" a @'PatchDMapWithMove' (Const2 k a) v@ to a @'PatchMapWithMove' k v'@. Weaken is in scare quotes because the 'Const2' has already disabled any
src/Reflex/Patch/IntMap.hs → src/Data/Patch/IntMap.hsrenamed+30−21
@@ -1,23 +1,41 @@
11{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveFoldable #-}
3−{-# LANGUAGE DeriveFunctor #-}
42{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleInstances #-}
54{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE StandaloneDeriving #-}
7+{-# LANGUAGE TemplateHaskell #-}
68{-# LANGUAGE TypeFamilies #-}
9+
710-- | Module containing 'PatchIntMap', a 'Patch' for 'IntMap' which allows for
811-- insert/update or delete of associations.
9−module Reflex.Patch.IntMap where
12+module Data.Patch.IntMap where
1013
14+import Control.Lens
1115import Data.IntMap.Strict (IntMap)
1216import qualified Data.IntMap.Strict as IntMap
1317import Data.Maybe
14−import Data.Semigroup
15−import Reflex.Patch.Class
18+import Data.Monoid.DecidablyEmpty
19+#if !MIN_VERSION_base(4,11,0)
20+import Data.Semigroup (Semigroup (..))
21+#endif
22+import Data.Patch.Class
1623
1724-- | 'Patch' for 'IntMap' which represents insertion or deletion of keys in the mapping.
1825-- Internally represented by 'IntMap (Maybe a)', where @Just@ means insert/update
1926-- and @Nothing@ means delete.
20−newtype PatchIntMap a = PatchIntMap (IntMap (Maybe a)) deriving (Functor, Foldable, Traversable, Monoid)
27+newtype PatchIntMap a = PatchIntMap { unPatchIntMap :: IntMap (Maybe a) }
28+ deriving ( Show, Read, Eq, Ord
29+ , Functor, Foldable, Traversable
30+ , Monoid, DecidablyEmpty
31+ )
32+
33+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
34+-- If the same key is modified by both patches, the one on the left will take
35+-- precedence.
36+deriving instance Semigroup (PatchIntMap v)
37+
38+makeWrapped ''PatchIntMap
2139
2240-- | Apply the insertions or deletions to a given 'IntMap'.
2341instance Patch (PatchIntMap a) where
@@ -27,20 +45,11 @@ instance Patch (PatchIntMap a) where
2745 adds = IntMap.mapMaybe id p
2846 in IntMap.union adds $ v `IntMap.difference` removes
2947
30−-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
31−-- If the same key is modified by both patches, the one on the left will take
32−-- precedence.
33−instance Semigroup (PatchIntMap v) where
34− PatchIntMap a <> PatchIntMap b = PatchIntMap $ a `mappend` b --TODO: Add a semigroup instance for Map
35− -- PatchMap is idempotent, so stimes n is id for every n
36−#if MIN_VERSION_semigroups(0,17,0)
37− stimes = stimesIdempotentMonoid
38−#else
39− times1p n x = case compare n 0 of
40− LT -> error "stimesIdempotentMonoid: negative multiplier"
41− EQ -> mempty
42− GT -> x
43−#endif
48+instance FunctorWithIndex Int PatchIntMap
49+instance FoldableWithIndex Int PatchIntMap
50+instance TraversableWithIndex Int PatchIntMap where
51+ itraverse = itraversed . Indexed
52+ itraversed = _Wrapped .> itraversed <. traversed
4453
4554-- | Map a function @Int -> a -> b@ over all @a@s in the given @'PatchIntMap' a@
4655-- (that is, all inserts/updates), producing a @PatchIntMap b@.
@@ -50,7 +59,7 @@ mapIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap $ IntMap.mapWithKey (\ k m
5059-- | Map an effectful function @Int -> a -> f b@ over all @a@s in the given @'PatchIntMap' a@
5160-- (that is, all inserts/updates), producing a @f (PatchIntMap b)@.
5261traverseIntMapPatchWithKey :: Applicative f => (Int -> a -> f b) -> PatchIntMap a -> f (PatchIntMap b)
53−traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (\k mv -> traverse (f k) mv) m
62+traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (traverse . f) m
5463
5564-- | Extract all @a@s inserted/updated by the given @'PatchIntMap' a@.
5665patchIntMapNewElements :: PatchIntMap a -> [a]
src/Reflex/Patch/Map.hs → src/Data/Patch/Map.hsrenamed+37−28
@@ -1,22 +1,48 @@
11{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
25{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE StandaloneDeriving #-}
8+{-# LANGUAGE TemplateHaskell #-}
39{-# LANGUAGE TypeFamilies #-}
10+
411-- | 'Patch'es on 'Map' that consist only of insertions (including overwrites)
512-- and deletions
6−module Reflex.Patch.Map where
13+module Data.Patch.Map where
714
8−import Reflex.Patch.Class
15+import Data.Patch.Class
916
17+import Control.Lens
1018import Data.Map (Map)
1119import qualified Data.Map as Map
1220import Data.Maybe
13−import Data.Semigroup
21+import Data.Monoid.DecidablyEmpty
22+import Data.Semigroup (Semigroup (..), stimesIdempotentMonoid)
1423
1524-- | A set of changes to a 'Map'. Any element may be inserted/updated or
1625-- deleted. Insertions are represented as values wrapped in 'Just', while
1726-- deletions are represented as 'Nothing's
1827newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
19− deriving (Show, Read, Eq, Ord)
28+ deriving ( Show, Read, Eq, Ord
29+ , Foldable, Traversable
30+ , DecidablyEmpty
31+ )
32+
33+-- | 'fmap'ping a 'PatchMap' will alter all of the values it will insert.
34+-- Deletions are unaffected.
35+deriving instance Functor (PatchMap k)
36+-- | The empty 'PatchMap' contains no insertions or deletions
37+deriving instance Ord k => Monoid (PatchMap k v)
38+
39+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
40+-- If the same key is modified by both patches, the one on the left will take
41+-- precedence.
42+instance Ord k => Semigroup (PatchMap k v) where
43+ PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
44+ -- PatchMap is idempotent, so stimes n is id for every n
45+ stimes = stimesIdempotentMonoid
2046
2147-- | Apply the insertions or deletions to a given 'Map'.
2248instance Ord k => Patch (PatchMap k v) where
@@ -29,30 +55,11 @@ instance Ord k => Patch (PatchMap k v) where
2955 Nothing -> Just ()
3056 Just _ -> Nothing
3157
32−-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
33−-- If the same key is modified by both patches, the one on the left will take
34−-- precedence.
35−instance Ord k => Semigroup (PatchMap k v) where
36− PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
37− -- PatchMap is idempotent, so stimes n is id for every n
38−#if MIN_VERSION_semigroups(0,17,0)
39− stimes = stimesIdempotentMonoid
40−#else
41− times1p n x = case compare n 0 of
42− LT -> error "stimesIdempotentMonoid: negative multiplier"
43− EQ -> mempty
44− GT -> x
45−#endif
46−
47−-- | The empty 'PatchMap' contains no insertions or deletions
48−instance Ord k => Monoid (PatchMap k v) where
49− mempty = PatchMap mempty
50− mappend = (<>)
51−
52−-- | 'fmap'ping a 'PatchMap' will alter all of the values it will insert.
53−-- Deletions are unaffected.
54−instance Functor (PatchMap k) where
55− fmap f = PatchMap . fmap (fmap f) . unPatchMap
58+instance FunctorWithIndex k (PatchMap k)
59+instance FoldableWithIndex k (PatchMap k)
60+instance TraversableWithIndex k (PatchMap k) where
61+ itraverse = itraversed . Indexed
62+ itraversed = _Wrapped .> itraversed <. traversed
5663
5764-- | Returns all the new elements that will be added to the 'Map'
5865patchMapNewElements :: PatchMap k v -> [v]
@@ -61,3 +68,5 @@ patchMapNewElements (PatchMap p) = catMaybes $ Map.elems p
6168-- | Returns all the new elements that will be added to the 'Map'
6269patchMapNewElementsMap :: PatchMap k v -> Map k v
6370patchMapNewElementsMap (PatchMap p) = Map.mapMaybe id p
71+
72+makeWrapped ''PatchMap
src/Data/Patch/MapWithMove.hsnew file+312
@@ -0,0 +1,312 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6+{-# LANGUAGE LambdaCase #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE PatternGuards #-}
9+{-# LANGUAGE PatternSynonyms #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE StandaloneDeriving #-}
12+{-# LANGUAGE TemplateHaskell #-}
13+{-# LANGUAGE TypeApplications #-}
14+{-# LANGUAGE TypeFamilies #-}
15+{-# LANGUAGE ViewPatterns #-}
16+
17+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
18+-- another
19+module Data.Patch.MapWithMove
20+ ( PatchMapWithMove
21+ ( PatchMapWithMove
22+ , unPatchMapWithMove
23+ , ..
24+ )
25+ , patchMapWithMove
26+ , patchMapWithMoveInsertAll
27+ , insertMapKey
28+ , moveMapKey
29+ , swapMapKey
30+ , deleteMapKey
31+ , unsafePatchMapWithMove
32+ , patchMapWithMoveNewElements
33+ , patchMapWithMoveNewElementsMap
34+ , patchThatSortsMapWith
35+ , patchThatChangesAndSortsMapWith
36+ , patchThatChangesMap
37+
38+ -- * Node Info
39+ , NodeInfo
40+ ( NodeInfo
41+ , _nodeInfo_to
42+ , _nodeInfo_from
43+ , ..
44+ )
45+ , bitraverseNodeInfo
46+ , nodeInfoMapFrom
47+ , nodeInfoMapMFrom
48+ , nodeInfoSetTo
49+
50+ -- * From
51+ , From
52+ ( From_Insert
53+ , From_Delete
54+ , From_Move
55+ , ..
56+ )
57+ , bitraverseFrom
58+
59+ -- * To
60+ , To
61+ ) where
62+
63+import Data.Coerce
64+import Data.Kind (Type)
65+import Data.Patch.Class
66+import Data.Patch.MapWithPatchingMove (PatchMapWithPatchingMove(..), To)
67+import qualified Data.Patch.MapWithPatchingMove as PM -- already a transparent synonym
68+
69+import Control.Lens
70+import Data.List
71+import Data.Map (Map)
72+import qualified Data.Map as Map
73+import Data.Proxy
74+#if !MIN_VERSION_base(4,11,0)
75+import Data.Semigroup (Semigroup (..))
76+#endif
77+import Data.Traversable (foldMapDefault)
78+
79+-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
80+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
81+-- and vice versa. There should never be any unpaired From/To keys.
82+newtype PatchMapWithMove k (v :: Type) = PatchMapWithMove'
83+ { -- | Extract the underlying 'PatchMapWithPatchingMove k (Proxy v)'
84+ unPatchMapWithMove' :: PatchMapWithPatchingMove k (Proxy v)
85+ }
86+ deriving ( Show, Read, Eq, Ord
87+-- Haddock cannot handle documentation here before GHC 8.6
88+ ,
89+#if __GLASGOW_HASKELL__ >= 806
90+ -- | Compose patches having the same effect as applying the
91+ -- patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p .
92+ -- 'applyAlways' q@
93+#endif
94+ Semigroup
95+ , Monoid
96+ )
97+
98+pattern Coerce :: Coercible a b => a -> b
99+pattern Coerce x <- (coerce -> x)
100+ where Coerce x = coerce x
101+
102+{-# COMPLETE PatchMapWithMove #-}
103+pattern PatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
104+-- | Extract the representation of the 'PatchMapWithMove' as a map of
105+-- 'NodeInfo'.
106+unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
107+pattern PatchMapWithMove { unPatchMapWithMove } = PatchMapWithMove' (PatchMapWithPatchingMove (Coerce unPatchMapWithMove))
108+
109+_PatchMapWithMove
110+ :: Iso
111+ (PatchMapWithMove k0 v0)
112+ (PatchMapWithMove k1 v1)
113+ (Map k0 (NodeInfo k0 v0))
114+ (Map k1 (NodeInfo k1 v1))
115+_PatchMapWithMove = iso unPatchMapWithMove PatchMapWithMove
116+
117+instance Functor (PatchMapWithMove k) where
118+ fmap f = runIdentity . traverse (Identity . f)
119+
120+instance Foldable (PatchMapWithMove k) where
121+ foldMap = foldMapDefault
122+
123+instance Traversable (PatchMapWithMove k) where
124+ traverse =
125+ _PatchMapWithMove .
126+ traverse .
127+ traverse
128+
129+instance FunctorWithIndex k (PatchMapWithMove k)
130+instance FoldableWithIndex k (PatchMapWithMove k)
131+instance TraversableWithIndex k (PatchMapWithMove k) where
132+ itraverse = itraversed . Indexed
133+ itraversed =
134+ _PatchMapWithMove .>
135+ itraversed <.
136+ traverse
137+
138+-- | Create a 'PatchMapWithMove', validating it
139+patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
140+patchMapWithMove = fmap PatchMapWithMove' . PM.patchMapWithPatchingMove . coerce
141+
142+-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
143+patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
144+patchMapWithMoveInsertAll = PatchMapWithMove' . PM.patchMapWithPatchingMoveInsertAll
145+
146+-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
147+insertMapKey :: k -> v -> PatchMapWithMove k v
148+insertMapKey k v = PatchMapWithMove' $ PM.insertMapKey k v
149+
150+-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
151+--
152+-- @
153+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
154+-- @
155+moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
156+moveMapKey src dst = PatchMapWithMove' $ PM.moveMapKey src dst
157+
158+-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
159+--
160+-- @
161+-- let aMay = Map.lookup a map
162+-- bMay = Map.lookup b map
163+-- in maybe id (Map.insert a) (bMay <> aMay)
164+-- . maybe id (Map.insert b) (aMay <> bMay)
165+-- . Map.delete a . Map.delete b $ map
166+-- @
167+swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
168+swapMapKey src dst = PatchMapWithMove' $ PM.swapMapKey src dst
169+
170+-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
171+deleteMapKey :: k -> PatchMapWithMove k v
172+deleteMapKey = PatchMapWithMove' . PM.deleteMapKey
173+
174+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
175+--
176+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
177+unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
178+unsafePatchMapWithMove = coerce PM.unsafePatchMapWithPatchingMove
179+
180+-- | Apply the insertions, deletions, and moves to a given 'Map'
181+instance Ord k => Patch (PatchMapWithMove k v) where
182+ type PatchTarget (PatchMapWithMove k v) = Map k v
183+ apply (PatchMapWithMove' p) = apply p
184+
185+-- | Returns all the new elements that will be added to the 'Map'.
186+patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
187+patchMapWithMoveNewElements = PM.patchMapWithPatchingMoveNewElements . unPatchMapWithMove'
188+
189+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
190+patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
191+patchMapWithMoveNewElementsMap = PM.patchMapWithPatchingMoveNewElementsMap . unPatchMapWithMove'
192+
193+-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
194+-- its values using the given ordering function. The set keys of the 'Map' is
195+-- not changed.
196+patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
197+patchThatSortsMapWith cmp = PatchMapWithMove' . PM.patchThatSortsMapWith cmp
198+
199+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
200+-- will produce a 'Map' with the same values as the second 'Map' but with the
201+-- values sorted with the given ordering function.
202+patchThatChangesAndSortsMapWith :: (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
203+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
204+ where newList = Map.toList newByIndexUnsorted
205+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
206+
207+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
208+-- will produce the second 'Map'.
209+patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
210+patchThatChangesMap oldByIndex newByIndex = PatchMapWithMove' $
211+ PM.patchThatChangesMap oldByIndex newByIndex
212+
213+--
214+-- NodeInfo
215+--
216+
217+-- | Holds the information about each key: where its new value should come from,
218+-- and where its old value should go to
219+newtype NodeInfo k (v :: Type) = NodeInfo' { unNodeInfo' :: PM.NodeInfo k (Proxy v) }
220+
221+deriving instance (Show k, Show p) => Show (NodeInfo k p)
222+deriving instance (Read k, Read p) => Read (NodeInfo k p)
223+deriving instance (Eq k, Eq p) => Eq (NodeInfo k p)
224+deriving instance (Ord k, Ord p) => Ord (NodeInfo k p)
225+
226+{-# COMPLETE NodeInfo #-}
227+pattern NodeInfo :: To k -> From k v -> NodeInfo k v
228+_nodeInfo_to :: NodeInfo k v -> To k
229+_nodeInfo_from :: NodeInfo k v -> From k v
230+pattern NodeInfo { _nodeInfo_to, _nodeInfo_from } = NodeInfo'
231+ PM.NodeInfo
232+ { PM._nodeInfo_to = _nodeInfo_to
233+ , PM._nodeInfo_from = Coerce _nodeInfo_from
234+ }
235+
236+_NodeInfo
237+ :: Iso
238+ (NodeInfo k0 v0)
239+ (NodeInfo k1 v1)
240+ (PM.NodeInfo k0 (Proxy v0))
241+ (PM.NodeInfo k1 (Proxy v1))
242+_NodeInfo = iso unNodeInfo' NodeInfo'
243+
244+instance Functor (NodeInfo k) where
245+ fmap f = runIdentity . traverse (Identity . f)
246+
247+instance Foldable (NodeInfo k) where
248+ foldMap = foldMapDefault
249+
250+instance Traversable (NodeInfo k) where
251+ traverse = bitraverseNodeInfo pure
252+
253+bitraverseNodeInfo
254+ :: Applicative f
255+ => (k0 -> f k1)
256+ -> (v0 -> f v1)
257+ -> NodeInfo k0 v0 -> f (NodeInfo k1 v1)
258+bitraverseNodeInfo fk fv = fmap NodeInfo'
259+ . PM.bitraverseNodeInfo fk (\ ~Proxy -> pure Proxy) fv
260+ . coerce
261+
262+-- | Change the 'From' value of a 'NodeInfo'
263+nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
264+nodeInfoMapFrom f = coerce $ PM.nodeInfoMapFrom (unFrom' . f . From')
265+
266+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
267+-- 'Applicative', 'Monad', etc.) action to get the new value
268+nodeInfoMapMFrom
269+ :: Functor f
270+ => (From k v -> f (From k v))
271+ -> NodeInfo k v -> f (NodeInfo k v)
272+nodeInfoMapMFrom f = fmap NodeInfo'
273+ . PM.nodeInfoMapMFrom (fmap unFrom' . f . From')
274+ . coerce
275+
276+-- | Set the 'To' field of a 'NodeInfo'
277+nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
278+nodeInfoSetTo = coerce . PM.nodeInfoSetTo
279+
280+--
281+-- From
282+--
283+
284+-- | Describe how a key's new value should be produced
285+newtype From k (v :: Type) = From' { unFrom' :: PM.From k (Proxy v) }
286+
287+{-# COMPLETE From_Insert, From_Delete, From_Move #-}
288+
289+-- | Insert the given value here
290+pattern From_Insert :: v -> From k v
291+pattern From_Insert v = From' (PM.From_Insert v)
292+
293+-- | Delete the existing value, if any, from here
294+pattern From_Delete :: From k v
295+pattern From_Delete = From' PM.From_Delete
296+
297+-- | Move the value here from the given key
298+pattern From_Move :: k -> From k v
299+pattern From_Move k = From' (PM.From_Move k Proxy)
300+
301+bitraverseFrom
302+ :: Applicative f
303+ => (k0 -> f k1)
304+ -> (v0 -> f v1)
305+ -> From k0 v0 -> f (From k1 v1)
306+bitraverseFrom fk fv = fmap From'
307+ . PM.bitraverseFrom fk (\ ~Proxy -> pure Proxy) fv
308+ . coerce
309+
310+makeWrapped ''PatchMapWithMove
311+makeWrapped ''NodeInfo
312+makeWrapped ''From
src/Data/Patch/MapWithPatchingMove.hsnew file+432
@@ -0,0 +1,432 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE PatternGuards #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE StandaloneDeriving #-}
10+{-# LANGUAGE TemplateHaskell #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+
14+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15+-- another
16+module Data.Patch.MapWithPatchingMove
17+ ( PatchMapWithPatchingMove (..)
18+ , patchMapWithPatchingMove
19+ , patchMapWithPatchingMoveInsertAll
20+ , insertMapKey
21+ , moveMapKey
22+ , swapMapKey
23+ , deleteMapKey
24+ , unsafePatchMapWithPatchingMove
25+ , patchMapWithPatchingMoveNewElements
26+ , patchMapWithPatchingMoveNewElementsMap
27+ , patchThatSortsMapWith
28+ , patchThatChangesAndSortsMapWith
29+ , patchThatChangesMap
30+
31+ -- * Node Info
32+ , NodeInfo (..)
33+ , bitraverseNodeInfo
34+ , nodeInfoMapFrom
35+ , nodeInfoMapMFrom
36+ , nodeInfoSetTo
37+
38+ -- * From
39+ , From(..)
40+ , bitraverseFrom
41+
42+ -- * To
43+ , To
44+
45+ -- TODO internals module
46+ , Fixup (..)
47+ ) where
48+
49+import Data.Patch.Class
50+
51+import Control.Lens hiding (from, to)
52+import Control.Lens.TH (makeWrapped)
53+import Data.Align (align)
54+import Data.Foldable (toList)
55+import Data.Function
56+import Data.List
57+import Data.Map (Map)
58+import qualified Data.Map as Map
59+import Data.Maybe
60+#if !MIN_VERSION_base(4,11,0)
61+import Data.Semigroup (Semigroup (..))
62+#endif
63+import Data.Monoid.DecidablyEmpty
64+import Data.Set (Set)
65+import qualified Data.Set as Set
66+import Data.These (These (..))
67+
68+-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
69+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
70+-- and vice versa. There should never be any unpaired From/To keys.
71+newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
72+ { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
73+ unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
74+ }
75+
76+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
77+deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
78+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
79+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
80+
81+deriving instance ( Ord k
82+#if !MIN_VERSION_base(4,11,0)
83+ , Semigroup p
84+#endif
85+ , DecidablyEmpty p
86+ , Patch p
87+ ) => DecidablyEmpty (PatchMapWithPatchingMove k p)
88+
89+-- | Create a 'PatchMapWithPatchingMove', validating it
90+patchMapWithPatchingMove
91+ :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
92+patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
93+ where valid = forwardLinks == backwardLinks
94+ forwardLinks = Map.mapMaybe _nodeInfo_to m
95+ backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
96+ case _nodeInfo_from p of
97+ From_Move from _ -> Just (from, to)
98+ _ -> Nothing
99+
100+-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
101+patchMapWithPatchingMoveInsertAll
102+ :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
103+patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
104+ { _nodeInfo_from = From_Insert v
105+ , _nodeInfo_to = Nothing
106+ }
107+
108+-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
109+insertMapKey
110+ :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
111+insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
112+
113+-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
114+--
115+-- @
116+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
117+-- @
118+moveMapKey
119+ :: ( DecidablyEmpty p
120+#if !MIN_VERSION_base(4,11,0)
121+ , Semigroup p
122+#endif
123+ , Patch p
124+ )
125+ => Ord k => k -> k -> PatchMapWithPatchingMove k p
126+moveMapKey src dst
127+ | src == dst = mempty
128+ | otherwise =
129+ PatchMapWithPatchingMove $ Map.fromList
130+ [ (dst, NodeInfo (From_Move src mempty) Nothing)
131+ , (src, NodeInfo From_Delete (Just dst))
132+ ]
133+
134+-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
135+--
136+-- @
137+-- let aMay = Map.lookup a map
138+-- bMay = Map.lookup b map
139+-- in maybe id (Map.insert a) (bMay <> aMay)
140+-- . maybe id (Map.insert b) (aMay <> bMay)
141+-- . Map.delete a . Map.delete b $ map
142+-- @
143+swapMapKey
144+ :: ( DecidablyEmpty p
145+#if !MIN_VERSION_base(4,11,0)
146+ , Semigroup p
147+#endif
148+ , Patch p
149+ )
150+ => Ord k => k -> k -> PatchMapWithPatchingMove k p
151+swapMapKey src dst
152+ | src == dst = mempty
153+ | otherwise =
154+ PatchMapWithPatchingMove $ Map.fromList
155+ [ (dst, NodeInfo (From_Move src mempty) (Just src))
156+ , (src, NodeInfo (From_Move dst mempty) (Just dst))
157+ ]
158+
159+-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160+-- the mapping, equivalent to 'Map.delete'.
161+deleteMapKey
162+ :: k -> PatchMapWithPatchingMove k v
163+deleteMapKey k = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo From_Delete Nothing
164+
165+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithPatchingMove' k v@, without checking any invariants.
166+--
167+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithPatchingMove' are preserved; they will not be checked.
168+unsafePatchMapWithPatchingMove
169+ :: Map k (NodeInfo k p) -> PatchMapWithPatchingMove k p
170+unsafePatchMapWithPatchingMove = PatchMapWithPatchingMove
171+
172+-- | Apply the insertions, deletions, and moves to a given 'Map'
173+instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
174+ type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
175+ -- TODO: return Nothing sometimes
176+ -- Note: the strict application here is critical to ensuring that incremental
177+ -- merges don't hold onto all their prerequisite events forever; can we make
178+ -- this more robust?
179+ apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
180+ where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
181+ From_Insert v -> Just v
182+ From_Move k p -> applyAlways p <$> Map.lookup k old
183+ From_Delete -> Nothing
184+ deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
185+ From_Delete -> Just ()
186+ _ -> Nothing
187+
188+-- | Returns all the new elements that will be added to the 'Map'
189+patchMapWithPatchingMoveNewElements
190+ :: PatchMapWithPatchingMove k p -> [PatchTarget p]
191+patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
192+
193+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
194+patchMapWithPatchingMoveNewElementsMap
195+ :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
196+patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
197+ where f ni = case _nodeInfo_from ni of
198+ From_Insert v -> Just v
199+ From_Move _ _ -> Nothing
200+ From_Delete -> Nothing
201+
202+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
203+-- its values using the given ordering function. The set keys of the 'Map' is
204+-- not changed.
205+patchThatSortsMapWith
206+ :: (Ord k, Monoid p)
207+ => (PatchTarget p -> PatchTarget p -> Ordering)
208+ -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
209+patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
210+ where unsorted = Map.toList m
211+ sorted = sortBy (cmp `on` snd) unsorted
212+ f (to, _) (from, _) = if to == from then Nothing else
213+ Just (from, to)
214+ reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
215+ g (to, _) (from, _) = if to == from then Nothing else
216+ let Just movingTo = Map.lookup from reverseMapping
217+ in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
218+
219+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
220+-- will produce a 'Map' with the same values as the second 'Map' but with the
221+-- values sorted with the given ordering function.
222+patchThatChangesAndSortsMapWith
223+ :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
224+ => (PatchTarget p -> PatchTarget p -> Ordering)
225+ -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
226+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
227+ where newList = Map.toList newByIndexUnsorted
228+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
229+
230+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
231+-- will produce the second 'Map'.
232+-- Note: this will never produce a patch on a value.
233+patchThatChangesMap
234+ :: forall k p
235+ . (Ord k, Ord (PatchTarget p), Monoid p)
236+ => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
237+patchThatChangesMap oldByIndex newByIndex = patch
238+ where invert :: Map k (PatchTarget p) -> Map (PatchTarget p) (Set k)
239+ invert = Map.fromListWith (<>) . fmap (\(k, v) -> (v, Set.singleton k)) . Map.toList
240+ -- In the places where we use unionDistinct, a non-distinct key indicates a bug in this function
241+ unionDistinct :: forall k' v'. Ord k' => Map k' v' -> Map k' v' -> Map k' v'
242+ unionDistinct = Map.unionWith (error "patchThatChangesMap: non-distinct keys")
243+ unionPairDistinct :: (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k))
244+ unionPairDistinct (oldFroms, oldTos) (newFroms, newTos) = (unionDistinct oldFroms newFroms, unionDistinct oldTos newTos)
245+ -- Generate patch info for a single value
246+ -- Keys that are found in both the old and new sets will not be patched
247+ -- Keys that are found in only the old set will be moved to a new position if any are available; otherwise they will be deleted
248+ -- Keys that are found in only the new set will be populated by moving an old key if any are available; otherwise they will be inserted
249+ patchSingleValue :: PatchTarget p -> Set k -> Set k -> (Map k (From k p), Map k (To k))
250+ patchSingleValue v oldKeys newKeys = foldl' unionPairDistinct mempty $ align (toList $ oldKeys `Set.difference` newKeys) (toList $ newKeys `Set.difference` oldKeys) <&> \case
251+ This oldK -> (mempty, Map.singleton oldK Nothing) -- There's nowhere for this value to go, so we know we are deleting it
252+ That newK -> (Map.singleton newK $ From_Insert v, mempty) -- There's nowhere fo this value to come from, so we know we are inserting it
253+ These oldK newK -> (Map.singleton newK $ From_Move oldK mempty, Map.singleton oldK $ Just newK)
254+ -- Run patchSingleValue on a These. Missing old or new sets are considered empty
255+ patchSingleValueThese :: PatchTarget p -> These (Set k) (Set k) -> (Map k (From k p), Map k (To k))
256+ patchSingleValueThese v = \case
257+ This oldKeys -> patchSingleValue v oldKeys mempty
258+ That newKeys -> patchSingleValue v mempty newKeys
259+ These oldKeys newKeys -> patchSingleValue v oldKeys newKeys
260+ -- Generate froms and tos for all values, then merge them together
261+ (froms, tos) = foldl' unionPairDistinct mempty $ Map.mapWithKey patchSingleValueThese $ align (invert oldByIndex) (invert newByIndex)
262+ patch = unsafePatchMapWithPatchingMove $ align froms tos <&> \case
263+ This from -> NodeInfo from Nothing -- Since we don't have a 'to' record for this key, that must mean it isn't being moved anywhere, so it should be deleted.
264+ That to -> NodeInfo From_Delete to -- Since we don't have a 'from' record for this key, it must be getting deleted
265+ These from to -> NodeInfo from to
266+
267+--
268+-- NodeInfo
269+--
270+
271+-- | Holds the information about each key: where its new value should come from,
272+-- and where its old value should go to
273+data NodeInfo k p = NodeInfo
274+ { _nodeInfo_from :: !(From k p)
275+ -- ^ Where do we get the new value for this key?
276+ , _nodeInfo_to :: !(To k)
277+ -- ^ If the old value is being kept (i.e. moved rather than deleted or
278+ -- replaced), where is it going?
279+ }
280+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
281+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
282+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
283+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
284+
285+-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
286+-- the type families here, this doesn't it any bi- or tri-traversal class.
287+bitraverseNodeInfo
288+ :: Applicative f
289+ => (k0 -> f k1)
290+ -> (p0 -> f p1)
291+ -> (PatchTarget p0 -> f (PatchTarget p1))
292+ -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
293+bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
294+ <$> bitraverseFrom fk fp fpt from
295+ <*> traverse fk to
296+
297+-- | Change the 'From' value of a 'NodeInfo'
298+nodeInfoMapFrom
299+ :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
300+nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
301+
302+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
303+-- 'Applicative', 'Monad', etc.) action to get the new value
304+nodeInfoMapMFrom
305+ :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
306+nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
307+
308+-- | Set the 'To' field of a 'NodeInfo'
309+nodeInfoSetTo
310+ :: To k -> NodeInfo k v -> NodeInfo k v
311+nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
312+
313+--
314+-- From
315+--
316+
317+-- | Describe how a key's new value should be produced
318+data From k p
319+ = From_Insert (PatchTarget p) -- ^ Insert the given value here
320+ | From_Delete -- ^ Delete the existing value, if any, from here
321+ | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
322+
323+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
324+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
325+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
326+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
327+
328+-- | Traverse the 'From' over the key, patch, and patch target. Because of
329+-- the type families here, this doesn't it any bi- or tri-traversal class.
330+bitraverseFrom
331+ :: Applicative f
332+ => (k0 -> f k1)
333+ -> (p0 -> f p1)
334+ -> (PatchTarget p0 -> f (PatchTarget p1))
335+ -> From k0 p0 -> f (From k1 p1)
336+bitraverseFrom fk fp fpt = \case
337+ From_Insert pt -> From_Insert <$> fpt pt
338+ From_Delete -> pure From_Delete
339+ From_Move k p -> From_Move <$> fk k <*> fp p
340+
341+--
342+-- To
343+--
344+
345+-- | Describe where a key's old value will go. If this is 'Just', that means
346+-- the key's old value will be moved to the given other key; if it is 'Nothing',
347+-- that means it will be deleted.
348+type To = Maybe
349+
350+--
351+-- Fixup
352+--
353+
354+-- | Helper data structure used for composing patches using the monoid instance.
355+data Fixup k v
356+ = Fixup_Delete
357+ | Fixup_Update (These (From k v) (To k))
358+
359+-- | Compose patches having the same effect as applying the patches in turn:
360+-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
361+instance ( Ord k
362+#if !MIN_VERSION_base(4,11,0)
363+ , Semigroup p
364+#endif
365+ , DecidablyEmpty p
366+ , Patch p
367+ ) => Semigroup (PatchMapWithPatchingMove k p) where
368+ PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
369+ where
370+ connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
371+ h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
372+ h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
373+ (Just toAfter, From_Move fromBefore p)
374+ | fromBefore == toAfter && isEmpty p
375+ -> [(toAfter, Fixup_Delete)]
376+ | otherwise
377+ -> [ (toAfter, Fixup_Update (This editBefore))
378+ , (fromBefore, Fixup_Update (That mToAfter))
379+ ]
380+ (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
381+ (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
382+ (Nothing, _) -> []
383+ mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
384+ mergeFixups _ (Fixup_Update a) (Fixup_Update b)
385+ | This x <- a, That y <- b
386+ = Fixup_Update $ These x y
387+ | That y <- a, This x <- b
388+ = Fixup_Update $ These x y
389+ mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
390+ fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
391+ combineNodeInfos _ nia nib = NodeInfo
392+ { _nodeInfo_from = _nodeInfo_from nia
393+ , _nodeInfo_to = _nodeInfo_to nib
394+ }
395+ applyFixup _ ni = \case
396+ Fixup_Delete -> Nothing
397+ Fixup_Update u -> Just $ NodeInfo
398+ { _nodeInfo_from = case _nodeInfo_from ni of
399+ f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
400+ Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
401+ Just (From_Insert v) -> From_Insert $ applyAlways p' v
402+ Just From_Delete -> From_Delete
403+ Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
404+ _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
405+ , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
406+ }
407+ m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
408+ getHere :: These a b -> Maybe a
409+ getHere = \case
410+ This a -> Just a
411+ These a _ -> Just a
412+ That _ -> Nothing
413+ getThere :: These a b -> Maybe b
414+ getThere = \case
415+ This _ -> Nothing
416+ These _ b -> Just b
417+ That b -> Just b
418+
419+--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
420+-- | Compose patches having the same effect as applying the patches in turn:
421+-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
422+instance ( Ord k
423+#if !MIN_VERSION_base(4,11,0)
424+ , Semigroup p
425+#endif
426+ , DecidablyEmpty p
427+ , Patch p
428+ ) => Monoid (PatchMapWithPatchingMove k p) where
429+ mempty = PatchMapWithPatchingMove mempty
430+ mappend = (<>)
431+
432+makeWrapped ''PatchMapWithPatchingMove
src/Data/Semigroup/Additive.hsnew file+54
@@ -0,0 +1,54 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE TypeOperators #-}
3+{-# LANGUAGE TypeFamilies #-}
4+-- |
5+-- Module:
6+-- Data.Semigroup.Additive
7+-- Description:
8+-- This module defines a class for commutative semigroups, until it is moved
9+-- to another library.
10+module Data.Semigroup.Additive
11+ ( Additive
12+ ) where
13+
14+import Data.Functor.Const (Const (..))
15+import Data.Functor.Identity
16+import Data.Proxy
17+#if !MIN_VERSION_base(4,12,0)
18+-- for :*: and :.: semigroup instances
19+import Data.Orphans ()
20+#endif
21+#if !MIN_VERSION_base(4,11,0)
22+import Data.Semigroup (Semigroup (..))
23+#endif
24+import GHC.Generics
25+
26+-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
27+class Semigroup q => Additive q where
28+
29+-- | Trivial additive semigroup.
30+instance Additive ()
31+
32+-- | Product additive semigroup.
33+-- A Pair of additive semigroups gives rise to a additive semigroup
34+instance (Additive a, Additive b) => Additive (a, b)
35+
36+-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
37+-- Base does not define Monoid (Compose f g a) so this is the best we can
38+-- really do for functor composition.
39+instance Additive (f (g a)) => Additive ((f :.: g) a)
40+
41+-- | Product of additive semigroups, Functor style.
42+instance (Additive (f a), Additive (g a)) => Additive ((f :*: g) a)
43+
44+-- | Trivial additive semigroup, Functor style
45+instance Additive (Proxy x)
46+
47+-- | Const lifts additive semigroups into a functor.
48+instance Additive a => Additive (Const a x)
49+
50+-- | Identity lifts additive semigroups pointwise (at only one point)
51+instance Additive a => Additive (Identity a)
52+
53+-- | Functions lift additive semigroups pointwise.
54+instance Additive b => Additive (a -> b)
src/Data/WeakBag.hsdeleted−121
@@ -1,121 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ExistentialQuantification #-}
4−#ifdef USE_REFLEX_OPTIMIZER
5−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
6−#endif
7−-- | This module defines the 'WeakBag' type, which represents a mutable
8−-- collection of items that does not cause the items to be retained in memory.
9−-- This is useful for situations where a value needs to be inspected or modified
10−-- if it is still alive, but can be ignored if it is dead.
11−module Data.WeakBag
12− ( WeakBag
13− , WeakBagTicket
14− , empty
15− , singleton
16− , insert
17− , traverse
18− , remove
19− -- * Internal functions
20− -- These will not always be available.
21− , _weakBag_children --TODO: Don't export this
22− ) where
23−
24−import Prelude hiding (traverse)
25−
26−import Control.Exception
27−import Control.Monad
28−import Control.Monad.IO.Class
29−import Data.IntMap.Strict (IntMap)
30−import qualified Data.IntMap.Strict as IntMap
31−import Data.IORef
32−import System.Mem.Weak
33−
34−-- | A 'WeakBag' holds a set of values of type @/a/@, but does not retain them -
35−-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
36−-- alive, the 'WeakBag' will continue to refer to them.
37−data WeakBag a = WeakBag
38− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
39− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ The items referenced by the WeakBag
40− }
41−
42−-- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned. If
43−-- the caller retains the ticket, the item is guranteed to stay in memory (and
44−-- thus in the 'WeakBag'). The ticket can also be used to remove the item from
45−-- the 'WeakBag' prematurely (i.e. while it is still alive), using 'remove'.
46−data WeakBagTicket = forall a. WeakBagTicket
47− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
48− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
49− }
50−
51−-- | Insert an item into a 'WeakBag'.
52−{-# INLINE insert #-}
53−insert :: a -- ^ The item
54− -> WeakBag a -- ^ The 'WeakBag' to insert into
55− -> IORef (Weak b) -- ^ An arbitrary value to be used in the following
56− -- callback
57− -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed
58− -- (whether automatically by the item being garbage
59− -- collected or manually via 'remove')
60− -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item
61− -- is retained and allows the item to be removed.
62−insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do
63− a' <- evaluate a
64− wbRef' <- evaluate wbRef
65− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
66− let cleanup = do
67− wb <- readIORef wbRef'
68− mb <- deRefWeak wb
69− forM_ mb $ \b -> do
70− csWithoutMe <- atomicModifyIORef children $ \cs ->
71− let !csWithoutMe = IntMap.delete myId cs
72− in (csWithoutMe, csWithoutMe)
73− when (IntMap.null csWithoutMe) $ finalizer b
74− wa <- mkWeakPtr a' $ Just cleanup
75− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
76− return $ WeakBagTicket
77− { _weakBagTicket_weakItem = wa
78− , _weakBagTicket_item = a'
79− }
80−
81−-- | Create an empty 'WeakBag'.
82−{-# INLINE empty #-}
83−empty :: IO (WeakBag a)
84−empty = {-# SCC "empty" #-} do
85− nextId <- newIORef 1
86− children <- newIORef IntMap.empty
87− let bag = WeakBag
88− { _weakBag_nextId = nextId
89− , _weakBag_children = children
90− }
91− return bag
92−
93−-- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with
94−-- 'empty', then using 'insert'.
95−{-# INLINE singleton #-}
96−singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
97−singleton a wbRef finalizer = {-# SCC "singleton" #-} do
98− bag <- empty
99− ticket <- insert a bag wbRef finalizer
100− return (bag, ticket)
101−
102−{-# INLINE traverse #-}
103−-- | Visit every node in the given list. If new nodes are appended during the
104−-- traversal, they will not be visited. Every live node that was in the list
105−-- when the traversal began will be visited exactly once; however, no guarantee
106−-- is made about the order of the traversal.
107−traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
108−traverse (WeakBag _ children) f = {-# SCC "traverse" #-} do
109− cs <- liftIO $ readIORef children
110− forM_ cs $ \c -> do
111− ma <- liftIO $ deRefWeak c
112− mapM_ f ma
113−
114−-- | Remove an item from the 'WeakBag'; does nothing if invoked multiple times
115−-- on the same 'WeakBagTicket'.
116−{-# INLINE remove #-}
117−remove :: WeakBagTicket -> IO ()
118−remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w
119−--TODO: Should 'remove' also drop the reference to the item?
120−
121−--TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hsdeleted−35
@@ -1,35 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−-- | This module exports all of the commonly-used functionality of Reflex; if
3−-- you are just getting started with Reflex, this is probably what you want.
4−module Reflex
5− ( module X
6− ) where
7−
8−import Reflex.Class as X
9−import Reflex.Adjustable.Class as X
10−import Reflex.BehaviorWriter.Base as X
11−import Reflex.BehaviorWriter.Class as X
12−import Reflex.Collection as X
13−import Reflex.Dynamic as X
14−import Reflex.EventWriter.Base as X
15−import Reflex.EventWriter.Class as X
16−#ifdef USE_TEMPLATE_HASKELL
17−import Reflex.Dynamic.TH as X
18−#endif
19−import Reflex.Dynamic.Uniq as X
20−import Reflex.DynamicWriter.Base as X
21−import Reflex.DynamicWriter.Class as X
22−import Reflex.NotReady.Class as X
23−import Reflex.PerformEvent.Base as X
24−import Reflex.PerformEvent.Class as X
25−import Reflex.PostBuild.Base as X
26−import Reflex.PostBuild.Class as X
27−import Reflex.Profiled as X
28−import Reflex.Query.Base as X
29−import Reflex.Query.Class as X
30−import Reflex.Requester.Base as X
31−import Reflex.Requester.Class as X
32−import Reflex.Spider as X
33−import Reflex.Time as X
34−import Reflex.TriggerEvent.Base as X
35−import Reflex.TriggerEvent.Class as X
src/Reflex/Adjustable/Class.hsdeleted−140
@@ -1,140 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−#ifdef USE_REFLEX_OPTIMIZER
12−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
13−#endif
14−-- |
15−-- Module:
16−-- Reflex.Adjustable.Class
17−-- Description:
18−-- A class for actions that can be "adjusted" over time based on some 'Event'
19−-- such that, when observed after the firing of any such 'Event', the result
20−-- is as though the action was originally run with the 'Event's value.
21−module Reflex.Adjustable.Class
22− (
23− -- * The Adjustable typeclass
24− Adjustable(..)
25− , sequenceDMapWithAdjust
26− , sequenceDMapWithAdjustWithMove
27− , mapMapWithAdjustWithMove
28− -- * Deprecated aliases
29− , MonadAdjust
30− ) where
31−
32−import Control.Monad.Identity
33−import Control.Monad.Reader
34−import Data.Dependent.Map (DMap, GCompare (..))
35−import qualified Data.Dependent.Map as DMap
36−import Data.Functor.Constant
37−import Data.Functor.Misc
38−import Data.IntMap.Strict (IntMap)
39−import qualified Data.IntMap.Strict as IntMap
40−import Data.Map (Map)
41−
42−import Reflex.Class
43−import Reflex.Patch.DMapWithMove
44−
45−-- | A 'Monad' that supports adjustment over time. After an action has been
46−-- run, if the given events fire, it will adjust itself so that its net effect
47−-- is as though it had originally been run with the new value. Note that there
48−-- is some issue here with persistent side-effects: obviously, IO (and some
49−-- other side-effects) cannot be undone, so it is up to the instance implementer
50−-- to determine what the best meaning for this class is in such cases.
51−class (Reflex t, Monad m) => Adjustable t m | m -> t where
52− runWithReplace
53− :: m a
54− -> Event t (m b)
55− -> m (a, Event t b)
56−
57− traverseIntMapWithKeyWithAdjust
58− :: (IntMap.Key -> v -> m v')
59− -> IntMap v
60− -> Event t (PatchIntMap v)
61− -> m (IntMap v', Event t (PatchIntMap v'))
62−
63− traverseDMapWithKeyWithAdjust
64− :: GCompare k
65− => (forall a. k a -> v a -> m (v' a))
66− -> DMap k v
67− -> Event t (PatchDMap k v)
68− -> m (DMap k v', Event t (PatchDMap k v'))
69− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
70− traverseDMapWithKeyWithAdjust f dm0 dm' = fmap (fmap (fmap fromPatchWithMove)) $
71− traverseDMapWithKeyWithAdjustWithMove f dm0 $ fmap toPatchWithMove dm'
72− where
73− toPatchWithMove (PatchDMap m) = PatchDMapWithMove $ DMap.map toNodeInfoWithMove m
74− toNodeInfoWithMove = \case
75− ComposeMaybe (Just v) -> NodeInfo (From_Insert v) $ ComposeMaybe Nothing
76− ComposeMaybe Nothing -> NodeInfo From_Delete $ ComposeMaybe Nothing
77− fromPatchWithMove (PatchDMapWithMove m) = PatchDMap $ DMap.map fromNodeInfoWithMove m
78− fromNodeInfoWithMove (NodeInfo from _) = ComposeMaybe $ case from of
79− From_Insert v -> Just v
80− From_Delete -> Nothing
81− From_Move _ -> error "traverseDMapWithKeyWithAdjust: implementation of traverseDMapWithKeyWithAdjustWithMove inserted spurious move"
82−
83− traverseDMapWithKeyWithAdjustWithMove
84− :: GCompare k
85− => (forall a. k a -> v a -> m (v' a))
86− -> DMap k v
87− -> Event t (PatchDMapWithMove k v)
88− -> m (DMap k v', Event t (PatchDMapWithMove k v'))
89−
90−instance Adjustable t m => Adjustable t (ReaderT r m) where
91− runWithReplace a0 a' = do
92− r <- ask
93− lift $ runWithReplace (runReaderT a0 r) $ fmap (`runReaderT` r) a'
94− traverseIntMapWithKeyWithAdjust f dm0 dm' = do
95− r <- ask
96− lift $ traverseIntMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm'
97− traverseDMapWithKeyWithAdjust f dm0 dm' = do
98− r <- ask
99− lift $ traverseDMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm'
100− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
101− r <- ask
102− lift $ traverseDMapWithKeyWithAdjustWithMove (\k v -> runReaderT (f k v) r) dm0 dm'
103−
104−-- | Traverse a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches
105−-- to the 'DMap' can add, remove, or update values.
106−sequenceDMapWithAdjust
107− :: (GCompare k, Adjustable t m)
108− => DMap k m
109− -> Event t (PatchDMap k m)
110− -> m (DMap k Identity, Event t (PatchDMap k Identity))
111−sequenceDMapWithAdjust = traverseDMapWithKeyWithAdjust $ \_ -> fmap Identity
112−
113−-- | Traverses a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches
114−-- to the 'DMap' can add, remove, update, move, or swap values.
115−sequenceDMapWithAdjustWithMove
116− :: (GCompare k, Adjustable t m)
117− => DMap k m
118− -> Event t (PatchDMapWithMove k m)
119− -> m (DMap k Identity, Event t (PatchDMapWithMove k Identity))
120−sequenceDMapWithAdjustWithMove = traverseDMapWithKeyWithAdjustWithMove $ \_ -> fmap Identity
121−
122−-- | Traverses a 'Map', running the provided 'Adjustable' action. The provided 'Event' of patches to the 'Map'
123−-- can add, remove, update, move, or swap values.
124−mapMapWithAdjustWithMove
125− :: forall t m k v v'. (Adjustable t m, Ord k)
126− => (k -> v -> m v')
127− -> Map k v
128− -> Event t (PatchMapWithMove k v)
129− -> m (Map k v', Event t (PatchMapWithMove k v'))
130−mapMapWithAdjustWithMove f m0 m' = do
131− (out0 :: DMap (Const2 k v) (Constant v'), out') <- traverseDMapWithKeyWithAdjustWithMove (\(Const2 k) (Identity v) -> Constant <$> f k v) (mapToDMap m0) (const2PatchDMapWithMoveWith Identity <$> m')
132− return (dmapToMapWith (\(Constant v') -> v') out0, patchDMapWithMoveToPatchMapWithMoveWith (\(Constant v') -> v') <$> out')
133−
134−--------------------------------------------------------------------------------
135−-- Deprecated functions
136−--------------------------------------------------------------------------------
137−
138−{-# DEPRECATED MonadAdjust "Use Adjustable instead" #-}
139−-- | Synonym for 'Adjustable'
140−type MonadAdjust = Adjustable
src/Reflex/BehaviorWriter/Base.hsdeleted−202
@@ -1,202 +0,0 @@
1−{-|
2−Module: Reflex.BehaviorWriter.Base
3−Description: Implementation of MonadBehaviorWriter
4−-}
5−{-# LANGUAGE CPP #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE GADTs #-}
8−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−{-# LANGUAGE StandaloneDeriving #-}
15−#ifdef USE_REFLEX_OPTIMIZER
16−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
17−#endif
18−module Reflex.BehaviorWriter.Base
19− ( BehaviorWriterT (..)
20− , runBehaviorWriterT
21− , withBehaviorWriterT
22− ) where
23−
24−import Control.Monad.Exception
25−import Control.Monad.Identity
26−import Control.Monad.IO.Class
27−import Control.Monad.Reader
28−import Control.Monad.Ref
29−import Control.Monad.State.Strict
30−import Data.Dependent.Map (DMap)
31−import qualified Data.Dependent.Map as DMap
32−import Data.Functor.Misc
33−import Data.IntMap (IntMap)
34−import qualified Data.IntMap as IntMap
35−import Data.Map (Map)
36−import qualified Data.Map as Map
37−import Data.Some (Some)
38−
39−import Reflex.Class
40−import Reflex.Adjustable.Class
41−import Reflex.BehaviorWriter.Class
42−import Reflex.Host.Class
43−import Reflex.PerformEvent.Class
44−import Reflex.PostBuild.Class
45−import Reflex.Query.Class
46−import Reflex.Requester.Class
47−import Reflex.TriggerEvent.Class
48−
49−-- | A basic implementation of 'MonadBehaviorWriter'.
50−newtype BehaviorWriterT t w m a = BehaviorWriterT { unBehaviorWriterT :: StateT [Behavior t w] m a }
51− deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadAsyncException, MonadException) -- The list is kept in reverse order
52−
53−-- | Run a 'BehaviorWriterT' action. The behavior writer output will be provided
54−-- along with the result of the action.
55−runBehaviorWriterT :: (Monad m, Reflex t, Monoid w) => BehaviorWriterT t w m a -> m (a, Behavior t w)
56−runBehaviorWriterT (BehaviorWriterT a) = do
57− (result, ws) <- runStateT a []
58− return (result, mconcat $ reverse ws)
59−
60−-- | Map a function over the output of a 'BehaviorWriterT'.
61−withBehaviorWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m)
62− => (w -> w')
63− -> BehaviorWriterT t w m a
64− -> BehaviorWriterT t w' m a
65−withBehaviorWriterT f dw = do
66− (r, d) <- lift $ do
67− (r, d) <- runBehaviorWriterT dw
68− let d' = fmap f d
69− return (r, d')
70− tellBehavior d
71− return r
72−
73−deriving instance MonadHold t m => MonadHold t (BehaviorWriterT t w m)
74−deriving instance MonadSample t m => MonadSample t (BehaviorWriterT t w m)
75−
76−instance MonadTrans (BehaviorWriterT t w) where
77− lift = BehaviorWriterT . lift
78−
79−instance MonadRef m => MonadRef (BehaviorWriterT t w m) where
80− type Ref (BehaviorWriterT t w m) = Ref m
81− newRef = lift . newRef
82− readRef = lift . readRef
83− writeRef r = lift . writeRef r
84−
85−instance MonadAtomicRef m => MonadAtomicRef (BehaviorWriterT t w m) where
86− atomicModifyRef r = lift . atomicModifyRef r
87−
88−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (BehaviorWriterT t w m) where
89− newEventWithTrigger = lift . newEventWithTrigger
90− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
91−
92−instance (Monad m, Monoid w, Reflex t) => MonadBehaviorWriter t w (BehaviorWriterT t w m) where
93− tellBehavior w = BehaviorWriterT $ modify (w :)
94−
95−instance MonadReader r m => MonadReader r (BehaviorWriterT t w m) where
96− ask = lift ask
97− local f (BehaviorWriterT a) = BehaviorWriterT $ mapStateT (local f) a
98− reader = lift . reader
99−
100−instance PerformEvent t m => PerformEvent t (BehaviorWriterT t w m) where
101− type Performable (BehaviorWriterT t w m) = Performable m
102− performEvent_ = lift . performEvent_
103− performEvent = lift . performEvent
104−
105−instance TriggerEvent t m => TriggerEvent t (BehaviorWriterT t w m) where
106− newTriggerEvent = lift newTriggerEvent
107− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
108− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
109−
110−instance PostBuild t m => PostBuild t (BehaviorWriterT t w m) where
111− getPostBuild = lift getPostBuild
112−
113−instance MonadState s m => MonadState s (BehaviorWriterT t w m) where
114− get = lift get
115− put = lift . put
116−
117−instance Requester t m => Requester t (BehaviorWriterT t w m) where
118− type Request (BehaviorWriterT t w m) = Request m
119− type Response (BehaviorWriterT t w m) = Response m
120− requesting = lift . requesting
121− requesting_ = lift . requesting_
122−
123−instance (MonadQuery t q m, Monad m) => MonadQuery t q (BehaviorWriterT t w m) where
124− tellQueryIncremental = lift . tellQueryIncremental
125− askQueryResult = lift askQueryResult
126− queryIncremental = lift . queryIncremental
127−
128−instance (Adjustable t m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (BehaviorWriterT t w m) where
129− runWithReplace a0 a' = do
130− (result0, result') <- lift $ runWithReplace (runBehaviorWriterT a0) $ runBehaviorWriterT <$> a'
131− tellBehavior . join =<< hold (snd result0) (snd <$> result')
132− return (fst result0, fst <$> result')
133− traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust
134− traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith
135−
136−traverseIntMapWithKeyWithAdjustImpl
137− :: forall t w v' p p' v m.
138− ( PatchTarget (p' (Behavior t w)) ~ IntMap (Behavior t w)
139− , Patch (p' (Behavior t w))
140− , Monoid w
141− , Reflex t
142− , MonadHold t m
143− , Functor p
144− , p ~ p'
145− )
146− => ( (IntMap.Key -> v -> m (v', Behavior t w))
147− -> IntMap v
148− -> Event t (p v)
149− -> m (IntMap (v', Behavior t w), Event t (p (v', Behavior t w)))
150− )
151− -> (IntMap.Key -> v -> BehaviorWriterT t w m v')
152− -> IntMap v
153− -> Event t (p v)
154− -> BehaviorWriterT t w m (IntMap v', Event t (p v'))
155−traverseIntMapWithKeyWithAdjustImpl base f (dm0 :: IntMap v) dm' = do
156− (result0, result') <- lift $ base (\k v -> runBehaviorWriterT $ f k v) dm0 dm'
157− let liftedResult0 = fmap fst result0
158− liftedResult' = fmap (fmap fst) result'
159− liftedWritten0 :: IntMap (Behavior t w)
160− liftedWritten0 = fmap snd result0
161− liftedWritten' = fmap (fmap snd) result'
162− i <- holdIncremental liftedWritten0 liftedWritten'
163− tellBehavior $ pull $ do
164− m <- sample $ currentIncremental i
165− mconcat . IntMap.elems <$> traverse sample m
166− return (liftedResult0, liftedResult')
167−
168−newtype BehaviorWriterTLoweredResult t w v a = BehaviorWriterTLoweredResult (v a, Behavior t w)
169−
170−traverseDMapWithKeyWithAdjustImpl
171− :: forall t w k v' p p' v m.
172− ( PatchTarget (p' (Some k) (Behavior t w)) ~ Map (Some k) (Behavior t w)
173− , Patch (p' (Some k) (Behavior t w))
174− , Monoid w
175− , Reflex t
176− , MonadHold t m
177− )
178− => ( (forall a. k a -> v a -> m (BehaviorWriterTLoweredResult t w v' a))
179− -> DMap k v
180− -> Event t (p k v)
181− -> m (DMap k (BehaviorWriterTLoweredResult t w v'), Event t (p k (BehaviorWriterTLoweredResult t w v')))
182− )
183− -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> v' a) -> p k (BehaviorWriterTLoweredResult t w v') -> p k v')
184− -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> Behavior t w) -> p k (BehaviorWriterTLoweredResult t w v') -> p' (Some k) (Behavior t w))
185− -> (forall a. k a -> v a -> BehaviorWriterT t w m (v' a))
186− -> DMap k v
187− -> Event t (p k v)
188− -> BehaviorWriterT t w m (DMap k v', Event t (p k v'))
189−traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith f (dm0 :: DMap k v) dm' = do
190− (result0, result') <- lift $ base (\k v -> fmap BehaviorWriterTLoweredResult $ runBehaviorWriterT $ f k v) dm0 dm'
191− let getValue (BehaviorWriterTLoweredResult (v, _)) = v
192− getWritten (BehaviorWriterTLoweredResult (_, w)) = w
193− liftedResult0 = DMap.map getValue result0
194− liftedResult' = ffor result' $ mapPatch getValue
195− liftedWritten0 :: Map (Some k) (Behavior t w)
196− liftedWritten0 = weakenDMapWith getWritten result0
197− liftedWritten' = ffor result' $ weakenPatchWith getWritten
198− i <- holdIncremental liftedWritten0 liftedWritten'
199− tellBehavior $ pull $ do
200− m <- sample $ currentIncremental i
201− mconcat . Map.elems <$> traverse sample m
202− return (liftedResult0, liftedResult')
src/Reflex/BehaviorWriter/Class.hsdeleted−26
@@ -1,26 +0,0 @@
1−{-|
2−Module: Reflex.BehaviorWriter.Class
3−Description: This module defines the 'MonadBehaviorWriter' class
4−-}
5−{-# LANGUAGE CPP #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−#ifdef USE_REFLEX_OPTIMIZER
11−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12−#endif
13−module Reflex.BehaviorWriter.Class
14− ( MonadBehaviorWriter (..)
15− ) where
16−
17−import Control.Monad.Reader (ReaderT, lift)
18−import Reflex.Class (Behavior)
19−
20−-- | 'MonadBehaviorWriter' efficiently collects 'Behavior' values using 'tellBehavior'
21−-- and combines them monoidally to provide a 'Behavior' result.
22−class (Monad m, Monoid w) => MonadBehaviorWriter t w m | m -> t w where
23− tellBehavior :: Behavior t w -> m ()
24−
25−instance MonadBehaviorWriter t w m => MonadBehaviorWriter t w (ReaderT r m) where
26− tellBehavior = lift . tellBehavior
src/Reflex/Class.hsdeleted−1591
@@ -1,1591 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE DefaultSignatures #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE LambdaCase #-}
10−{-# LANGUAGE MultiParamTypeClasses #-}
11−{-# LANGUAGE NoMonomorphismRestriction #-}
12−{-# LANGUAGE PolyKinds #-}
13−{-# LANGUAGE RankNTypes #-}
14−{-# LANGUAGE RecursiveDo #-}
15−{-# LANGUAGE RoleAnnotations #-}
16−{-# LANGUAGE ScopedTypeVariables #-}
17−{-# LANGUAGE TypeFamilies #-}
18−{-# LANGUAGE TypeOperators #-}
19−{-# LANGUAGE UndecidableInstances #-}
20−#ifdef USE_REFLEX_OPTIMIZER
21−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
22−#endif
23−
24−-- |
25−-- Module:
26−-- Reflex.Class
27−-- Description:
28−-- This module contains the Reflex interface, as well as a variety of
29−-- convenience functions for working with 'Event's, 'Behavior's, and other
30−-- signals.
31−module Reflex.Class
32− ( module Reflex.Patch
33− -- * Primitives
34− , Reflex (..)
35− , mergeInt
36− , coerceBehavior
37− , coerceEvent
38− , coerceDynamic
39− , MonadSample (..)
40− , MonadHold (..)
41− -- ** 'fan' related types
42− , EventSelector (..)
43− , EventSelectorInt (..)
44− -- * Convenience functions
45− , constDyn
46− , pushAlways
47− -- ** Combining 'Event's
48− , leftmost
49− , mergeMap
50− , mergeIntMap
51− , mergeMapIncremental
52− , mergeMapIncrementalWithMove
53− , mergeIntMapIncremental
54− , coincidencePatchMap
55− , coincidencePatchMapWithMove
56− , coincidencePatchIntMap
57− , mergeList
58− , mergeWith
59− , difference
60− , alignEventWithMaybe
61− -- ** Breaking up 'Event's
62− , splitE
63− , fanEither
64− , fanThese
65− , fanMap
66− , dmapToThese
67− , EitherTag (..)
68− , eitherToDSum
69− , dsumToEither
70− , factorEvent
71− , filterEventKey
72− -- ** Collapsing 'Event . Event'
73− , switchHold
74− , switchHoldPromptly
75− , switchHoldPromptOnly
76− , switchHoldPromptOnlyIncremental
77− -- ** Using 'Event's to sample 'Behavior's
78− , tag
79− , tagMaybe
80− , attach
81− , attachWith
82− , attachWithMaybe
83− -- ** Blocking an 'Event' based on a 'Behavior'
84− , gate
85− -- ** Combining 'Dynamic's
86− , distributeDMapOverDynPure
87− , distributeListOverDyn
88− , distributeListOverDynWith
89− , zipDyn
90− , zipDynWith
91− -- ** Accumulating state
92− , Accumulator (..)
93− , accumDyn
94− , accumMDyn
95− , accumMaybeDyn
96− , accumMaybeMDyn
97− , mapAccumDyn
98− , mapAccumMDyn
99− , mapAccumMaybeDyn
100− , mapAccumMaybeMDyn
101− , accumB
102− , accumMB
103− , accumMaybeB
104− , accumMaybeMB
105− , mapAccumB
106− , mapAccumMB
107− , mapAccumMaybeB
108− , mapAccumMaybeMB
109− , mapAccum_
110− , mapAccumM_
111− , mapAccumMaybe_
112− , mapAccumMaybeM_
113− , accumIncremental
114− , accumMIncremental
115− , accumMaybeIncremental
116− , accumMaybeMIncremental
117− , mapAccumIncremental
118− , mapAccumMIncremental
119− , mapAccumMaybeIncremental
120− , mapAccumMaybeMIncremental
121− , zipListWithEvent
122− , numberOccurrences
123− , numberOccurrencesFrom
124− , numberOccurrencesFrom_
125− , (<@>)
126− , (<@)
127− , tailE
128− , headTailE
129− , takeWhileE
130− , takeWhileJustE
131− , dropWhileE
132− , takeDropWhileJustE
133− , switcher
134− -- * Debugging functions
135− , traceEvent
136− , traceEventWith
137− -- * Unsafe functions
138− , unsafeDynamic
139− , unsafeMapIncremental
140− -- * 'Filterable' convenience functions
141− , FunctorMaybe -- fmapMaybe is purposely not exported from deprecated 'FunctorMaybe' and the new alias is exported instead
142− , mapMaybe -- Re-exported for convenience
143− , fmapMaybe
144− , fforMaybe
145− , ffilter
146− , filterLeft
147− , filterRight
148− -- * Miscellaneous convenience functions
149− , ffor
150− , ffor2
151− , ffor3
152− -- * Deprecated functions
153− , switchPromptly
154− , switchPromptOnly
155− -- * "Cheap" functions
156− , fmapMaybeCheap
157− , mapMaybeCheap
158− , fmapCheap
159− , fforCheap
160− , fforMaybeCheap
161− , pushAlwaysCheap
162− , tagCheap
163− , mergeWithCheap
164− , mergeWithCheap'
165− -- * Slow, but general, implementations
166− , slowHeadE
167− ) where
168−
169−import Control.Applicative
170−import Control.Monad.Identity
171−import Control.Monad.Reader
172−import Control.Monad.State.Strict
173−import Control.Monad.Trans.Cont (ContT)
174−import Control.Monad.Trans.Except (ExceptT)
175−import Control.Monad.Trans.RWS (RWST)
176−import Control.Monad.Trans.Writer (WriterT)
177−import Data.Align
178−import Data.Bifunctor
179−import Data.Coerce
180−import Data.Default
181−import Data.Dependent.Map (DMap, DSum (..))
182−import qualified Data.Dependent.Map as DMap
183−import Data.Functor.Compose
184−import Data.Functor.Product
185−import Data.GADT.Compare (GEq (..), GCompare (..), (:~:) (..))
186−import Data.FastMutableIntMap (PatchIntMap)
187−import Data.Foldable
188−import Data.Functor.Bind
189−import Data.Functor.Misc
190−import Data.Functor.Plus
191−import Data.IntMap.Strict (IntMap)
192−import qualified Data.IntMap.Strict as IntMap
193−import Data.List.NonEmpty (NonEmpty (..))
194−import Data.Map (Map)
195−import Data.Semigroup (Semigroup, sconcat, stimes, (<>))
196−import Data.Some (Some)
197−import qualified Data.Some as Some
198−import Data.String
199−import Data.These
200−import Data.Type.Coercion
201−import Data.Witherable (Filterable(..))
202−import qualified Data.Witherable as W
203−import Reflex.FunctorMaybe (FunctorMaybe)
204−import qualified Reflex.FunctorMaybe
205−import Reflex.Patch
206−import qualified Reflex.Patch.MapWithMove as PatchMapWithMove
207−
208−import Debug.Trace (trace)
209−
210−-- | The 'Reflex' class contains all the primitive functionality needed for
211−-- Functional Reactive Programming (FRP). The @/t/@ type parameter indicates
212−-- which "timeline" is in use. Timelines are fully-independent FRP contexts,
213−-- and the type of the timeline determines the FRP engine to be used. For most
214−-- purposes, the 'Reflex.Spider' implementation is recommended.
215−class ( MonadHold t (PushM t)
216− , MonadSample t (PullM t)
217− , MonadFix (PushM t)
218− , Functor (Dynamic t)
219− , Applicative (Dynamic t) -- Necessary for GHC <= 7.8
220− , Monad (Dynamic t)
221− ) => Reflex t where
222− -- | A container for a value that can change over time. 'Behavior's can be
223− -- sampled at will, but it is not possible to be notified when they change
224− data Behavior t :: * -> *
225− -- | A stream of occurrences. During any given frame, an 'Event' is either
226− -- occurring or not occurring; if it is occurring, it will contain a value of
227− -- the given type (its "occurrence type")
228− data Event t :: * -> *
229− -- | A container for a value that can change over time and allows
230− -- notifications on changes. Basically a combination of a 'Behavior' and an
231− -- 'Event', with a rule that the 'Behavior' will change if and only if the
232− -- 'Event' fires.
233− data Dynamic t :: * -> *
234− -- | An 'Incremental' is a more general form of a 'Dynamic'.
235− -- Instead of always fully replacing the value, only parts of it can be patched.
236− -- This is only needed for performance critical code via `mergeIncremental` to make small
237− -- changes to large values.
238− data Incremental t :: * -> *
239− -- | A monad for doing complex push-based calculations efficiently
240− type PushM t :: * -> *
241− -- | A monad for doing complex pull-based calculations efficiently
242− type PullM t :: * -> *
243− -- | An 'Event' with no occurrences
244− never :: Event t a
245− -- | Create a 'Behavior' that always has the given value
246− constant :: a -> Behavior t a --TODO: Refactor to use 'pure' from Applicative instead; however, we need to make sure that encouraging Applicative-style use of 'Behavior's doesn't have a negative performance impact
247− -- | Create an 'Event' from another 'Event'; the provided function can sample
248− -- 'Behavior's and hold 'Event's, and use the results to produce a occurring
249− -- (Just) or non-occurring (Nothing) result
250− push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
251− -- | Like 'push' but intended for functions that the implementation can consider cheap to compute for performance considerations. WARNING: The function passed to 'pushCheap' may be run multiple times without any caching.
252− pushCheap :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
253− -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be
254− -- recomputed whenever any of the read 'Behavior's changes
255− pull :: PullM t a -> Behavior t a
256− -- | Merge a collection of events; the resulting 'Event' will only occur if at
257− -- least one input event is occurring, and will contain all of the input keys
258− -- that are occurring simultaneously
259− merge :: GCompare k => DMap k (Event t) -> Event t (DMap k Identity) --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
260− -- | Efficiently fan-out an event to many destinations. This function should
261− -- be partially applied, and then the result applied repeatedly to create
262− -- child events
263− fan :: GCompare k => Event t (DMap k Identity) -> EventSelector t k --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
264− -- | Create an 'Event' that will occur whenever the currently-selected input
265− -- 'Event' occurs
266− switch :: Behavior t (Event t a) -> Event t a
267− -- | Create an 'Event' that will occur whenever the input event is occurring -- and its occurrence value, another 'Event', is also occurring
268− coincidence :: Event t (Event t a) -> Event t a
269− -- | Extract the 'Behavior' of a 'Dynamic'.
270− current :: Dynamic t a -> Behavior t a
271− -- | Extract the 'Event' of the 'Dynamic'.
272− updated :: Dynamic t a -> Event t a
273− -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
274− -- recent firing of the given 'Event', if any.
275− unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
276− -- | Create a new 'Incremental'. The given "PullM"'s value must always change
277− -- in the same way that the accumulated application of patches would change
278− -- that value.
279− unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
280− -- | Create a merge whose parents can change over time
281− mergeIncremental :: GCompare k => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
282− -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
283− mergeIncrementalWithMove :: GCompare k => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity)
284− -- | Extract the 'Behavior' component of an 'Incremental'
285− currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
286− -- | Extract the 'Event' component of an 'Incremental'
287− updatedIncremental :: Patch p => Incremental t p -> Event t p
288− -- | Convert an 'Incremental' to a 'Dynamic'
289− incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
290− -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
291− -- occurrence type
292− behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
293− -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
294− -- occurrence type
295− eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
296− -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
297− -- occurrence type
298− dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
299− mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
300− fanInt :: Event t (IntMap a) -> EventSelectorInt t a
301−
302−--TODO: Specialize this so that we can take advantage of knowing that there's no changing going on
303−-- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple
304−-- keys simultaneously.
305−mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
306−mergeInt m = mergeIntIncremental $ unsafeBuildIncremental (return m) never
307−
308−-- | Coerce a 'Behavior' between representationally-equivalent value types
309−coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
310−coerceBehavior = coerceWith $ behaviorCoercion Coercion
311−
312−-- | Coerce an 'Event' between representationally-equivalent occurrence types
313−coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
314−coerceEvent = coerceWith $ eventCoercion Coercion
315−
316−-- | Coerce a 'Dynamic' between representationally-equivalent value types
317−coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
318−coerceDynamic = coerceWith $ dynamicCoercion Coercion
319−
320−-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
321−-- __must__ change when and only when the 'Event' fires, such that the
322−-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
323−-- if this is not the case, the resulting 'Dynamic' will behave
324−-- nondeterministically.
325−unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
326−unsafeDynamic = unsafeBuildDynamic . sample
327−
328−-- | Construct a 'Dynamic' value that never changes
329−constDyn :: Reflex t => a -> Dynamic t a
330−constDyn = pure
331−
332−instance (Reflex t, Default a) => Default (Dynamic t a) where
333− def = pure def
334−
335−-- | 'MonadSample' designates monads that can read the current value of a
336−-- 'Behavior'. This includes both 'PullM' and 'PushM'.
337−class (Applicative m, Monad m) => MonadSample t m | m -> t where
338− -- | Get the current value in the 'Behavior'
339− sample :: Behavior t a -> m a
340−
341−-- | 'MonadHold' designates monads that can create new 'Behavior's based on
342−-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
343−-- is required to create any stateful computations with Reflex.
344−class MonadSample t m => MonadHold t m where
345− -- | Create a new 'Behavior' whose value will initially be equal to the given
346− -- value and will be updated whenever the given 'Event' occurs. The update
347− -- takes effect immediately after the 'Event' occurs; if the occurrence that
348− -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
349− -- the 'Behavior', it will see the __old__ value of the 'Behavior', not the new
350− -- one.
351− hold :: a -> Event t a -> m (Behavior t a)
352− default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)
353− hold v0 = lift . hold v0
354− -- | Create a 'Dynamic' value using the given initial value that changes every
355− -- time the 'Event' occurs.
356− holdDyn :: a -> Event t a -> m (Dynamic t a)
357− default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)
358− holdDyn v0 = lift . holdDyn v0
359− -- | Create an 'Incremental' value using the given initial value that changes
360− -- every time the 'Event' occurs.
361− holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
362− default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)
363− holdIncremental v0 = lift . holdIncremental v0
364− buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)
365− {-
366− default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)
367− buildDynamic getV0 = lift . buildDynamic getV0
368− -}
369− -- | Create a new 'Event' that only occurs only once, on the first occurrence of
370− -- the supplied 'Event'.
371− headE :: Event t a -> m (Event t a)
372−
373−-- | Accumulate an 'Incremental' with the supplied initial value and the firings of the provided 'Event',
374−-- using the combining function to produce a patch.
375−accumIncremental
376− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
377− => (PatchTarget p -> b -> p)
378− -> PatchTarget p
379− -> Event t b
380− -> m (Incremental t p)
381−accumIncremental f = accumMaybeIncremental $ \v o -> Just $ f v o
382−
383−-- | Similar to 'accumIncremental' but the combining function runs in 'PushM'
384−accumMIncremental
385− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
386− => (PatchTarget p -> b -> PushM t p)
387− -> PatchTarget p
388− -> Event t b
389− -> m (Incremental t p)
390−accumMIncremental f = accumMaybeMIncremental $ \v o -> Just <$> f v o
391−
392−-- | Similar to 'accumIncremental' but allows filtering of updates (by dropping updates when the
393−-- combining function produces @Nothing@)
394−accumMaybeIncremental
395− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
396− => (PatchTarget p -> b -> Maybe p)
397− -> PatchTarget p
398− -> Event t b
399− -> m (Incremental t p)
400−accumMaybeIncremental f = accumMaybeMIncremental $ \v o -> return $ f v o
401−
402−-- | Similar to 'accumMaybeMIncremental' but the combining function runs in 'PushM'
403−accumMaybeMIncremental
404− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
405− => (PatchTarget p -> b -> PushM t (Maybe p))
406− -> PatchTarget p
407− -> Event t b
408− -> m (Incremental t p)
409−accumMaybeMIncremental f z e = do
410− rec let e' = flip push e $ \o -> do
411− v <- sample $ currentIncremental d'
412− f v o
413− d' <- holdIncremental z e'
414− return d'
415−
416−-- | Accumulate an 'Incremental' by folding occurrences of an 'Event'
417−-- with a function that both accumulates and produces a value to fire
418−-- as an 'Event'. Returns both the accumulated value and the constructed
419−-- 'Event'.
420−mapAccumIncremental
421− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
422− => (PatchTarget p -> b -> (p, c))
423− -> PatchTarget p
424− -> Event t b
425− -> m (Incremental t p, Event t c)
426−mapAccumIncremental f = mapAccumMaybeIncremental $ \v o -> bimap Just Just $ f v o
427−
428−-- | Like 'mapAccumIncremental' but the combining function runs in 'PushM'
429−mapAccumMIncremental
430− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
431− => (PatchTarget p -> b -> PushM t (p, c))
432− -> PatchTarget p
433− -> Event t b
434− -> m (Incremental t p, Event t c)
435−mapAccumMIncremental f = mapAccumMaybeMIncremental $ \v o -> bimap Just Just <$> f v o
436−
437−-- | Accumulate an 'Incremental' by folding occurrences of an 'Event' with
438−-- a function that both optionally accumulates and optionally produces
439−-- a value to fire as a separate output 'Event'.
440−-- Note that because 'Nothing's are discarded in both cases, the output
441−-- 'Event' may fire even though the output 'Incremental' has not changed, and
442−-- the output 'Incremental' may update even when the output 'Event' is not firing.
443−mapAccumMaybeIncremental
444− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
445− => (PatchTarget p -> b -> (Maybe p, Maybe c))
446− -> PatchTarget p
447− -> Event t b
448− -> m (Incremental t p, Event t c)
449−mapAccumMaybeIncremental f = mapAccumMaybeMIncremental $ \v o -> return $ f v o
450−
451−-- | Like 'mapAccumMaybeIncremental' but the combining function is a 'PushM' action
452−mapAccumMaybeMIncremental
453− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
454− => (PatchTarget p -> b -> PushM t (Maybe p, Maybe c))
455− -> PatchTarget p
456− -> Event t b
457− -> m (Incremental t p, Event t c)
458−mapAccumMaybeMIncremental f z e = do
459− rec let e' = flip push e $ \o -> do
460− v <- sample $ currentIncremental d'
461− result <- f v o
462− return $ case result of
463− (Nothing, Nothing) -> Nothing
464− _ -> Just result
465− d' <- holdIncremental z $ mapMaybe fst e'
466− return (d', mapMaybe snd e')
467−
468−-- | A somewhat slow implementation of 'headE'
469−slowHeadE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
470−slowHeadE e = do
471− rec be <- hold e $ fmapCheap (const never) e'
472− let e' = switch be
473− return e'
474−
475−-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
476−-- key. This is much more efficient than filtering for each key with
477−-- 'mapMaybe'.
478−newtype EventSelector t k = EventSelector
479− { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
480− -- determined by the type of the key, so this can be used to fan-out
481− -- 'Event's whose sub-'Event's have different types.
482− --
483− -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
484− -- (but equivalent to) using 'mapMaybe' to select only the relevant
485− -- occurrences of an 'Event'.
486− select :: forall a. k a -> Event t a
487− }
488−
489−-- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually
490−-- filtering by key.
491−newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }
492−
493−--------------------------------------------------------------------------------
494−-- Instances
495−--------------------------------------------------------------------------------
496−
497−instance MonadSample t m => MonadSample t (ReaderT r m) where
498− sample = lift . sample
499−
500−instance MonadHold t m => MonadHold t (ReaderT r m) where
501− hold a0 = lift . hold a0
502− holdDyn a0 = lift . holdDyn a0
503− holdIncremental a0 = lift . holdIncremental a0
504− buildDynamic a0 = lift . buildDynamic a0
505− headE = lift . headE
506−
507−instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
508− sample = lift . sample
509−
510−instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
511− hold a0 = lift . hold a0
512− holdDyn a0 = lift . holdDyn a0
513− holdIncremental a0 = lift . holdIncremental a0
514− buildDynamic a0 = lift . buildDynamic a0
515− headE = lift . headE
516−
517−instance MonadSample t m => MonadSample t (StateT s m) where
518− sample = lift . sample
519−
520−instance MonadHold t m => MonadHold t (StateT s m) where
521− hold a0 = lift . hold a0
522− holdDyn a0 = lift . holdDyn a0
523− holdIncremental a0 = lift . holdIncremental a0
524− buildDynamic a0 = lift . buildDynamic a0
525− headE = lift . headE
526−
527−instance MonadSample t m => MonadSample t (ExceptT e m) where
528− sample = lift . sample
529−
530−instance MonadHold t m => MonadHold t (ExceptT e m) where
531− hold a0 = lift . hold a0
532− holdDyn a0 = lift . holdDyn a0
533− holdIncremental a0 = lift . holdIncremental a0
534− buildDynamic a0 = lift . buildDynamic a0
535− headE = lift . headE
536−
537−instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
538− sample = lift . sample
539−
540−instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
541− hold a0 = lift . hold a0
542− holdDyn a0 = lift . holdDyn a0
543− holdIncremental a0 = lift . holdIncremental a0
544− buildDynamic a0 = lift . buildDynamic a0
545− headE = lift . headE
546−
547−instance MonadSample t m => MonadSample t (ContT r m) where
548− sample = lift . sample
549−
550−instance MonadHold t m => MonadHold t (ContT r m) where
551− hold a0 = lift . hold a0
552− holdDyn a0 = lift . holdDyn a0
553− holdIncremental a0 = lift . holdIncremental a0
554− buildDynamic a0 = lift . buildDynamic a0
555− headE = lift . headE
556−
557−--------------------------------------------------------------------------------
558−-- Convenience functions
559−--------------------------------------------------------------------------------
560−
561−-- | Create an 'Event' from another 'Event'. The provided function can sample
562−-- 'Behavior's and hold 'Event's.
563−pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
564−pushAlways f = push (fmap Just . f)
565−
566−-- | Flipped version of 'fmap'.
567−ffor :: Functor f => f a -> (a -> b) -> f b
568−ffor = flip fmap
569−
570−-- | Rotated version of 'liftA2'.
571−ffor2 :: Applicative f => f a -> f b -> (a -> b -> c) -> f c
572−ffor2 a b f = liftA2 f a b
573−
574−-- | Rotated version of 'liftA3'.
575−ffor3 :: Applicative f => f a -> f b -> f c -> (a -> b -> c -> d) -> f d
576−ffor3 a b c f = liftA3 f a b c
577−
578−instance Reflex t => Applicative (Behavior t) where
579− pure = constant
580− f <*> x = pull $ sample f `ap` sample x
581− _ *> b = b
582− a <* _ = a
583−
584−instance Reflex t => Apply (Behavior t) where
585− (<.>) = (<*>)
586−
587−instance Reflex t => Bind (Behavior t) where
588− (>>-) = (>>=)
589−
590−instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
591− (/) = liftA2 (/)
592− fromRational = pure . fromRational
593− recip = fmap recip
594−
595−instance Reflex t => Functor (Behavior t) where
596− fmap f = pull . fmap f . sample
597−
598−instance (Reflex t, IsString a) => IsString (Behavior t a) where
599− fromString = pure . fromString
600−
601−instance Reflex t => Monad (Behavior t) where
602− a >>= f = pull $ sample a >>= sample . f
603− -- Note: it is tempting to write (_ >> b = b); however, this would result in (fail x >> return y) succeeding (returning y), which violates the law that (a >> b = a >>= \_ -> b), since the implementation of (>>=) above actually will fail. Since we can't examine 'Behavior's other than by using sample, I don't think it's possible to write (>>) to be more efficient than the (>>=) above.
604− return = constant
605− fail = error "Monad (Behavior t) does not support fail"
606−
607−instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
608− mempty = constant mempty
609− mappend a b = pull $ liftM2 mappend (sample a) (sample b)
610− mconcat = pull . fmap mconcat . mapM sample
611−
612−instance (Reflex t, Num a) => Num (Behavior t a) where
613− (+) = liftA2 (+)
614− (-) = liftA2 (-)
615− (*) = liftA2 (*)
616− abs = fmap abs
617− fromInteger = pure . fromInteger
618− negate = fmap negate
619− signum = fmap signum
620−
621−instance (Num a, Reflex t) => Num (Dynamic t a) where
622− (+) = liftA2 (+)
623− (*) = liftA2 (*)
624− abs = fmap abs
625− signum = fmap signum
626− fromInteger = pure . fromInteger
627− negate = fmap negate
628− (-) = liftA2 (-)
629−
630−instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
631− a <> b = pull $ liftM2 (<>) (sample a) (sample b)
632− sconcat = pull . fmap sconcat . mapM sample
633−#if MIN_VERSION_semigroups(0,17,0)
634− stimes n = fmap $ stimes n
635−#else
636− times1p n = fmap $ times1p n
637−#endif
638−
639−-- | Alias for 'mapMaybe'
640−fmapMaybe :: Filterable f => (a -> Maybe b) -> f a -> f b
641−fmapMaybe = mapMaybe
642−
643−-- | Flipped version of 'mapMaybe'.
644−fforMaybe :: Filterable f => f a -> (a -> Maybe b) -> f b
645−fforMaybe = flip mapMaybe
646−
647−-- | Filter 'f a' using the provided predicate.
648−ffilter :: Filterable f => (a -> Bool) -> f a -> f a
649−ffilter = W.filter
650−
651−-- | Filter 'Left's from 'f (Either a b)' into 'a'.
652−filterLeft :: Filterable f => f (Either a b) -> f a
653−filterLeft = mapMaybe (either Just (const Nothing))
654−
655−-- | Filter 'Right's from 'f (Either a b)' into 'b'.
656−filterRight :: Filterable f => f (Either a b) -> f b
657−filterRight = mapMaybe (either (const Nothing) Just)
658−
659−-- | Left-biased event union (prefers left event on simultaneous
660−-- occurrence).
661−instance Reflex t => Alt (Event t) where
662− ev1 <!> ev2 = leftmost [ev1, ev2]
663−
664−-- | 'Event' intersection (convenient interface to 'coincidence').
665−instance Reflex t => Apply (Event t) where
666− evf <.> evx = coincidence (fmap (<$> evx) evf)
667−
668−-- | 'Event' intersection (convenient interface to 'coincidence').
669−instance Reflex t => Bind (Event t) where
670− evx >>- f = coincidence (f <$> evx)
671− join = coincidence
672−
673−instance Reflex t => Functor (Event t) where
674− {-# INLINE fmap #-}
675− fmap f = mapMaybe $ Just . f
676− {-# INLINE (<$) #-}
677− x <$ e = fmapCheap (const x) e
678−
679−-- TODO Remove this instance
680−instance Reflex t => FunctorMaybe (Event t) where
681− {-# INLINE fmapMaybe #-}
682− fmapMaybe = mapMaybe
683−
684−instance Reflex t => Filterable (Event t) where
685− {-# INLINE mapMaybe #-}
686− mapMaybe f = push $ return . f
687−
688−-- | Never: @'zero' = 'never'@.
689−instance Reflex t => Plus (Event t) where
690− zero = never
691−
692−-- | Replace each occurrence value of the 'Event' with the value of the
693−-- 'Behavior' at the time of that occurrence.
694−tag :: Reflex t => Behavior t b -> Event t a -> Event t b
695−tag b = pushAlways $ \_ -> sample b
696−
697−-- | Replace each occurrence value of the 'Event' with the value of the
698−-- 'Behavior' at that time; if it is 'Just', fire with the contained value; if
699−-- it is 'Nothing', drop the occurrence.
700−tagMaybe :: Reflex t => Behavior t (Maybe b) -> Event t a -> Event t b
701−tagMaybe b = push $ \_ -> sample b
702−
703−-- | Create a new 'Event' that combines occurrences of supplied 'Event' with the
704−-- current value of the 'Behavior'.
705−attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
706−attach = attachWith (,)
707−
708−-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
709−-- combining it with the current value of the 'Behavior'.
710−attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
711−attachWith f = attachWithMaybe $ \a b -> Just $ f a b
712−
713−-- | Create a new 'Event' by combining each occurrence with the current value of
714−-- the 'Behavior'. The occurrence is discarded if the combining function returns
715−-- Nothing
716−attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
717−attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
718−
719−-- | Create a new 'Event' that occurs on all but the first occurrence of the
720−-- supplied 'Event'.
721−tailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a)
722−tailE e = snd <$> headTailE e
723−
724−-- | Create a tuple of two 'Event's with the first one occurring only the first
725−-- time the supplied 'Event' occurs and the second occurring on all but the first
726−-- occurrence.
727−headTailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a, Event t a)
728−headTailE e = do
729− eHead <- headE e
730− be <- hold never $ fmap (const e) eHead
731− return (eHead, switch be)
732−
733−-- | Take the streak of occurrences starting at the current time for which the
734−-- event returns 'True'.
735−--
736−-- Starting at the current time, fire all the occurrences of the 'Event' for
737−-- which the given predicate returns 'True'. When first 'False' is returned,
738−-- do not fire, and permanently stop firing, even if 'True' values would have
739−-- been encountered later.
740−takeWhileE
741− :: forall t m a
742− . (Reflex t, MonadFix m, MonadHold t m)
743− => (a -> Bool)
744− -> Event t a
745− -> m (Event t a)
746−takeWhileE f = takeWhileJustE $ \v -> guard (f v) $> v
747−
748−-- | Take the streak of occurrences starting at the current time for which the
749−-- event returns 'Just b'.
750−--
751−-- Starting at the current time, fire all the occurrences of the 'Event' for
752−-- which the given predicate returns 'Just b'. When first 'Nothing' is returned,
753−-- do not fire, and permanently stop firing, even if 'Just b' values would have
754−-- been encountered later.
755−takeWhileJustE
756− :: forall t m a b
757− . (Reflex t, MonadFix m, MonadHold t m)
758− => (a -> Maybe b)
759− -> Event t a
760− -> m (Event t b)
761−takeWhileJustE f e = do
762− rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of
763− Nothing -> Left never
764− Just b -> Right b
765− eFirstBad <- headE eBad
766− e' <- switchHold e eFirstBad
767− return eTrue
768−
769−-- | Drop the streak of occurrences starting at the current time for which the
770−-- event returns 'True'.
771−--
772−-- Starting at the current time, do not fire all the occurrences of the 'Event'
773−-- for which the given predicate returns 'True'. When 'False' is first
774−-- returned, do fire, and permanently continue firing, even if 'True' values
775−-- would have been encountered later.
776−dropWhileE
777− :: forall t m a
778− . (Reflex t, MonadFix m, MonadHold t m)
779− => (a -> Bool)
780− -> Event t a
781− -> m (Event t a)
782−dropWhileE f e = snd <$> takeDropWhileJustE (\v -> guard (f v) $> v) e
783−
784−-- | Both take and drop the streak of occurrences starting at the current time
785−-- for which the event returns 'Just b'.
786−--
787−-- For the left event, starting at the current time, fire all the occurrences
788−-- of the 'Event' for which the given function returns 'Just b'. When
789−-- 'Nothing' is returned, do not fire, and permanently stop firing, even if
790−-- 'Just b' values would have been encountered later.
791−--
792−-- For the right event, do not fire until the first occurrence where the given
793−-- function returns 'Nothing', and fire that one and all subsequent
794−-- occurrences. Even if the function would have again returned 'Just b', keep
795−-- on firing.
796−takeDropWhileJustE
797− :: forall t m a b
798− . (Reflex t, MonadFix m, MonadHold t m)
799− => (a -> Maybe b)
800− -> Event t a
801− -> m (Event t b, Event t a)
802−takeDropWhileJustE f e = do
803− rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of
804− Nothing -> Left ()
805− Just b -> Right b
806− eFirstBad <- headE eBad
807− e' <- switchHold e (never <$ eFirstBad)
808− eRest <- switchHoldPromptOnly never (e <$ eFirstBad)
809− return (eGood, eRest)
810−
811−-- | Split the supplied 'Event' into two individual 'Event's occurring at the
812−-- same time with the respective values from the tuple.
813−splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
814−splitE e = (fmap fst e, fmap snd e)
815−
816−-- | Print the supplied 'String' and the value of the 'Event' on each
817−-- occurrence. This should /only/ be used for debugging.
818−--
819−-- Note: As with Debug.Trace.trace, the message will only be printed if the
820−-- 'Event' is actually used.
821−traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
822−traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
823−
824−-- | Print the output of the supplied function on each occurrence of the
825−-- 'Event'. This should /only/ be used for debugging.
826−--
827−-- Note: As with Debug.Trace.trace, the message will only be printed if the
828−-- 'Event' is actually used.
829−traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
830−traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
831−
832−instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
833− (<>) = alignWith (mergeThese (<>))
834− sconcat = fmap sconcat . mergeList . toList
835−#if MIN_VERSION_semigroups(0,17,0)
836− stimes n = fmap $ stimes n
837−#else
838− times1p n = fmap $ times1p n
839−#endif
840−
841−instance (Semigroup a, Reflex t) => Monoid (Event t a) where
842− mempty = never
843− mappend = (<>)
844− mconcat = fmap sconcat . mergeList
845−
846−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
847−-- list occurs. If multiple occur at the same time they are folded from the left
848−-- with the given function.
849−{-# INLINE mergeWith #-}
850−mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
851−mergeWith = mergeWith' id
852−
853−{-# INLINE mergeWith' #-}
854−mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
855−mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)
856− . mergeInt
857− . IntMap.fromDistinctAscList
858− $ zip [0 :: Int ..] es
859−
860−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
861−-- list occurs. If multiple occur at the same time the value is the value of the
862−-- leftmost event.
863−{-# INLINE leftmost #-}
864−leftmost :: Reflex t => [Event t a] -> Event t a
865−leftmost = mergeWith const
866−
867−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
868−-- list occurs and has a list of the values of all 'Event's occurring at that
869−-- time.
870−mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
871−mergeList [] = never
872−mergeList es = mergeWithFoldCheap' id es
873−
874−unsafeMapIncremental
875− :: (Reflex t, Patch p, Patch p')
876− => (PatchTarget p -> PatchTarget p')
877− -> (p -> p')
878− -> Incremental t p
879− -> Incremental t p'
880−unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
881−
882−-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
883−-- occurs if at least one of them occurs and has a map of values of all 'Event's
884−-- occurring at that time.
885−mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
886−mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
887−
888−-- | Like 'mergeMap' but for 'IntMap'.
889−mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
890−mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap
891−
892−-- | Create a merge whose parents can change over time
893−mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a)
894−mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id)
895−
896−-- | Create a merge whose parents can change over time
897−mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
898−mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)
899−
900−-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
901−mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a)
902−mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id)
903−
904−-- | Split the event into separate events for 'Left' and 'Right' values.
905−fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
906−fanEither e =
907− let justLeft = either Just (const Nothing)
908− justRight = either (const Nothing) Just
909− in (mapMaybe justLeft e, mapMaybe justRight e)
910−
911−-- | Split the event into separate events for 'This' and 'That' values,
912−-- allowing them to fire simultaneously when the input value is 'These'.
913−fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
914−fanThese e =
915− let this (This x) = Just x
916− this (These x _) = Just x
917− this _ = Nothing
918− that (That y) = Just y
919− that (These _ y) = Just y
920− that _ = Nothing
921− in (mapMaybe this e, mapMaybe that e)
922−
923−-- | Split the event into an 'EventSelector' that allows efficient selection of
924−-- the individual 'Event's.
925−fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
926−fanMap = fan . fmap mapToDMap
927−
928−-- | Switches to the new event whenever it receives one. Only the old event is
929−-- considered the moment a new one is switched in; the output event will fire at
930−-- that moment only if the old event does.
931−--
932−-- Because the simultaneous firing case is irrelevant, this function imposes
933−-- laxer "timing requirements" on the overall circuit, avoiding many potential
934−-- cyclic dependency / metastability failures. It's also more performant. Use
935−-- this rather than 'switchHoldPromptly' and 'switchHoldPromptOnly' unless you
936−-- are absolutely sure you need to act on the new event in the coincidental
937−-- case.
938−switchHold :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
939−switchHold ea0 eea = switch <$> hold ea0 eea
940−
941−-- | Switches to the new event whenever it receives one. Whenever a new event is
942−-- provided, if it is firing, its value will be the resulting event's value; if
943−-- it is not firing, but the old one is, the old one's value will be used.
944−--
945−-- 'switchHold', by always forwarding the old event the moment it is switched
946−-- out, avoids many potential cyclic dependency problems / metastability
947−-- problems. It's also more performant. Use it instead unless you are sure you
948−-- cannot.
949−switchHoldPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
950−switchHoldPromptly ea0 eea = do
951− bea <- hold ea0 eea
952− let eLag = switch bea
953− eCoincidences = coincidence eea
954− return $ leftmost [eCoincidences, eLag]
955−
956−-- | switches to a new event whenever it receives one. At the moment of
957−-- switching, the old event will be ignored if it fires, and the new one will be
958−-- used if it fires; this is the opposite of 'switch', which will use only the
959−-- old value.
960−--
961−-- 'switchHold', by always forwarding the old event the moment it is switched
962−-- out, avoids many potential cyclic dependency problems / metastability
963−-- problems. It's also more performant. Use it instead unless you are sure you
964−-- cannot.
965−switchHoldPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
966−switchHoldPromptOnly e0 e' = do
967− eLag <- switch <$> hold e0 e'
968− return $ coincidence $ leftmost [e', eLag <$ eLag]
969−
970−-- | When the given outer event fires, condense the inner events into the contained patch. Non-firing inner events will be replaced with deletions.
971−coincidencePatchMap :: (Reflex t, Ord k) => Event t (PatchMap k (Event t v)) -> Event t (PatchMap k v)
972−coincidencePatchMap e = fmapCheap PatchMap $ coincidence $ ffor e $ \(PatchMap m) -> mergeMap $ ffor m $ \case
973− Nothing -> fmapCheap (const Nothing) e
974− Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
975−
976−-- | See 'coincidencePatchMap'
977−coincidencePatchIntMap :: Reflex t => Event t (PatchIntMap (Event t v)) -> Event t (PatchIntMap v)
978−coincidencePatchIntMap e = fmapCheap PatchIntMap $ coincidence $ ffor e $ \(PatchIntMap m) -> mergeIntMap $ ffor m $ \case
979− Nothing -> fmapCheap (const Nothing) e
980− Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
981−
982−-- | See 'coincidencePatchMap'
983−coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v)
984−coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of
985− PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->
986− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
987− PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->
988− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }
989− PatchMapWithMove.From_Insert ev -> leftmost
990− [ fforCheap ev $ \v ->
991− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }
992− , fforCheap e $ \_ ->
993− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
994− ]
995−
996−-- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es
997−-- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that
998−-- fires with the patched value.
999−switchHoldPromptOnlyIncremental
1000− :: forall t m p pt w
1001− . ( Reflex t
1002− , MonadHold t m
1003− , Patch (p (Event t w))
1004− , PatchTarget (p (Event t w)) ~ pt (Event t w)
1005− , Patch (p w)
1006− , PatchTarget (p w) ~ pt w
1007− , Monoid (pt w)
1008− )
1009− => (Incremental t (p (Event t w)) -> Event t (pt w))
1010− -> (Event t (p (Event t w)) -> Event t (p w))
1011− -> pt (Event t w)
1012− -> Event t (p (Event t w))
1013− -> m (Event t (pt w))
1014−switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch e0 e' = do
1015− lag <- mergePatchIncremental <$> holdIncremental e0 e'
1016− pure $ ffor (align lag (coincidencePatch e')) $ \case
1017− This old -> old
1018− That new -> new `applyAlways` mempty
1019− These old new -> new `applyAlways` old
1020−
1021−instance Reflex t => Align (Event t) where
1022− nil = never
1023−#if MIN_VERSION_these(0, 8, 0)
1024−instance Reflex t => Semialign (Event t) where
1025−#endif
1026− align = alignEventWithMaybe Just
1027−
1028−
1029−-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
1030−-- the 'Behavior' is true at the time of occurrence.
1031−gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
1032−gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
1033−
1034−-- | Create a new behavior given a starting behavior and switch to the behavior
1035−-- carried by the event when it fires.
1036−switcher :: (Reflex t, MonadHold t m)
1037− => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
1038−switcher b eb = pull . (sample <=< sample) <$> hold b eb
1039−
1040−instance (Reflex t, IsString a) => IsString (Dynamic t a) where
1041− fromString = pure . fromString
1042−
1043−-- | Combine two 'Dynamic's. The result will change whenever either (or both)
1044−-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
1045−zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
1046−zipDyn = zipDynWith (,)
1047−
1048−-- | Combine two 'Dynamic's with a combining function. The result will change
1049−-- whenever either (or both) input 'Dynamic' changes.
1050−-- More efficient than 'liftA2'.
1051−zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
1052−zipDynWith f da db =
1053− let eab = align (updated da) (updated db)
1054− ec = flip push eab $ \o -> do
1055− (a, b) <- case o of
1056− This a -> do
1057− b <- sample $ current db
1058− return (a, b)
1059− That b -> do
1060− a <- sample $ current da
1061− return (a, b)
1062− These a b -> return (a, b)
1063− return $ Just $ f a b
1064− in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
1065−
1066−instance (Reflex t, Semigroup a) => Semigroup (Dynamic t a) where
1067− (<>) = zipDynWith (<>)
1068−#if MIN_VERSION_semigroups(0,17,0)
1069− stimes n = fmap $ stimes n
1070−#else
1071− times1p n = fmap $ times1p n
1072−#endif
1073−
1074−instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
1075− mconcat = distributeListOverDynWith mconcat
1076− mempty = constDyn mempty
1077− mappend = zipDynWith mappend
1078−
1079−-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1080−-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1081−-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1082−distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
1083−distributeDMapOverDynPure dm = case DMap.toList dm of
1084− [] -> constDyn DMap.empty
1085− [k :=> v] -> fmap (DMap.singleton k . Identity) v
1086− _ ->
1087− let getInitial = DMap.traverseWithKey (\_ -> fmap Identity . sample . current) dm
1088− edmPre = merge $ DMap.map updated dm
1089− result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
1090− olds <- sample $ current result
1091− return $ DMap.unionWithKey (\_ _ new -> new) olds news
1092− in result
1093−
1094−-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
1095−distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
1096−distributeListOverDyn = distributeListOverDynWith id
1097−
1098−-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
1099−distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
1100−distributeListOverDynWith f =
1101− fmap (f . map fromDSum . DMap.toAscList) .
1102− distributeDMapOverDynPure .
1103− DMap.fromDistinctAscList .
1104− zipWith toDSum [0..]
1105− where
1106− toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
1107− toDSum k v = Const2 k :=> v
1108− fromDSum :: DSum (Const2 Int a) Identity -> a
1109− fromDSum (Const2 _ :=> Identity v) = v
1110−
1111−-- | Create a new 'Event' that occurs when the first supplied 'Event' occurs
1112−-- unless the second supplied 'Event' occurs simultaneously.
1113−difference :: Reflex t => Event t a -> Event t b -> Event t a
1114−difference = alignEventWithMaybe $ \case
1115− This a -> Just a
1116− _ -> Nothing
1117−
1118−-- | Zips two values by taking the union of their shapes and combining with the provided function.
1119−-- 'Nothing' values are dropped.
1120−alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c
1121−alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $
1122− merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1123−
1124−-- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that
1125−-- matches the provided key.
1126−filterEventKey
1127− :: forall t m k v a.
1128− ( Reflex t
1129− , MonadFix m
1130− , MonadHold t m
1131− , GEq k
1132− )
1133− => k a
1134− -> Event t (DSum k v)
1135− -> m (Event t (v a))
1136−filterEventKey k kv' = do
1137− let f :: DSum k v -> Maybe (v a)
1138− f (newK :=> newV) = case newK `geq` k of
1139− Just Refl -> Just newV
1140− Nothing -> Nothing
1141− takeWhileJustE f kv'
1142−
1143−-- | "Factor" the input 'DSum' 'Event' to produce an 'Event' which
1144−-- fires when the 'DSum' key changes and contains both the value of the
1145−-- 'DSum' at switchover and an 'Event' of values produced by subsequent
1146−-- firings of the input 'Event' that do not change the 'DSum' key.
1147−factorEvent
1148− :: forall t m k v a.
1149− ( Reflex t
1150− , MonadFix m
1151− , MonadHold t m
1152− , GEq k
1153− )
1154− => k a
1155− -> Event t (DSum k v)
1156− -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v))))
1157−factorEvent k0 kv' = do
1158− key :: Behavior t (Some k) <- hold (Some.This k0) $ fmapCheap (\(k :=> _) -> Some.This k) kv'
1159− let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case
1160− Some.This oldKey -> case newKey `geq` oldKey of
1161− Just Refl -> return Nothing
1162− Nothing -> do
1163− newInner <- filterEventKey newKey kv'
1164− return $ Just $ newKey :=> Pair newVal (Compose newInner)
1165− eInitial <- filterEventKey k0 kv'
1166− return (eInitial, update)
1167−
1168−--------------------------------------------------------------------------------
1169−-- Accumulator
1170−--------------------------------------------------------------------------------
1171−
1172−-- | An 'Accumulator' type can be built by accumulating occurrences of an
1173−-- 'Event'.
1174−#if __GLASGOW_HASKELL__ < 802
1175−{-# WARNING accum "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1176−{-# WARNING accumM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1177−{-# WARNING accumMaybe "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1178−{-# WARNING accumMaybeM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1179−#endif
1180−class Reflex t => Accumulator t f | f -> t where
1181− accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
1182− accum f = accumMaybe $ \v o -> Just $ f v o
1183− accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
1184− accumM f = accumMaybeM $ \v o -> Just <$> f v o
1185− accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
1186− accumMaybe f = accumMaybeM $ \v o -> return $ f v o
1187− accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
1188− mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
1189− mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
1190− mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
1191− mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
1192− mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1193− mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
1194− mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1195−
1196−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1197−-- with the provided function. See 'foldDyn'.
1198−accumDyn
1199− :: (Reflex t, MonadHold t m, MonadFix m)
1200− => (a -> b -> a)
1201− -> a
1202− -> Event t b
1203− -> m (Dynamic t a)
1204−accumDyn f = accumMaybeDyn $ \v o -> Just $ f v o
1205−
1206−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1207−-- with the provided 'PushM' action.
1208−accumMDyn
1209− :: (Reflex t, MonadHold t m, MonadFix m)
1210− => (a -> b -> PushM t a)
1211− -> a
1212− -> Event t b
1213− -> m (Dynamic t a)
1214−accumMDyn f = accumMaybeMDyn $ \v o -> Just <$> f v o
1215−
1216−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1217−-- with the provided function, discarding 'Nothing' results.
1218−accumMaybeDyn
1219− :: (Reflex t, MonadHold t m, MonadFix m)
1220− => (a -> b -> Maybe a)
1221− -> a
1222− -> Event t b
1223− -> m (Dynamic t a)
1224−accumMaybeDyn f = accumMaybeMDyn $ \v o -> return $ f v o
1225−
1226−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1227−-- with the provided 'PushM' action, discarding 'Nothing' results.
1228−accumMaybeMDyn
1229− :: (Reflex t, MonadHold t m, MonadFix m)
1230− => (a -> b -> PushM t (Maybe a))
1231− -> a
1232− -> Event t b
1233− -> m (Dynamic t a)
1234−accumMaybeMDyn f z e = do
1235− rec let e' = flip push e $ \o -> do
1236− v <- sample $ current d'
1237− f v o
1238− d' <- holdDyn z e'
1239− return d'
1240−
1241−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1242−-- with a function that both accumulates and produces a value to fire
1243−-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1244−mapAccumDyn
1245− :: (Reflex t, MonadHold t m, MonadFix m)
1246− => (a -> b -> (a, c))
1247− -> a
1248− -> Event t b
1249− -> m (Dynamic t a, Event t c)
1250−mapAccumDyn f = mapAccumMaybeDyn $ \v o -> bimap Just Just $ f v o
1251−
1252−-- | Similar to 'mapAccumDyn' except that the combining function is a
1253−-- 'PushM' action.
1254−mapAccumMDyn
1255− :: (Reflex t, MonadHold t m, MonadFix m)
1256− => (a -> b -> PushM t (a, c))
1257− -> a
1258− -> Event t b
1259− -> m (Dynamic t a, Event t c)
1260−mapAccumMDyn f = mapAccumMaybeMDyn $ \v o -> bimap Just Just <$> f v o
1261−
1262−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event' with
1263−-- a function that both optionally accumulates and optionally produces
1264−-- a value to fire as a separate output 'Event'.
1265−-- Note that because 'Nothing's are discarded in both cases, the output
1266−-- 'Event' may fire even though the output 'Dynamic' has not changed, and
1267−-- the output 'Dynamic' may update even when the output 'Event' is not firing.
1268−mapAccumMaybeDyn
1269− :: (Reflex t, MonadHold t m, MonadFix m)
1270− => (a -> b -> (Maybe a, Maybe c))
1271− -> a
1272− -> Event t b
1273− -> m (Dynamic t a, Event t c)
1274−mapAccumMaybeDyn f = mapAccumMaybeMDyn $ \v o -> return $ f v o
1275−
1276−-- | Like 'mapAccumMaybeDyn' except that the combining function is a
1277−-- 'PushM' action.
1278−mapAccumMaybeMDyn
1279− :: (Reflex t, MonadHold t m, MonadFix m)
1280− => (a -> b -> PushM t (Maybe a, Maybe c))
1281− -> a
1282− -> Event t b
1283− -> m (Dynamic t a, Event t c)
1284−mapAccumMaybeMDyn f z e = do
1285− rec let e' = flip push e $ \o -> do
1286− v <- sample $ current d'
1287− result <- f v o
1288− return $ case result of
1289− (Nothing, Nothing) -> Nothing
1290− _ -> Just result
1291− d' <- holdDyn z $ mapMaybe fst e'
1292− return (d', mapMaybe snd e')
1293−
1294−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1295−-- with the provided function.
1296−{-# INLINE accumB #-}
1297−accumB
1298− :: (Reflex t, MonadHold t m, MonadFix m)
1299− => (a -> b -> a)
1300− -> a
1301− -> Event t b
1302− -> m (Behavior t a)
1303−accumB f = accumMaybeB $ \v o -> Just $ f v o
1304−
1305−-- | Like 'accumB' except that the combining function is a 'PushM' action.
1306−{-# INLINE accumMB #-}
1307−accumMB
1308− :: (Reflex t, MonadHold t m, MonadFix m)
1309− => (a -> b -> PushM t a)
1310− -> a
1311− -> Event t b
1312− -> m (Behavior t a)
1313−accumMB f = accumMaybeMB $ \v o -> Just <$> f v o
1314−
1315−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1316−-- with the provided function, discarding 'Nothing' results.
1317−{-# INLINE accumMaybeB #-}
1318−accumMaybeB
1319− :: (Reflex t, MonadHold t m, MonadFix m)
1320− => (a -> b -> Maybe a)
1321− -> a
1322− -> Event t b
1323− -> m (Behavior t a)
1324−accumMaybeB f = accumMaybeMB $ \v o -> return $ f v o
1325−
1326−-- | Like 'accumMaybeB' except that the combining function is a 'PushM' action.
1327−{-# INLINE accumMaybeMB #-}
1328−accumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (Behavior t a)
1329−accumMaybeMB f z e = do
1330− rec let e' = flip push e $ \o -> do
1331− v <- sample d'
1332− f v o
1333− d' <- hold z e'
1334− return d'
1335−
1336−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1337−-- with a function that both accumulates and produces a value to fire
1338−-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1339−{-# INLINE mapAccumB #-}
1340−mapAccumB
1341− :: (Reflex t, MonadHold t m, MonadFix m)
1342− => (a -> b -> (a, c))
1343− -> a
1344− -> Event t b
1345− -> m (Behavior t a, Event t c)
1346−mapAccumB f = mapAccumMaybeB $ \v o -> bimap Just Just $ f v o
1347−
1348−-- | Like 'mapAccumB' except that the combining function is a 'PushM' action.
1349−{-# INLINE mapAccumMB #-}
1350−mapAccumMB
1351− :: (Reflex t, MonadHold t m, MonadFix m)
1352− => (a -> b -> PushM t (a, c))
1353− -> a
1354− -> Event t b
1355− -> m (Behavior t a, Event t c)
1356−mapAccumMB f = mapAccumMaybeMB $ \v o -> bimap Just Just <$> f v o
1357−
1358−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event' with
1359−-- a function that both optionally accumulates and optionally produces
1360−-- a value to fire as a separate output 'Event'. 'Nothing's are discarded.
1361−{-# INLINE mapAccumMaybeB #-}
1362−mapAccumMaybeB
1363− :: (Reflex t, MonadHold t m, MonadFix m)
1364− => (a -> b -> (Maybe a, Maybe c))
1365− -> a
1366− -> Event t b
1367− -> m (Behavior t a, Event t c)
1368−mapAccumMaybeB f = mapAccumMaybeMB $ \v o -> return $ f v o
1369−
1370−-- | LIke 'mapAccumMaybeB' except that the combining function is a 'PushM' action.
1371−{-# INLINE mapAccumMaybeMB #-}
1372−mapAccumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (Behavior t a, Event t c)
1373−mapAccumMaybeMB f z e = do
1374− rec let e' = flip push e $ \o -> do
1375− v <- sample d'
1376− result <- f v o
1377− return $ case result of
1378− (Nothing, Nothing) -> Nothing
1379− _ -> Just result
1380− d' <- hold z $ mapMaybe fst e'
1381− return (d', mapMaybe snd e')
1382−
1383−-- | Accumulate occurrences of an 'Event', producing an output occurrence each
1384−-- time. Discard the underlying 'Accumulator'.
1385−{-# INLINE mapAccum_ #-}
1386−mapAccum_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (Event t c)
1387−mapAccum_ f z e = do
1388− (_, result) <- mapAccumB f z e
1389− return result
1390−
1391−-- | Accumulate occurrences of an 'Event', possibly producing an output
1392−-- occurrence each time. Discard the underlying 'Accumulator'.
1393−{-# INLINE mapAccumMaybe_ #-}
1394−mapAccumMaybe_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (Event t c)
1395−mapAccumMaybe_ f z e = do
1396− (_, result) <- mapAccumMaybeB f z e
1397− return result
1398−
1399−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
1400−-- an output occurrence each time. Discard the underlying 'Accumulator'.
1401−{-# INLINE mapAccumM_ #-}
1402−mapAccumM_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (Event t c)
1403−mapAccumM_ f z e = do
1404− (_, result) <- mapAccumMB f z e
1405− return result
1406−
1407−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
1408−-- producing an output occurrence each time. Discard the underlying
1409−-- 'Accumulator'.
1410−{-# INLINE mapAccumMaybeM_ #-}
1411−mapAccumMaybeM_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (Event t c)
1412−mapAccumMaybeM_ f z e = do
1413− (_, result) <- mapAccumMaybeMB f z e
1414− return result
1415−
1416−instance Reflex t => Accumulator t (Dynamic t) where
1417− accumMaybeM = accumMaybeMDyn
1418− mapAccumMaybeM = mapAccumMaybeMDyn
1419−
1420−instance Reflex t => Accumulator t (Behavior t) where
1421− accumMaybeM = accumMaybeMB
1422− mapAccumMaybeM = mapAccumMaybeMB
1423−
1424−instance Reflex t => Accumulator t (Event t) where
1425− accumMaybeM f z e = updated <$> accumMaybeM f z e
1426− mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
1427−
1428−-- | Create a new 'Event' by combining each occurrence with the next value of the
1429−-- list using the supplied function. If the list runs out of items, all
1430−-- subsequent 'Event' occurrences will be ignored.
1431−zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
1432−zipListWithEvent f l e = do
1433− let f' a b = case a of
1434− h:t -> (Just t, Just $ f h b)
1435− _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
1436− mapAccumMaybe_ f' l e
1437−
1438−-- | Assign a number to each occurrence of the given 'Event', starting from 0
1439−{-# INLINE numberOccurrences #-}
1440−numberOccurrences :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Event t (b, a))
1441−numberOccurrences = numberOccurrencesFrom 0
1442−
1443−-- | Assign a number to each occurrence of the given 'Event'
1444−{-# INLINE numberOccurrencesFrom #-}
1445−numberOccurrencesFrom :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t (b, a))
1446−numberOccurrencesFrom = mapAccum_ (\n a -> let !next = n + 1 in (next, (n, a)))
1447−
1448−-- | Assign a number to each occurrence of the given 'Event'; discard the occurrences' values
1449−{-# INLINE numberOccurrencesFrom_ #-}
1450−numberOccurrencesFrom_ :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t b)
1451−numberOccurrencesFrom_ = mapAccum_ (\n _ -> let !next = n + 1 in (next, n))
1452−
1453−-- | This is used to sample the value of a 'Behavior' using an 'Event'.
1454−--
1455−-- The '<@>' operator is intended to be used in conjunction with
1456−-- the 'Applicative' instance for 'Behavior'.
1457−--
1458−-- This is useful when we want to combine the values of one 'Event' and
1459−-- the value of several 'Behavior's at the time the 'Event' is firing.
1460−--
1461−-- If we have:
1462−--
1463−-- > f :: a -> b -> c -> d
1464−-- > b1 :: Behavior t a
1465−-- > b2 :: Behavior t b
1466−-- > e :: Event t c
1467−--
1468−-- then we can do:
1469−--
1470−-- > f <$> b1 <*> b2 <@> e :: Event t d
1471−--
1472−-- in order to apply the function 'f' to the relevant values.
1473−--
1474−-- The alternative would be something like:
1475−--
1476−-- > attachWith (\(x1, x2) y -> f x1 x2 y) ((,) <$> b1 <*> b2) e :: Event t d
1477−--
1478−-- or a variation involing a custom data type to hold the combination of
1479−-- 'Behavior's even when that combination might only ever be used by 'f'.
1480−--
1481−-- A more suggestive example might be:
1482−--
1483−-- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)
1484−--
1485−(<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b
1486−(<@>) b = push $ \x -> do
1487− f <- sample b
1488− return . Just . f $ x
1489−infixl 4 <@>
1490−
1491−-- | An version of '<@>' that does not use the value of the 'Event'.
1492−--
1493−-- Alternatively, it is 'tag' in operator form.
1494−--
1495−-- This is useful when we want to combine the values of several
1496−-- 'Behavior's at particular points in time using an 'Applicative'
1497−-- style syntax.
1498−--
1499−-- If we have:
1500−--
1501−-- > g :: a -> b -> d
1502−-- > b1 :: Behavior t a
1503−-- > b2 :: Behavior t b
1504−-- > e :: Event t c
1505−--
1506−-- where 'e' is firing at the points in time of interest.
1507−--
1508−-- Then we can use '<@':
1509−--
1510−-- > g <$> b1 <*> b2 <@ e :: Event t d
1511−--
1512−-- to combine the values of 'b1' and 'b2' at each of those points of time,
1513−-- with the function 'g' being used to combine the values.
1514−--
1515−-- This is the same as '<@>' except that the 'Event' is being used only
1516−-- to act as a trigger.
1517−(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b
1518−(<@) = tag
1519−infixl 4 <@
1520−
1521−------------------
1522−-- Cheap Functions
1523−------------------
1524−
1525−-- | A "cheap" version of 'pushAlways'. See the performance note on 'pushCheap'.
1526−{-# INLINE pushAlwaysCheap #-}
1527−pushAlwaysCheap :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
1528−pushAlwaysCheap f = pushCheap (fmap Just . f)
1529−
1530−-- | A "cheap" version of 'mapMaybe'. See the performance note on 'pushCheap'.
1531−{-# INLINE mapMaybeCheap #-}
1532−mapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1533−mapMaybeCheap f = pushCheap $ return . f
1534−
1535−-- | An alias for 'mapMaybeCheap'
1536−{-# INLINE fmapMaybeCheap #-}
1537−fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1538−fmapMaybeCheap = mapMaybeCheap
1539−
1540−
1541−-- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'.
1542−{-# INLINE fforMaybeCheap #-}
1543−fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b
1544−fforMaybeCheap = flip mapMaybeCheap
1545−
1546−-- | A "cheap" version of 'ffor'. See the performance note on 'pushCheap'.
1547−{-# INLINE fforCheap #-}
1548−fforCheap :: Reflex t => Event t a -> (a -> b) -> Event t b
1549−fforCheap = flip fmapCheap
1550−
1551−-- | A "cheap" version of 'fmap'. See the performance note on 'pushCheap'.
1552−{-# INLINE fmapCheap #-}
1553−fmapCheap :: Reflex t => (a -> b) -> Event t a -> Event t b
1554−fmapCheap f = pushCheap $ return . Just . f
1555−
1556−-- | A "cheap" version of 'tag'. See the performance note on 'pushCheap'.
1557−{-# INLINE tagCheap #-}
1558−tagCheap :: Reflex t => Behavior t b -> Event t a -> Event t b
1559−tagCheap b = pushAlwaysCheap $ \_ -> sample b
1560−
1561−-- | A "cheap" version of 'mergeWithCheap'. See the performance note on 'pushCheap'.
1562−{-# INLINE mergeWithCheap #-}
1563−mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
1564−mergeWithCheap = mergeWithCheap' id
1565−
1566−-- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'.
1567−{-# INLINE mergeWithCheap' #-}
1568−mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
1569−mergeWithCheap' f g = mergeWithFoldCheap' $ foldl1 g . fmap f
1570−
1571−-- | A "cheap" version of 'mergeWithFoldCheap''. See the performance note on 'pushCheap'.
1572−{-# INLINE mergeWithFoldCheap' #-}
1573−mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b
1574−mergeWithFoldCheap' f es =
1575− fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)
1576− . mergeInt
1577− . IntMap.fromDistinctAscList
1578− $ zip [0 :: Int ..] es
1579−
1580−--------------------------------------------------------------------------------
1581−-- Deprecated functions
1582−--------------------------------------------------------------------------------
1583−
1584−{-# DEPRECATED switchPromptly "Use 'switchHoldPromptly' instead. The 'switchHold*' naming convention was chosen because those functions are more closely related to each other than they are to 'switch'. " #-}
1585−-- | See 'switchHoldPromptly'
1586−switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1587−switchPromptly = switchHoldPromptly
1588−{-# DEPRECATED switchPromptOnly "Use 'switchHoldPromptOnly' instead. The 'switchHold*' naming convention was chosen because those functions are more closely related to each other than they are to 'switch'. " #-}
1589−-- | See 'switchHoldPromptOnly'
1590−switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1591−switchPromptOnly = switchHoldPromptOnly
src/Reflex/Collection.hsdeleted−218
@@ -1,218 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE LambdaCase #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE RankNTypes #-}
6−{-# LANGUAGE RecursiveDo #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−#ifdef USE_REFLEX_OPTIMIZER
11−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12−#endif
13−-- |
14−-- Module:
15−-- Reflex.Collection
16−module Reflex.Collection
17− (
18− -- * Widgets on Collections
19− listHoldWithKey
20− , listWithKey
21− , listWithKeyShallowDiff
22− , listViewWithKey
23− , selectViewListWithKey
24− , selectViewListWithKey_
25− -- * List Utils
26− , list
27− , simpleList
28− ) where
29−
30−import Control.Monad.Identity
31−import Data.Align
32−import Data.Functor.Misc
33−import Data.Map (Map)
34−import qualified Data.Map as Map
35−import Data.Map.Misc
36−import Data.These
37−
38−import Reflex.Class
39−import Reflex.Adjustable.Class
40−import Reflex.Dynamic
41−import Reflex.PostBuild.Class
42−
43−-- | Create a set of widgets based on the provided 'Map'. When the
44−-- input 'Event' fires, remove widgets for keys with the value 'Nothing'
45−-- and add/replace widgets for keys with 'Just' values.
46−listHoldWithKey
47− :: forall t m k v a
48− . (Ord k, Adjustable t m, MonadHold t m)
49− => Map k v
50− -> Event t (Map k (Maybe v))
51− -> (k -> v -> m a)
52− -> m (Dynamic t (Map k a))
53−listHoldWithKey m0 m' f = do
54− let dm0 = mapWithFunctorToDMap $ Map.mapWithKey f m0
55− dm' = fmap
56− (PatchDMap . mapWithFunctorToDMap . Map.mapWithKey
57− (\k v -> ComposeMaybe $ fmap (f k) v)
58− )
59− m'
60− (a0, a') <- sequenceDMapWithAdjust dm0 dm'
61−
62− --TODO: Move the dmapToMap to the righthand side so it doesn't get
63− --fully redone every time
64− fmap dmapToMap . incrementalToDynamic <$> holdIncremental a0 a'
65−
66−--TODO: Something better than Dynamic t (Map k v) - we want something
67−--where the Events carry diffs, not the whole value
68−listWithKey
69− :: forall t k v m a
70− . (Ord k, Adjustable t m, PostBuild t m, MonadFix m, MonadHold t m)
71− => Dynamic t (Map k v)
72− -> (k -> Dynamic t v -> m a)
73− -> m (Dynamic t (Map k a))
74−listWithKey vals mkChild = do
75− postBuild <- getPostBuild
76− let childValChangedSelector = fanMap $ updated vals
77−
78− -- We keep track of changes to children values in the mkChild
79− -- function we pass to listHoldWithKey The other changes we need
80− -- to keep track of are child insertions and
81− -- deletions. diffOnlyKeyChanges keeps track of insertions and
82− -- deletions but ignores value changes, since they're already
83− -- accounted for.
84− diffOnlyKeyChanges olds news =
85− flip Map.mapMaybe (align olds news) $ \case
86− This _ -> Just Nothing
87− These _ _ -> Nothing
88− That new -> Just $ Just new
89− rec sentVals :: Dynamic t (Map k v) <- foldDyn applyMap Map.empty changeVals
90− let changeVals :: Event t (Map k (Maybe v))
91− changeVals =
92− attachWith diffOnlyKeyChanges (current sentVals) $ leftmost
93− [ updated vals
94−
95− -- TODO: This should probably be added to the
96− -- attachWith, not to the updated; if we were using
97− -- diffMap instead of diffMapNoEq, I think it might not
98− -- work
99− , tag (current vals) postBuild
100− ]
101− listHoldWithKey Map.empty changeVals $ \k v ->
102− mkChild k =<< holdDyn v (select childValChangedSelector $ Const2 k)
103−
104−-- | Display the given map of items (in key order) using the builder
105−-- function provided, and update it with the given event. 'Nothing'
106−-- update entries will delete the corresponding children, and 'Just'
107−-- entries will create them if they do not exist or send an update
108−-- event to them if they do.
109−listWithKeyShallowDiff
110− :: (Ord k, Adjustable t m, MonadFix m, MonadHold t m)
111− => Map k v
112− -> Event t (Map k (Maybe v))
113− -> (k -> v -> Event t v -> m a)
114− -> m (Dynamic t (Map k a))
115−listWithKeyShallowDiff initialVals valsChanged mkChild = do
116− let childValChangedSelector = fanMap $ fmap (Map.mapMaybe id) valsChanged
117− sentVals <- foldDyn applyMap (void initialVals) $ fmap (fmap void) valsChanged
118− let relevantPatch patch _ = case patch of
119−
120− -- Even if we let a Nothing through when the element doesn't
121− -- already exist, this doesn't cause a problem because it is
122− -- ignored
123− Nothing -> Just Nothing
124−
125− -- We don't want to let spurious re-creations of items through
126− Just _ -> Nothing
127− listHoldWithKey
128− initialVals
129− (attachWith (flip (Map.differenceWith relevantPatch))
130− (current sentVals)
131− valsChanged
132− )
133− $ \k v -> mkChild k v $ select childValChangedSelector $ Const2 k
134−
135−--TODO: Something better than Dynamic t (Map k v) - we want something
136−--where the Events carry diffs, not the whole value
137−-- | Create a dynamically-changing set of Event-valued widgets. This
138−-- is like 'listWithKey', specialized for widgets returning @/Event t a/@.
139−-- 'listWithKey' would return @/Dynamic t (Map k (Event t a))/@ in
140−-- this scenario, but 'listViewWithKey' flattens this to
141−-- @/Event t (Map k a)/@ via 'switch'.
142−listViewWithKey
143− :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
144− => Dynamic t (Map k v)
145− -> (k -> Dynamic t v -> m (Event t a))
146− -> m (Event t (Map k a))
147−listViewWithKey vals mkChild =
148− switch . fmap mergeMap <$> listViewWithKey' vals mkChild
149−
150−listViewWithKey'
151− :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
152− => Dynamic t (Map k v)
153− -> (k -> Dynamic t v -> m a)
154− -> m (Behavior t (Map k a))
155−listViewWithKey' vals mkChild = current <$> listWithKey vals mkChild
156−
157−-- | Create a dynamically-changing set of widgets, one of which is
158−-- selected at any time.
159−selectViewListWithKey
160− :: forall t m k v a
161− . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
162− => Dynamic t k
163− -- ^ Current selection key
164− -> Dynamic t (Map k v)
165− -- ^ Dynamic key/value map
166− -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
167− -- ^ Function to create a widget for a given key from Dynamic value
168− -- and Dynamic Bool indicating if this widget is currently selected
169− -> m (Event t (k, a))
170− -- ^ Event that fires when any child's return Event fires. Contains
171− -- key of an arbitrary firing widget.
172−selectViewListWithKey selection vals mkChild = do
173− -- For good performance, this value must be shared across all children
174− let selectionDemux = demux selection
175− selectChild <- listWithKey vals $ \k v -> do
176− let selected = demuxed selectionDemux k
177− selectSelf <- mkChild k v selected
178− return $ fmap ((,) k) selectSelf
179− return $ switchPromptlyDyn $ leftmost . Map.elems <$> selectChild
180−
181−-- | Like 'selectViewListWithKey' but discards the value of the list
182−-- item widget's output 'Event'.
183−selectViewListWithKey_
184− :: forall t m k v a
185− . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
186− => Dynamic t k
187− -- ^ Current selection key
188− -> Dynamic t (Map k v)
189− -- ^ Dynamic key/value map
190− -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
191− -- ^ Function to create a widget for a given key from Dynamic value
192− -- and Dynamic Bool indicating if this widget is currently selected
193− -> m (Event t k)
194− -- ^ Event that fires when any child's return Event fires. Contains
195− -- key of an arbitrary firing widget.
196−selectViewListWithKey_ selection vals mkChild =
197− fmap fst <$> selectViewListWithKey selection vals mkChild
198−
199−-- | Create a dynamically-changing set of widgets from a Dynamic
200−-- key/value map. Unlike the 'withKey' variants, the child widgets
201−-- are insensitive to which key they're associated with.
202−list
203− :: (Ord k, Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
204− => Dynamic t (Map k v)
205− -> (Dynamic t v -> m a)
206− -> m (Dynamic t (Map k a))
207−list dm mkChild = listWithKey dm (\_ dv -> mkChild dv)
208−
209−-- | Create a dynamically-changing set of widgets from a Dynamic list.
210−simpleList
211− :: (Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
212− => Dynamic t [v]
213− -> (Dynamic t v -> m a)
214− -> m (Dynamic t [a])
215−simpleList xs mkChild =
216− fmap (fmap (map snd . Map.toList)) $ flip list mkChild $ fmap
217− (Map.fromList . zip [(1 :: Int) ..])
218− xs
src/Reflex/Dynamic.hsdeleted−530
@@ -1,530 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoMonomorphismRestriction #-}
9−{-# LANGUAGE PolyKinds #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE RecursiveDo #-}
12−{-# LANGUAGE ScopedTypeVariables #-}
13−{-# LANGUAGE StandaloneDeriving #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE TypeOperators #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−#ifdef USE_REFLEX_OPTIMIZER
18−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
19−#endif
20−-- |
21−-- Module:
22−-- Reflex.Dynamic
23−-- Description:
24−-- This module contains various functions for working with 'Dynamic' values.
25−-- 'Dynamic' and its primitives have been moved to the 'Reflex' class.
26−module Reflex.Dynamic
27− ( -- * Basics
28− Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update
29− , current
30− , updated
31− , holdDyn
32− , mapDynM
33− , forDynM
34− , constDyn
35− , count
36− , toggle
37− , switchDyn
38− , switchPromptlyDyn
39− , tagPromptlyDyn
40− , attachPromptlyDyn
41− , attachPromptlyDynWith
42− , attachPromptlyDynWithMaybe
43− , maybeDyn
44− , eitherDyn
45− , factorDyn
46− , scanDyn
47− , scanDynMaybe
48− , holdUniqDyn
49− , holdUniqDynBy
50− , improvingMaybe
51− , foldDyn
52− , foldDynM
53− , foldDynMaybe
54− , foldDynMaybeM
55− , joinDynThroughMap
56− , traceDyn
57− , traceDynWith
58− , splitDynPure
59− , distributeMapOverDynPure
60− , distributeDMapOverDynPure
61− , distributeListOverDynPure
62− , Demux
63− , demux
64− , demuxed
65− -- * Miscellaneous
66− -- Things that probably aren't very useful:
67− , HList (..)
68− , FHList (..)
69− , collectDynPure
70− , RebuildSortedHList (..)
71− , IsHList (..)
72− , AllAreFunctors (..)
73− , HListPtr (..)
74− , distributeFHListOverDynPure
75− -- * Unsafe
76− , unsafeDynamic
77− ) where
78−
79−import Data.Functor.Compose
80−import Data.Functor.Misc
81−import Reflex.Class
82−
83−import Control.Monad
84−import Control.Monad.Fix
85−import Control.Monad.Identity
86−import Data.Align
87−import Data.Dependent.Map (DMap)
88−import qualified Data.Dependent.Map as DMap
89−import Data.Dependent.Sum (DSum (..))
90−import Data.GADT.Compare ((:~:) (..), GCompare (..), GEq (..), GOrdering (..))
91−import Data.Map (Map)
92−import Data.Maybe
93−import Data.Monoid ((<>))
94−import Data.These
95−
96−import Debug.Trace
97−
98−-- | Map a sampling function over a 'Dynamic'.
99−mapDynM :: forall t m a b. (Reflex t, MonadHold t m) => (forall m'. MonadSample t m' => a -> m' b) -> Dynamic t a -> m (Dynamic t b)
100−mapDynM f d = buildDynamic (f =<< sample (current d)) $ pushAlways f (updated d)
101−
102−-- | Flipped version of 'mapDynM'
103−forDynM :: forall t m a b. (Reflex t, MonadHold t m) => Dynamic t a -> (forall m'. MonadSample t m' => a -> m' b) -> m (Dynamic t b)
104−forDynM d f = mapDynM f d
105−
106−-- | Create a new 'Dynamic' that only signals changes if the values actually
107−-- changed.
108−holdUniqDyn :: (Reflex t, MonadHold t m, MonadFix m, Eq a) => Dynamic t a -> m (Dynamic t a)
109−holdUniqDyn = holdUniqDynBy (==)
110−
111−-- | Create a new 'Dynamic' that changes only when the underlying 'Dynamic'
112−-- changes and the given function returns 'False' when given both the old and
113−-- the new values.
114−holdUniqDynBy :: (Reflex t, MonadHold t m, MonadFix m) => (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
115−holdUniqDynBy eq = scanDynMaybe id (\new old -> if new `eq` old then Nothing else Just new)
116−
117−-- | @/Dynamic Maybe/@ that can only update from @/Nothing/@ to @/Just/@ or @/Just/@ to @/Just/@ (i.e., cannot revert to @/Nothing/@)
118−improvingMaybe :: (Reflex t, MonadHold t m, MonadFix m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe a))
119−improvingMaybe = scanDynMaybe id (\new _ -> if isJust new then Just new else Nothing)
120−
121−-- | Create a 'Dynamic' that accumulates values from another 'Dynamic'. This
122−-- function does not force its input 'Dynamic' until the output 'Dynamic' is
123−-- forced.
124−scanDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> b) -> Dynamic t a -> m (Dynamic t b)
125−scanDyn z f = scanDynMaybe z (\a b -> Just $ f a b)
126−
127−-- | Like 'scanDyn', but the the accumulator function may decline to update the
128−-- result 'Dynamic''s value.
129−scanDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> Maybe b) -> Dynamic t a -> m (Dynamic t b)
130−scanDynMaybe z f d = do
131− rec d' <- buildDynamic (z <$> sample (current d)) $ flip push (updated d) $ \a -> do
132− b <- sample $ current d'
133− return $ f a b
134− return d'
135−
136−-- | Create a 'Dynamic' using the initial value and change it each time the
137−-- 'Event' occurs using a folding function on the previous value and the value
138−-- of the 'Event'.
139−foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b)
140−foldDyn = accumDyn . flip
141−
142−-- | Like 'foldDyn', but the combining function is a 'PushM' action, so it
143−-- can 'sample' existing 'Behaviors' and 'hold' new ones.
144−foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b)
145−foldDynM = accumMDyn . flip
146−
147−-- | Create a 'Dynamic' using the provided initial value and change it each time
148−-- the provided 'Event' occurs, using a function to combine the old value with
149−-- the 'Event''s value. If the function returns 'Nothing', the value is not
150−-- changed; this is distinct from returning 'Just' the old value, since the
151−-- 'Dynamic''s 'updated' 'Event' will fire in the 'Just' case, and will not fire
152−-- in the 'Nothing' case.
153−foldDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> Maybe b) -> b -> Event t a -> m (Dynamic t b)
154−foldDynMaybe = accumMaybeDyn . flip
155−
156−-- | Like 'foldDynMaybe', but the combining function is a 'PushM' action, so it
157−-- can 'sample' existing 'Behaviors' and 'hold' new ones.
158−foldDynMaybeM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe b)) -> b -> Event t a -> m (Dynamic t b)
159−foldDynMaybeM = accumMaybeMDyn . flip
160−
161−-- | Create a new 'Dynamic' that counts the occurrences of the 'Event'.
162−count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)
163−count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e
164−
165−-- | Create a new 'Dynamic' using the initial value that flips its
166−-- value every time the 'Event' occurs.
167−toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool)
168−toggle = foldDyn (const not)
169−
170−-- | Switches to the new 'Event' whenever it receives one. Only the old event is
171−-- considered the moment a new one is switched in; the output event will fire at
172−-- that moment if only if the old event does.
173−--
174−-- Prefer this to 'switchPromptlyDyn' where possible. The lack of doing double
175−-- work when the outer and (new) inner fires means this imposes fewer "timing
176−-- requirements" and thus is far more easy to use without introducing fresh
177−-- failure cases. 'switchDyn' is also more performant.
178−switchDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
179−switchDyn d = switch (current d)
180−
181−-- | Switches to the new 'Event' whenever it receives one. Switching occurs
182−-- __before__ the inner 'Event' fires - so if the 'Dynamic' changes and both the
183−-- old and new inner Events fire simultaneously, the output will fire with the
184−-- value of the __new__ 'Event'.
185−--
186−-- Prefer 'switchDyn' to this where possible. The timing requirements that
187−-- switching before imposes are likely to bring down your app unless you are
188−-- very careful. 'switchDyn' is also more performant.
189−switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
190−switchPromptlyDyn de =
191− let eLag = switch $ current de
192− eCoincidences = coincidence $ updated de
193− in leftmost [eCoincidences, eLag]
194−
195−-- | Split a 'Dynamic' pair into a pair of 'Dynamic's
196−splitDynPure :: Reflex t => Dynamic t (a, b) -> (Dynamic t a, Dynamic t b)
197−splitDynPure d = (fmap fst d, fmap snd d)
198−
199−-- | Convert a 'Map' with 'Dynamic' elements into a 'Dynamic' of a 'Map' with
200−-- non-'Dynamic' elements.
201−distributeMapOverDynPure :: (Reflex t, Ord k) => Map k (Dynamic t v) -> Dynamic t (Map k v)
202−distributeMapOverDynPure = fmap dmapToMap . distributeDMapOverDynPure . mapWithFunctorToDMap
203−
204−-- | Convert a list with 'Dynamic' elements into a 'Dynamic' of a list with
205−-- non-'Dynamic' elements, preserving the order of the elements.
206−{-# DEPRECATED distributeListOverDynPure "Use 'distributeListOverDyn' instead" #-}
207−distributeListOverDynPure :: Reflex t => [Dynamic t v] -> Dynamic t [v]
208−distributeListOverDynPure = distributeListOverDyn
209−
210−--TODO: Generalize this to functors other than Maps
211−-- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic'
212−-- with the current values of the 'Dynamic's in a map.
213−joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)
214−joinDynThroughMap = (distributeMapOverDynPure =<<)
215−
216−-- | Print the value of the 'Dynamic' when it is first read and on each
217−-- subsequent change that is observed (as 'traceEvent'), prefixed with the
218−-- provided string. This should /only/ be used for debugging.
219−--
220−-- Note: Just like Debug.Trace.trace, the value will only be shown if something
221−-- else in the system is depending on it.
222−traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a
223−traceDyn s = traceDynWith $ \x -> s <> ": " <> show x
224−
225−-- | Print the result of applying the provided function to the value
226−-- of the 'Dynamic' when it is first read and on each subsequent change
227−-- that is observed (as 'traceEvent'). This should /only/ be used for
228−-- debugging.
229−--
230−-- Note: Just like Debug.Trace.trace, the value will only be shown if something
231−-- else in the system is depending on it.
232−traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a
233−traceDynWith f d =
234− let e' = traceEventWith f $ updated d
235− getV0 = do
236− x <- sample $ current d
237− trace (f x) $ return x
238− in unsafeBuildDynamic getV0 e'
239−
240−-- | Replace the value of the 'Event' with the current value of the 'Dynamic'
241−-- each time the 'Event' occurs.
242−--
243−-- Note: @/tagPromptlyDyn d e/@ differs from @/tag (current d) e/@ in the case that @/e/@ is firing
244−-- at the same time that @/d/@ is changing. With @/tagPromptlyDyn d e/@, the __new__ value of @/d/@
245−-- will replace the value of @/e/@, whereas with @/tag (current d) e/@, the __old__ value
246−-- will be used, since the 'Behavior' won't be updated until the end of the frame.
247−-- Additionally, this means that the output 'Event' may not be used to directly change
248−-- the input 'Dynamic', because that would mean its value depends on itself. __When creating__
249−-- __cyclic data flows, generally @/tag (current d) e/@ is preferred.__
250−tagPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
251−tagPromptlyDyn = attachPromptlyDynWith const
252−
253−-- | Attach the current value of the 'Dynamic' to the value of the
254−-- 'Event' each time it occurs.
255−--
256−-- Note: @/attachPromptlyDyn d/@ is not the same as @/attach (current d)/@. See 'tagPromptlyDyn' for details.
257−attachPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
258−attachPromptlyDyn = attachPromptlyDynWith (,)
259−
260−-- | Combine the current value of the 'Dynamic' with the value of the
261−-- 'Event' each time it occurs.
262−--
263−-- Note: @/attachPromptlyDynWith f d/@ is not the same as @/attachWith f (current d)/@. See 'tagPromptlyDyn' for details.
264−attachPromptlyDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
265−attachPromptlyDynWith f = attachPromptlyDynWithMaybe $ \a b -> Just $ f a b
266−
267−-- | Create a new 'Event' by combining the value at each occurrence with the
268−-- current value of the 'Dynamic' value and possibly filtering if the combining
269−-- function returns 'Nothing'.
270−--
271−-- Note: @/attachPromptlyDynWithMaybe f d/@ is not the same as @/attachWithMaybe f (current d)/@. See 'tagPromptlyDyn' for details.
272−attachPromptlyDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
273−attachPromptlyDynWithMaybe f d e =
274− let e' = attach (current d) e
275− in fforMaybe (align e' $ updated d) $ \case
276− This (a, b) -> f a b -- Only the tagging event is firing, so use that
277− These (_, b) a -> f a b -- Both events are firing, so use the newer value
278− That _ -> Nothing -- The tagging event isn't firing, so don't fire
279−
280−-- | Factor a @/Dynamic t (Maybe a)/@ into a @/Dynamic t (Maybe (Dynamic t a))/@,
281−-- such that the outer 'Dynamic' is updated only when the "Maybe"'s constructor
282−-- chages from 'Nothing' to 'Just' or vice-versa. Whenever the constructor
283−-- becomes 'Just', an inner 'Dynamic' will be provided, whose value will track
284−-- the 'a' inside the 'Just'; when the constructor becomes 'Nothing', the
285−-- existing inner 'Dynamic' will become constant, and will not change when the
286−-- outer constructor changes back to 'Nothing'.
287−maybeDyn :: forall t a m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe (Dynamic t a)))
288−maybeDyn = fmap (fmap unpack) . eitherDyn . fmap pack
289− where pack = \case
290− Nothing -> Left ()
291− Just a -> Right a
292− unpack = \case
293− Left _ -> Nothing
294− Right a -> Just a
295−
296−-- | Turns a 'Dynamic t (Either a b)' into a 'Dynamic t (Either (Dynamic t a) (Dynamic t b))' such that
297−-- the outer 'Dynamic' is updated only when the 'Either' constructor changes (e.g., from 'Left' to 'Right').
298−eitherDyn :: forall t a b m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Either a b) -> m (Dynamic t (Either (Dynamic t a) (Dynamic t b)))
299−eitherDyn = fmap (fmap unpack) . factorDyn . fmap eitherToDSum
300− where unpack :: DSum (EitherTag a b) (Compose (Dynamic t) Identity) -> Either (Dynamic t a) (Dynamic t b)
301− unpack = \case
302− LeftTag :=> Compose a -> Left $ coerceDynamic a
303− RightTag :=> Compose b -> Right $ coerceDynamic b
304−
305−-- | Factor a 'Dynamic t DSum' into a 'Dynamic' 'DSum' containing nested 'Dynamic' values.
306−-- The outer 'Dynamic' updates only when the key of the 'DSum' changes, while the update of the inner
307−-- 'Dynamic' represents updates within the current key.
308−factorDyn :: forall t m k v. (Reflex t, MonadHold t m, GEq k)
309− => Dynamic t (DSum k v) -> m (Dynamic t (DSum k (Compose (Dynamic t) v)))
310−factorDyn d = buildDynamic (sample (current d) >>= holdKey) update where
311− update :: Event t (DSum k (Compose (Dynamic t) v))
312− update = flip push (updated d) $ \(newKey :=> newVal) -> do
313− (oldKey :=> _) <- sample (current d)
314− case newKey `geq` oldKey of
315− Just Refl -> return Nothing
316− Nothing -> Just <$> holdKey (newKey :=> newVal)
317−
318− holdKey (k :=> v) = do
319− inner' <- filterEventKey k (updated d)
320− inner <- holdDyn v inner'
321− return $ k :=> Compose inner
322−
323−--------------------------------------------------------------------------------
324−-- Demux
325−--------------------------------------------------------------------------------
326−
327−-- | Represents a time changing value together with an 'EventSelector' that can
328−-- efficiently detect when the underlying 'Dynamic' has a particular value.
329−-- This is useful for representing data like the current selection of a long
330−-- list.
331−--
332−-- Semantically,
333−--
334−-- > demuxed (demux d) k === fmap (== k) d
335−--
336−-- However, when getDemuxed is used multiple times, the complexity is only
337−-- /O(log(n))/, rather than /O(n)/ for fmap.
338−data Demux t k = Demux { demuxValue :: Behavior t k
339− , demuxSelector :: EventSelector t (Const2 k Bool)
340− }
341−
342−-- | Demultiplex an input value to a 'Demux' with many outputs. At any given
343−-- time, whichever output is indicated by the given 'Dynamic' will be 'True'.
344−demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k
345−demux k = Demux (current k)
346− (fan $ attachWith (\k0 k1 -> if k0 == k1
347− then DMap.empty
348− else DMap.fromList [Const2 k0 :=> Identity False,
349− Const2 k1 :=> Identity True])
350− (current k) (updated k))
351−
352−-- | Select a particular output of the 'Demux'; this is equivalent to (but much
353−-- faster than) mapping over the original 'Dynamic' and checking whether it is
354−-- equal to the given key.
355−demuxed :: (Reflex t, Eq k) => Demux t k -> k -> Dynamic t Bool
356−demuxed d k =
357− let e = select (demuxSelector d) (Const2 k)
358− in unsafeBuildDynamic (fmap (==k) $ sample $ demuxValue d) e
359−
360−--------------------------------------------------------------------------------
361−-- collectDyn
362−--------------------------------------------------------------------------------
363−
364−--TODO: This whole section is badly in need of cleanup
365−
366−-- | A heterogeneous list whose type and length are fixed statically. This is
367−-- reproduced from the 'HList' package due to integration issues, and because
368−-- very little other functionality from that library is needed.
369−data HList (l::[*]) where
370− HNil :: HList '[]
371− HCons :: e -> HList l -> HList (e ': l)
372−
373−infixr 2 `HCons`
374−
375−type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
376−type instance HRevApp '[] l = l
377−type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
378−
379−hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
380−hRevApp HNil l = l
381−hRevApp (HCons x l) l' = hRevApp l (HCons x l')
382−
383−hReverse :: HList l -> HList (HRevApp l '[])
384−hReverse l = hRevApp l HNil
385−
386−hBuild :: (HBuild' '[] r) => r
387−hBuild = hBuild' HNil
388−
389−class HBuild' l r where
390− hBuild' :: HList l -> r
391−
392−instance (l' ~ HRevApp l '[])
393− => HBuild' l (HList l') where
394− hBuild' = hReverse
395−
396−instance HBuild' (a ': l) r
397− => HBuild' l (a->r) where
398− hBuild' l x = hBuild' (HCons x l)
399−
400−-- | Like 'HList', but with a functor wrapping each element.
401−data FHList f l where
402− FHNil :: FHList f '[]
403− FHCons :: f e -> FHList f l -> FHList f (e ': l)
404−
405−instance GEq (HListPtr l) where
406− HHeadPtr `geq` HHeadPtr = Just Refl
407− HHeadPtr `geq` HTailPtr _ = Nothing
408− HTailPtr _ `geq` HHeadPtr = Nothing
409− HTailPtr a `geq` HTailPtr b = a `geq` b
410−
411−instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dmapTo*HList will break
412− HHeadPtr `gcompare` HHeadPtr = GEQ
413− HHeadPtr `gcompare` HTailPtr _ = GLT
414− HTailPtr _ `gcompare` HHeadPtr = GGT
415− HTailPtr a `gcompare` HTailPtr b = a `gcompare` b
416−
417−-- | A typed index into a typed heterogeneous list.
418−data HListPtr l a where
419− HHeadPtr :: HListPtr (h ': t) h
420− HTailPtr :: HListPtr t a -> HListPtr (h ': t) a
421−
422−deriving instance Eq (HListPtr l a)
423−deriving instance Ord (HListPtr l a)
424−
425−fhlistToDMap :: forall (f :: * -> *) l. FHList f l -> DMap (HListPtr l) f
426−fhlistToDMap = DMap.fromList . go
427− where go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]
428− go = \case
429− FHNil -> []
430− FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)
431−
432−-- | This class allows 'HList's and 'FHlist's to be built from regular lists;
433−-- they must be contiguous and sorted.
434−class RebuildSortedHList l where
435− rebuildSortedFHList :: [DSum (HListPtr l) f] -> FHList f l
436− rebuildSortedHList :: [DSum (HListPtr l) Identity] -> HList l
437−
438−instance RebuildSortedHList '[] where
439− rebuildSortedFHList l = case l of
440− [] -> FHNil
441− _ : _ -> error "rebuildSortedFHList{'[]}: empty list expected"
442− rebuildSortedHList l = case l of
443− [] -> HNil
444− _ : _ -> error "rebuildSortedHList{'[]}: empty list expected"
445−
446−instance RebuildSortedHList t => RebuildSortedHList (h ': t) where
447− rebuildSortedFHList l = case l of
448− ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
449− _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected"
450− rebuildSortedHList l = case l of
451− ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
452− _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected"
453−
454−dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) Identity -> HList l
455−dmapToHList = rebuildSortedHList . DMap.toList
456−
457−-- | Collect a hetereogeneous list whose elements are all 'Dynamic's into a
458−-- single 'Dynamic' whose value represents the current values of all of the
459−-- input 'Dynamic's.
460−distributeFHListOverDynPure :: (Reflex t, RebuildSortedHList l) => FHList (Dynamic t) l -> Dynamic t (HList l)
461−distributeFHListOverDynPure l = fmap dmapToHList $ distributeDMapOverDynPure $ fhlistToDMap l
462−
463−-- | Indicates that all elements in a type-level list are applications of the
464−-- same functor.
465−class AllAreFunctors (f :: a -> *) (l :: [a]) where
466− type FunctorList f l :: [*]
467− toFHList :: HList (FunctorList f l) -> FHList f l
468− fromFHList :: FHList f l -> HList (FunctorList f l)
469−
470−instance AllAreFunctors f '[] where
471− type FunctorList f '[] = '[]
472− toFHList l = case l of
473− HNil -> FHNil
474−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
475− _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
476−#endif
477− fromFHList FHNil = HNil
478−
479−instance AllAreFunctors f t => AllAreFunctors f (h ': t) where
480− type FunctorList f (h ': t) = f h ': FunctorList f t
481− toFHList l = case l of
482− a `HCons` b -> a `FHCons` toFHList b
483−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
484− _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
485−#endif
486− fromFHList (a `FHCons` b) = a `HCons` fromFHList b
487−
488−-- | Convert a datastructure whose constituent parts are all 'Dynamic's into a
489−-- single 'Dynamic' whose value represents all the current values of the input's
490−-- constituent 'Dynamic's.
491−collectDynPure :: ( RebuildSortedHList (HListElems b)
492− , IsHList a, IsHList b
493− , AllAreFunctors (Dynamic t) (HListElems b)
494− , Reflex t
495− , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
496− ) => a -> Dynamic t b
497−collectDynPure ds = fmap fromHList $ distributeFHListOverDynPure $ toFHList $ toHList ds
498−
499−-- | Poor man's 'Generic's for product types only.
500−class IsHList a where
501− type HListElems a :: [*]
502− toHList :: a -> HList (HListElems a)
503− fromHList :: HList (HListElems a) -> a
504−
505−instance IsHList (a, b) where
506− type HListElems (a, b) = [a, b]
507− toHList (a, b) = hBuild a b
508− fromHList l = case l of
509− a `HCons` b `HCons` HNil -> (a, b)
510−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
511− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
512−#endif
513−
514−instance IsHList (a, b, c, d) where
515− type HListElems (a, b, c, d) = [a, b, c, d]
516− toHList (a, b, c, d) = hBuild a b c d
517− fromHList l = case l of
518− a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d)
519−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
520− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
521−#endif
522−
523−instance IsHList (a, b, c, d, e, f) where
524− type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]
525− toHList (a, b, c, d, e, f) = hBuild a b c d e f
526− fromHList l = case l of
527− a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f)
528−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
529− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
530−#endif
src/Reflex/Dynamic/TH.hsdeleted−106
@@ -1,106 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE EmptyDataDecls #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE PatternGuards #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE TemplateHaskell #-}
7−{-# LANGUAGE TypeOperators #-}
8−#ifdef USE_REFLEX_OPTIMIZER
9−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10−#endif
11−-- | Template Haskell helper functions for building complex 'Dynamic' values.
12−module Reflex.Dynamic.TH
13− ( qDynPure
14− , unqDyn
15− , mkDynPure
16− ) where
17−
18−import Reflex.Dynamic
19−
20−import Control.Monad.State
21−import Data.Data
22−import Data.Generics
23−import Data.Monoid ((<>))
24−import qualified Language.Haskell.Exts as Hs
25−import qualified Language.Haskell.Meta.Syntax.Translate as Hs
26−import Language.Haskell.TH
27−import Language.Haskell.TH.Quote
28−import qualified Language.Haskell.TH.Syntax as TH
29−
30−-- | Quote a 'Dynamic' expression. Within the quoted expression, you can use
31−-- @$(unqDyn [| x |])@ to refer to any expression @x@ of type @Dynamic t a@; the
32−-- unquoted result will be of type @a@
33−qDynPure :: Q Exp -> Q Exp
34−qDynPure qe = do
35− e <- qe
36− let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d
37− f d = case eqT of
38− Just (Refl :: d :~: Exp)
39− | AppE (VarE m) eInner <- d
40− , m == 'unqMarker
41− -> do n <- lift $ newName "dynamicQuotedExpressionVariable"
42− modify ((n, eInner):)
43− return $ VarE n
44− _ -> gmapM f d
45− (e', exprsReversed) <- runStateT (gmapM f e) []
46− let exprs = reverse exprsReversed
47− arg = foldr (\a b -> ConE 'FHCons `AppE` snd a `AppE` b) (ConE 'FHNil) exprs
48− param = foldr (\a b -> ConP 'HCons [VarP (fst a), b]) (ConP 'HNil []) exprs
49− [| $(return $ LamE [param] e') <$> distributeFHListOverDynPure $(return arg) |]
50−
51−-- | Antiquote a 'Dynamic' expression. This can /only/ be used inside of a
52−-- 'qDyn' quotation.
53−unqDyn :: Q Exp -> Q Exp
54−unqDyn e = [| unqMarker $e |]
55−
56−-- | This type represents an occurrence of unqDyn before it has been processed
57−-- by qDyn. If you see it in a type error, it probably means that unqDyn has
58−-- been used outside of a qDyn context.
59−data UnqDyn
60−
61−-- unqMarker must not be exported; it is used only as a way of smuggling data
62−-- from unqDyn to qDyn
63−
64−--TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery
65−unqMarker :: a -> UnqDyn
66−unqMarker = error "An unqDyn expression was used outside of a qDyn expression"
67−
68−-- | Create a 'Dynamic' value using other 'Dynamic's as inputs. The result is
69−-- sometimes more concise and readable than the equivalent 'Applicative'-based
70−-- expression. For example:
71−--
72−-- > [mkDyn| $x + $v * $t + 1/2 * $a * $t ^ 2 |]
73−--
74−-- would have a very cumbersome 'Applicative' encoding.
75−mkDynPure :: QuasiQuoter
76−mkDynPure = QuasiQuoter
77− { quoteExp = mkDynExp
78− , quotePat = error "mkDyn: pattern splices are not supported"
79− , quoteType = error "mkDyn: type splices are not supported"
80− , quoteDec = error "mkDyn: declaration splices are not supported"
81− }
82−
83−mkDynExp :: String -> Q Exp
84−mkDynExp s = case Hs.parseExpWithMode (Hs.defaultParseMode { Hs.extensions = [ Hs.EnableExtension Hs.TemplateHaskell ] }) s of
85− Hs.ParseFailed (Hs.SrcLoc _ l c) err -> fail $ "mkDyn:" <> show l <> ":" <> show c <> ": " <> err
86− Hs.ParseOk e -> qDynPure $ return $ everywhere (id `extT` reinstateUnqDyn) $ Hs.toExp $ everywhere (id `extT` antiE) e
87− where TH.Name (TH.OccName occName) (TH.NameG _ _ (TH.ModName modName)) = 'unqMarker
88−#if MIN_VERSION_haskell_src_exts(1,18,0)
89− antiE :: Hs.Exp Hs.SrcSpanInfo -> Hs.Exp Hs.SrcSpanInfo
90− antiE x = case x of
91− Hs.SpliceExp l se ->
92− Hs.App l (Hs.Var l $ Hs.Qual l (Hs.ModuleName l modName) (Hs.Ident l occName)) $ case se of
93− Hs.IdSplice l2 v -> Hs.Var l2 $ Hs.UnQual l2 $ Hs.Ident l2 v
94− Hs.ParenSplice _ ps -> ps
95− _ -> x
96−#else
97− antiE x = case x of
98− Hs.SpliceExp se ->
99− Hs.App (Hs.Var $ Hs.Qual (Hs.ModuleName modName) (Hs.Ident occName)) $ case se of
100− Hs.IdSplice v -> Hs.Var $ Hs.UnQual $ Hs.Ident v
101− Hs.ParenSplice ps -> ps
102− _ -> x
103−#endif
104− reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName')))
105− | modName == modName' && occName == occName' = 'unqMarker
106− reinstateUnqDyn x = x
src/Reflex/Dynamic/Uniq.hsdeleted−105
@@ -1,105 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE MagicHash #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−#ifdef USE_REFLEX_OPTIMIZER
6−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
7−#endif
8−-- | This module provides a variation of 'Dynamic' values that uses cheap
9−-- pointer equality checks to reduce the amount of signal propagation needed.
10−module Reflex.Dynamic.Uniq
11− ( UniqDynamic
12− , uniqDynamic
13− , fromUniqDynamic
14− , alreadyUniqDynamic
15− ) where
16−
17−import Control.Applicative (Applicative (..))
18−import GHC.Exts
19−import Reflex.Class
20−
21−-- | A 'Dynamic' whose 'updated' 'Event' will never fire with the same value as
22−-- the 'current' 'Behavior''s contents. In order to maintain this constraint,
23−-- the value inside a 'UniqDynamic' is always evaluated to
24−-- <https://wiki.haskell.org/Weak_head_normal_form weak head normal form>.
25−--
26−-- Internally, 'UniqDynamic' uses pointer equality as a heuristic to avoid
27−-- unnecessary update propagation; this is much more efficient than performing
28−-- full comparisons. However, when the 'UniqDynamic' is converted back into a
29−-- regular 'Dynamic', a full comparison is performed.
30−newtype UniqDynamic t a = UniqDynamic { unUniqDynamic :: Dynamic t a }
31−
32−-- | Construct a 'UniqDynamic' by eliminating redundant updates from a 'Dynamic'.
33−uniqDynamic :: Reflex t => Dynamic t a -> UniqDynamic t a
34−uniqDynamic d = UniqDynamic $ unsafeBuildDynamic (sample $ current d) $ flip pushCheap (updated d) $ \new -> do
35− old <- sample $ current d --TODO: Is it better to sample ourselves here?
36− return $ unsafeJustChanged old new
37−
38−-- | Retrieve a normal 'Dynamic' from a 'UniqDynamic'. This will perform a
39−-- final check using the output type's 'Eq' instance to ensure deterministic
40−-- behavior.
41−--
42−-- WARNING: If used with a type whose 'Eq' instance is not law-abiding -
43−-- specifically, if there are cases where @x /= x@, 'fromUniqDynamic' may
44−-- eliminate more 'updated' occurrences than it should. For example, NaN values
45−-- of 'Double' and 'Float' are considered unequal to themselves by the 'Eq'
46−-- instance, but can be equal by pointer equality. This may cause 'UniqDynamic'
47−-- to lose changes from NaN to NaN.
48−fromUniqDynamic :: (Reflex t, Eq a) => UniqDynamic t a -> Dynamic t a
49−fromUniqDynamic (UniqDynamic d) = unsafeDynamic (current d) e'
50− where
51− -- Only consider values different if they fail both pointer equality /and/
52− -- 'Eq' equality. This is to make things a bit more deterministic in the
53− -- case of unlawful 'Eq' instances. However, it is still possible to
54− -- achieve nondeterminism by constructing elements that are identical in
55− -- value, unequal according to 'Eq', and nondeterministically equal or
56− -- nonequal by pointer quality. I suspect that it is impossible to make the
57− -- behavior deterministic in this case.
58− superEq a b = a `unsafePtrEq` b || a == b
59− e' = attachWithMaybe (\x x' -> if x' `superEq` x then Nothing else Just x') (current d) (updated d)
60−
61−-- | Create a UniqDynamic without uniqing it on creation. This will be slightly
62−-- faster than uniqDynamic when used with a Dynamic whose values are always (or
63−-- nearly always) different from its previous values; if used with a Dynamic
64−-- whose values do not change frequently, it may be much slower than uniqDynamic
65−alreadyUniqDynamic :: Dynamic t a -> UniqDynamic t a
66−alreadyUniqDynamic = UniqDynamic
67−
68−unsafePtrEq :: a -> a -> Bool
69−unsafePtrEq a b = case a `seq` b `seq` reallyUnsafePtrEquality# a b of
70− 0# -> False
71− _ -> True
72−
73−unsafeJustChanged :: a -> a -> Maybe a
74−unsafeJustChanged old new =
75− if old `unsafePtrEq` new
76− then Nothing
77− else Just new
78−
79−instance Reflex t => Accumulator t (UniqDynamic t) where
80− accumMaybeM f z e = do
81− let f' old change = do
82− mNew <- f old change
83− return $ unsafeJustChanged old =<< mNew
84− d <- accumMaybeMDyn f' z e
85− return $ UniqDynamic d
86− mapAccumMaybeM f z e = do
87− let f' old change = do
88− (mNew, output) <- f old change
89− return (unsafeJustChanged old =<< mNew, output)
90− (d, out) <- mapAccumMaybeMDyn f' z e
91− return (UniqDynamic d, out)
92−
93−instance Reflex t => Functor (UniqDynamic t) where
94− fmap f (UniqDynamic d) = uniqDynamic $ fmap f d
95−
96−instance Reflex t => Applicative (UniqDynamic t) where
97− pure = UniqDynamic . constDyn
98− UniqDynamic a <*> UniqDynamic b = uniqDynamic $ a <*> b
99− _ *> b = b
100− a <* _ = a
101−
102−instance Reflex t => Monad (UniqDynamic t) where
103− UniqDynamic x >>= f = uniqDynamic $ x >>= unUniqDynamic . f
104− _ >> b = b
105− return = pure
src/Reflex/DynamicWriter.hsdeleted−7
@@ -1,7 +0,0 @@
1−module Reflex.DynamicWriter
2− {-# DEPRECATED "Use 'Reflex.DynamicWriter.Class' and 'Reflex.DynamicWrite.Base' instead, or just import 'Reflex'" #-}
3− ( module X
4− ) where
5−
6−import Reflex.DynamicWriter.Base as X
7−import Reflex.DynamicWriter.Class as X
src/Reflex/DynamicWriter/Base.hsdeleted−237
@@ -1,237 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−{-# LANGUAGE StandaloneDeriving #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−module Reflex.DynamicWriter.Base
17− ( DynamicWriterT (..)
18− , runDynamicWriterT
19− , withDynamicWriterT
20− ) where
21−
22−import Control.Monad.Exception
23−import Control.Monad.Identity
24−import Control.Monad.IO.Class
25−import Control.Monad.Primitive
26−import Control.Monad.Reader
27−import Control.Monad.Ref
28−import Control.Monad.State.Strict
29−import Data.Align
30−import Data.Dependent.Map (DMap)
31−import qualified Data.Dependent.Map as DMap
32−import Data.FastMutableIntMap
33−import Data.Functor.Misc
34−import Data.IntMap (IntMap)
35−import qualified Data.IntMap as IntMap
36−import Data.Map (Map)
37−import qualified Data.Map as Map
38−import Data.Semigroup (Semigroup(..))
39−import Data.Some (Some)
40−import Data.These
41−
42−import Reflex.Adjustable.Class
43−import Reflex.Class
44−import Reflex.DynamicWriter.Class
45−import Reflex.EventWriter.Class (EventWriter, tellEvent)
46−import Reflex.Host.Class
47−import qualified Reflex.Patch.MapWithMove as MapWithMove
48−import Reflex.PerformEvent.Class
49−import Reflex.PostBuild.Class
50−import Reflex.Query.Class
51−import Reflex.Requester.Class
52−import Reflex.TriggerEvent.Class
53−
54−instance MonadTrans (DynamicWriterT t w) where
55− lift = DynamicWriterT . lift
56−
57−mapIncrementalMapValues :: (Reflex t, Patch (p v), Patch (p v'), PatchTarget (p v) ~ f v, PatchTarget (p v') ~ f v', Functor p, Functor f) => (v -> v') -> Incremental t (p v) -> Incremental t (p v')
58−mapIncrementalMapValues f = unsafeMapIncremental (fmap f) (fmap f)
59−
60−mergeDynIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Dynamic t v)) -> Incremental t (PatchMap k v)
61−mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
62− where changedValues = fmap (PatchMap . fmap Just) $ mergeMapIncremental $ mapIncrementalMapValues updated a
63− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m
64−
65−mergeIntMapDynIncremental :: Reflex t => Incremental t (PatchIntMap (Dynamic t v)) -> Incremental t (PatchIntMap v)
66−mergeIntMapDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
67− where changedValues = fmap (PatchIntMap . fmap Just) $ mergeIntMapIncremental $ mapIncrementalMapValues updated a
68− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchIntMap m) -> PatchIntMap <$> mapM (mapM (sample . current)) m
69−
70−mergeDynIncrementalWithMove :: forall t k v. (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Dynamic t v)) -> Incremental t (PatchMapWithMove k v)
71−mergeDynIncrementalWithMove a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ alignWith f addedAndRemovedValues changedValues
72− where changedValues = mergeMapIncrementalWithMove $ mapIncrementalMapValues updated a
73− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ fmap unsafePatchMapWithMove . mapM (mapM (sample . current)) . unPatchMapWithMove
74− f :: These (PatchMapWithMove k v) (Map k v) -> PatchMapWithMove k v
75− f x = unsafePatchMapWithMove $
76− let (p, changed) = case x of
77− This p_ -> (unPatchMapWithMove p_, mempty)
78− That c -> (mempty, c)
79− These p_ c -> (unPatchMapWithMove p_, c)
80− (pWithNewVals, noLongerMoved) = flip runState [] $ forM p $ MapWithMove.nodeInfoMapMFrom $ \case
81− MapWithMove.From_Insert v -> return $ MapWithMove.From_Insert v
82− MapWithMove.From_Delete -> return MapWithMove.From_Delete
83− MapWithMove.From_Move k -> case Map.lookup k changed of
84− Nothing -> return $ MapWithMove.From_Move k
85− Just v -> do
86− modify (k:)
87− return $ MapWithMove.From_Insert v
88− noLongerMovedMap = Map.fromList $ fmap (, ()) noLongerMoved
89− in Map.differenceWith (\e _ -> Just $ MapWithMove.nodeInfoSetTo Nothing e) pWithNewVals noLongerMovedMap --TODO: Check if any in the second map are not covered?
90−
91−-- | A basic implementation of 'DynamicWriter'.
92−newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT [Dynamic t w] m a }
93− deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadAsyncException, MonadException) -- The list is kept in reverse order
94−
95−deriving instance MonadHold t m => MonadHold t (DynamicWriterT t w m)
96−deriving instance MonadSample t m => MonadSample t (DynamicWriterT t w m)
97−
98−
99−instance MonadRef m => MonadRef (DynamicWriterT t w m) where
100− type Ref (DynamicWriterT t w m) = Ref m
101− newRef = lift . newRef
102− readRef = lift . readRef
103− writeRef r = lift . writeRef r
104−
105−instance MonadAtomicRef m => MonadAtomicRef (DynamicWriterT t w m) where
106− atomicModifyRef r = lift . atomicModifyRef r
107−
108−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DynamicWriterT t w m) where
109− newEventWithTrigger = lift . newEventWithTrigger
110− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
111−
112−-- | Run a 'DynamicWriterT' action. The dynamic writer output will be provided
113−-- along with the result of the action.
114−runDynamicWriterT :: (MonadFix m, Reflex t, Monoid w) => DynamicWriterT t w m a -> m (a, Dynamic t w)
115−runDynamicWriterT (DynamicWriterT a) = do
116− (result, ws) <- runStateT a []
117− return (result, mconcat $ reverse ws)
118−
119−instance (Monad m, Monoid w, Reflex t) => DynamicWriter t w (DynamicWriterT t w m) where
120− tellDyn w = DynamicWriterT $ modify (w :)
121−
122−instance MonadReader r m => MonadReader r (DynamicWriterT t w m) where
123− ask = lift ask
124− local f (DynamicWriterT a) = DynamicWriterT $ mapStateT (local f) a
125− reader = lift . reader
126−
127−instance PerformEvent t m => PerformEvent t (DynamicWriterT t w m) where
128− type Performable (DynamicWriterT t w m) = Performable m
129− performEvent_ = lift . performEvent_
130− performEvent = lift . performEvent
131−
132−instance TriggerEvent t m => TriggerEvent t (DynamicWriterT t w m) where
133− newTriggerEvent = lift newTriggerEvent
134− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
135− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
136−
137−instance PostBuild t m => PostBuild t (DynamicWriterT t w m) where
138− getPostBuild = lift getPostBuild
139−
140−instance MonadState s m => MonadState s (DynamicWriterT t w m) where
141− get = lift get
142− put = lift . put
143−
144−instance PrimMonad m => PrimMonad (DynamicWriterT t w m) where
145− type PrimState (DynamicWriterT t w m) = PrimState m
146− primitive = lift . primitive
147−
148−newtype DynamicWriterTLoweredResult t w v a = DynamicWriterTLoweredResult (v a, Dynamic t w)
149−
150−-- | When the execution of a 'DynamicWriterT' action is adjusted using
151−-- 'Adjustable', the 'Dynamic' output of that action will also be updated to
152−-- match.
153−instance (Adjustable t m, MonadFix m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (DynamicWriterT t w m) where
154− runWithReplace a0 a' = do
155− (result0, result') <- lift $ runWithReplace (runDynamicWriterT a0) $ runDynamicWriterT <$> a'
156− tellDyn . join =<< holdDyn (snd result0) (snd <$> result')
157− return (fst result0, fst <$> result')
158− traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust mergeIntMapDynIncremental
159− traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap weakenPatchDMapWith mergeDynIncremental
160− traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeDynIncrementalWithMove
161−
162−traverseDMapWithKeyWithAdjustImpl :: forall t w k v' p p' v m. (PatchTarget (p' (Some k) (Dynamic t w)) ~ Map (Some k) (Dynamic t w), PatchTarget (p' (Some k) w) ~ Map (Some k) w, Patch (p' (Some k) w), Patch (p' (Some k) (Dynamic t w)), MonadFix m, Monoid w, Reflex t, MonadHold t m)
163− => ( (forall a. k a -> v a -> m (DynamicWriterTLoweredResult t w v' a))
164− -> DMap k v
165− -> Event t (p k v)
166− -> m (DMap k (DynamicWriterTLoweredResult t w v'), Event t (p k (DynamicWriterTLoweredResult t w v')))
167− )
168− -> ((forall a. DynamicWriterTLoweredResult t w v' a -> v' a) -> p k (DynamicWriterTLoweredResult t w v') -> p k v')
169− -> ((forall a. DynamicWriterTLoweredResult t w v' a -> Dynamic t w) -> p k (DynamicWriterTLoweredResult t w v') -> p' (Some k) (Dynamic t w))
170− -> (Incremental t (p' (Some k) (Dynamic t w)) -> Incremental t (p' (Some k) w))
171− -> (forall a. k a -> v a -> DynamicWriterT t w m (v' a))
172− -> DMap k v
173− -> Event t (p k v)
174− -> DynamicWriterT t w m (DMap k v', Event t (p k v'))
175−traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith mergeMyDynIncremental f (dm0 :: DMap k v) dm' = do
176− (result0, result') <- lift $ base (\k v -> fmap DynamicWriterTLoweredResult $ runDynamicWriterT $ f k v) dm0 dm'
177− let getValue (DynamicWriterTLoweredResult (v, _)) = v
178− getWritten (DynamicWriterTLoweredResult (_, w)) = w
179− liftedResult0 = DMap.map getValue result0
180− liftedResult' = ffor result' $ mapPatch getValue
181− liftedWritten0 :: Map (Some k) (Dynamic t w)
182− liftedWritten0 = weakenDMapWith getWritten result0
183− liftedWritten' = ffor result' $ weakenPatchWith getWritten
184− --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
185− i <- holdIncremental liftedWritten0 liftedWritten'
186− tellDyn $ fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
187− return (liftedResult0, liftedResult')
188−
189−traverseIntMapWithKeyWithAdjustImpl :: forall t w v' p p' v m. (PatchTarget (p' (Dynamic t w)) ~ IntMap (Dynamic t w), PatchTarget (p' w) ~ IntMap w, Patch (p' w), Patch (p' (Dynamic t w)), MonadFix m, Monoid w, Reflex t, MonadHold t m, Functor p, p ~ p')
190− => ( (IntMap.Key -> v -> m (v', Dynamic t w))
191− -> IntMap v
192− -> Event t (p v)
193− -> m (IntMap (v', Dynamic t w), Event t (p (v', Dynamic t w)))
194− )
195− -> (Incremental t (p' (Dynamic t w)) -> Incremental t (p' w))
196− -> (IntMap.Key -> v -> DynamicWriterT t w m v')
197− -> IntMap v
198− -> Event t (p v)
199− -> DynamicWriterT t w m (IntMap v', Event t (p v'))
200−traverseIntMapWithKeyWithAdjustImpl base mergeMyDynIncremental f (dm0 :: IntMap v) dm' = do
201− (result0, result') <- lift $ base (\k v -> runDynamicWriterT $ f k v) dm0 dm'
202− let liftedResult0 = fmap fst result0
203− liftedResult' = fmap (fmap fst) result'
204− liftedWritten0 :: IntMap (Dynamic t w)
205− liftedWritten0 = fmap snd result0
206− liftedWritten' = fmap (fmap snd) result'
207− --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
208− i <- holdIncremental liftedWritten0 liftedWritten'
209− tellDyn $ fmap (mconcat . IntMap.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
210− return (liftedResult0, liftedResult')
211−
212−-- | Map a function over the output of a 'DynamicWriterT'.
213−withDynamicWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m, MonadFix m)
214− => (w -> w')
215− -> DynamicWriterT t w m a
216− -> DynamicWriterT t w' m a
217−withDynamicWriterT f dw = do
218− (r, d) <- lift $ do
219− (r, d) <- runDynamicWriterT dw
220− let d' = fmap f d
221− return (r, d')
222− tellDyn d
223− return r
224−
225−instance Requester t m => Requester t (DynamicWriterT t w m) where
226− type Request (DynamicWriterT t w m) = Request m
227− type Response (DynamicWriterT t w m) = Response m
228− requesting = lift . requesting
229− requesting_ = lift . requesting_
230−
231−instance (MonadQuery t q m, Monad m) => MonadQuery t q (DynamicWriterT t w m) where
232− tellQueryIncremental = lift . tellQueryIncremental
233− askQueryResult = lift askQueryResult
234− queryIncremental = lift . queryIncremental
235−
236−instance EventWriter t w m => EventWriter t w (DynamicWriterT t v m) where
237− tellEvent = lift . tellEvent
src/Reflex/DynamicWriter/Class.hsdeleted−30
@@ -1,30 +0,0 @@
1−-- | This module defines the 'DynamicWriter' class.
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE UndecidableInstances #-}
8−#ifdef USE_REFLEX_OPTIMIZER
9−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10−#endif
11−module Reflex.DynamicWriter.Class
12− ( MonadDynamicWriter
13− , DynamicWriter(..)
14− ) where
15−
16−import Control.Monad.Reader (ReaderT, lift)
17−import Reflex.Class (Dynamic)
18−
19−{-# DEPRECATED MonadDynamicWriter "Use 'DynamicWriter' instead" #-}
20−-- | Type synonym for 'DynamicWriter'
21−type MonadDynamicWriter = DynamicWriter
22−
23−-- | 'MonadDynamicWriter' efficiently collects 'Dynamic' values using 'tellDyn'
24−-- and combines them monoidally to provide a 'Dynamic' result.
25−class (Monad m, Monoid w) => DynamicWriter t w m | m -> t w where
26− tellDyn :: Dynamic t w -> m ()
27−
28−instance DynamicWriter t w m => DynamicWriter t w (ReaderT r m) where
29− tellDyn = lift . tellDyn
30−
src/Reflex/EventWriter.hsdeleted−7
@@ -1,7 +0,0 @@
1−module Reflex.EventWriter
2− {-# DEPRECATED "Use 'Reflex.EventWriter.Class' and 'Reflex.EventWriter.Base' instead, or just import 'Reflex'" #-}
3− ( module X
4− ) where
5−
6−import Reflex.EventWriter.Base as X
7−import Reflex.EventWriter.Class as X
src/Reflex/EventWriter/Base.hsdeleted−306
@@ -1,306 +0,0 @@
1−-- | This module provides 'EventWriterT', the standard implementation of
2−-- 'EventWriter'.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE ExistentialQuantification #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE Rank2Types #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE TypeOperators #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−module Reflex.EventWriter.Base
17− ( EventWriterT (..)
18− , runEventWriterT
19− , runWithReplaceEventWriterTWith
20− , sequenceDMapWithAdjustEventWriterTWith
21− , mapEventWriterT
22− , withEventWriterT
23− ) where
24−
25−import Reflex.Adjustable.Class
26−import Reflex.Class
27−import Reflex.EventWriter.Class (EventWriter, tellEvent)
28−import Reflex.DynamicWriter.Class (DynamicWriter, tellDyn)
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.PostBuild.Class
32−import Reflex.Query.Class
33−import Reflex.Requester.Class
34−import Reflex.TriggerEvent.Class
35−
36−import Control.Monad.Exception
37−import Control.Monad.Identity
38−import Control.Monad.Primitive
39−import Control.Monad.Reader
40−import Control.Monad.Ref
41−import Control.Monad.State.Strict
42−import Data.Dependent.Map (DMap, DSum (..))
43−import qualified Data.Dependent.Map as DMap
44−import Data.Functor.Compose
45−import Data.Functor.Misc
46−import Data.GADT.Compare (GCompare (..), GEq (..), GOrdering (..))
47−import Data.IntMap.Strict (IntMap)
48−import qualified Data.IntMap.Strict as IntMap
49−import Data.List.NonEmpty (NonEmpty (..))
50−import Data.Map (Map)
51−import qualified Data.Map as Map
52−import Data.Semigroup
53−import Data.Some (Some)
54−import Data.Tuple
55−import Data.Type.Equality hiding (apply)
56−
57−import Unsafe.Coerce
58−
59−{-# DEPRECATED TellId "Do not construct this directly; use tellId instead" #-}
60−newtype TellId w x
61− = TellId Int -- ^ WARNING: Do not construct this directly; use 'tellId' instead
62− deriving (Show, Eq, Ord, Enum)
63−
64−tellId :: Int -> TellId w w
65−tellId = TellId
66−{-# INLINE tellId #-}
67−
68−tellIdRefl :: TellId w x -> w :~: x
69−tellIdRefl _ = unsafeCoerce Refl
70−
71−withTellIdRefl :: TellId w x -> (w ~ x => r) -> r
72−withTellIdRefl tid r = case tellIdRefl tid of
73− Refl -> r
74−
75−instance GEq (TellId w) where
76− a `geq` b =
77− withTellIdRefl a $
78− withTellIdRefl b $
79− if a == b
80− then Just Refl
81− else Nothing
82−
83−instance GCompare (TellId w) where
84− a `gcompare` b =
85− withTellIdRefl a $
86− withTellIdRefl b $
87− case a `compare` b of
88− LT -> GLT
89− EQ -> GEQ
90− GT -> GGT
91−
92−data EventWriterState t w = EventWriterState
93− { _eventWriterState_nextId :: {-# UNPACK #-} !Int -- Always negative (and decreasing over time)
94− , _eventWriterState_told :: ![DSum (TellId w) (Event t)] -- In increasing order
95− }
96−
97−-- | A basic implementation of 'EventWriter'.
98−newtype EventWriterT t w m a = EventWriterT { unEventWriterT :: StateT (EventWriterState t w) m a }
99− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
100−
101−-- | Run a 'EventWriterT' action.
102−runEventWriterT :: forall t m w a. (Reflex t, Monad m, Semigroup w) => EventWriterT t w m a -> m (a, Event t w)
103−runEventWriterT (EventWriterT a) = do
104− (result, requests) <- runStateT a $ EventWriterState (-1) []
105− let combineResults :: DMap (TellId w) Identity -> w
106− combineResults = sconcat
107− . (\(h : t) -> h :| t) -- Unconditional; 'merge' guarantees that it will only fire with non-empty DMaps
108− . DMap.foldlWithKey (\vs tid (Identity v) -> withTellIdRefl tid $ v : vs) [] -- This is where we finally reverse the DMap to get things in the correct order
109− return (result, fmap combineResults $ merge $ DMap.fromDistinctAscList $ _eventWriterState_told requests) --TODO: We can probably make this fromDistinctAscList more efficient by knowing the length in advance, but this will require exposing internals of DMap; also converting it to use a strict list might help
110−
111−instance (Reflex t, Monad m, Semigroup w) => EventWriter t w (EventWriterT t w m) where
112− tellEvent w = EventWriterT $ modify $ \old ->
113− let myId = _eventWriterState_nextId old
114− in EventWriterState
115− { _eventWriterState_nextId = pred myId
116− , _eventWriterState_told = (tellId myId :=> w) : _eventWriterState_told old
117− }
118−
119−instance MonadTrans (EventWriterT t w) where
120− lift = EventWriterT . lift
121−
122−instance MonadSample t m => MonadSample t (EventWriterT t w m) where
123− sample = lift . sample
124−
125−instance MonadHold t m => MonadHold t (EventWriterT t w m) where
126− {-# INLINABLE hold #-}
127− hold v0 = lift . hold v0
128− {-# INLINABLE holdDyn #-}
129− holdDyn v0 = lift . holdDyn v0
130− {-# INLINABLE holdIncremental #-}
131− holdIncremental v0 = lift . holdIncremental v0
132− {-# INLINABLE buildDynamic #-}
133− buildDynamic a0 = lift . buildDynamic a0
134− {-# INLINABLE headE #-}
135− headE = lift . headE
136−
137−instance (Reflex t, Adjustable t m, MonadHold t m, Semigroup w) => Adjustable t (EventWriterT t w m) where
138− runWithReplace = runWithReplaceEventWriterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
139− traverseIntMapWithKeyWithAdjust = sequenceIntMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') mergeIntIncremental coincidencePatchIntMap
140− traverseDMapWithKeyWithAdjust = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith mergeMapIncremental coincidencePatchMap
141− traverseDMapWithKeyWithAdjustWithMove = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeMapIncrementalWithMove coincidencePatchMapWithMove
142−
143−instance Requester t m => Requester t (EventWriterT t w m) where
144− type Request (EventWriterT t w m) = Request m
145− type Response (EventWriterT t w m) = Response m
146− requesting = lift . requesting
147− requesting_ = lift . requesting_
148−
149−-- | Given a function like 'runWithReplace' for the underlying monad, implement
150−-- 'runWithReplace' for 'EventWriterT'. This is necessary when the underlying
151−-- monad doesn't have a 'Adjustable' instance or to override the default
152−-- 'Adjustable' behavior.
153−runWithReplaceEventWriterTWith :: forall m t w a b. (Reflex t, MonadHold t m, Semigroup w)
154− => (forall a' b'. m a' -> Event t (m b') -> EventWriterT t w m (a', Event t b'))
155− -> EventWriterT t w m a
156− -> Event t (EventWriterT t w m b)
157− -> EventWriterT t w m (a, Event t b)
158−runWithReplaceEventWriterTWith f a0 a' = do
159− (result0, result') <- f (runEventWriterT a0) $ fmapCheap runEventWriterT a'
160− tellEvent =<< switchHoldPromptOnly (snd result0) (fmapCheap snd result')
161− return (fst result0, fmapCheap fst result')
162−
163−-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceIntMapWithAdjust'.
164−sequenceIntMapWithAdjustEventWriterTWith
165− :: forall t m p w v v'
166− . ( Reflex t
167− , MonadHold t m
168− , Semigroup w
169− , Functor p
170− , Patch (p (Event t w))
171− , PatchTarget (p (Event t w)) ~ IntMap (Event t w)
172− , Patch (p w)
173− , PatchTarget (p w) ~ IntMap w
174− )
175− => ( (IntMap.Key -> v -> m (Event t w, v'))
176− -> IntMap v
177− -> Event t (p v)
178− -> EventWriterT t w m (IntMap (Event t w, v'), Event t (p (Event t w, v')))
179− )
180− -> (Incremental t (p (Event t w)) -> Event t (PatchTarget (p w)))
181− -> (Event t (p (Event t w)) -> Event t (p w))
182− -> (IntMap.Key -> v -> EventWriterT t w m v')
183− -> IntMap v
184− -> Event t (p v)
185− -> EventWriterT t w m (IntMap v', Event t (p v'))
186−sequenceIntMapWithAdjustEventWriterTWith base mergePatchIncremental coincidencePatch f dm0 dm' = do
187− let f' :: IntMap.Key -> v -> m (Event t w, v')
188− f' k v = swap <$> runEventWriterT (f k v)
189− (children0, children') <- base f' dm0 dm'
190− let result0 = fmap snd children0
191− result' = fmapCheap (fmap snd) children'
192− requests0 :: IntMap (Event t w)
193− requests0 = fmap fst children0
194− requests' :: Event t (p (Event t w))
195− requests' = fmapCheap (fmap fst) children'
196− e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
197− tellEvent $ fforMaybeCheap e $ \m ->
198− case IntMap.elems m of
199− [] -> Nothing
200− h : t -> Just $ sconcat $ h :| t
201− return (result0, result')
202−
203−-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceDMapWithAdjust'.
204−sequenceDMapWithAdjustEventWriterTWith
205− :: forall t m p p' w k v v'
206− . ( Reflex t
207− , MonadHold t m
208− , Semigroup w
209− , Patch (p' (Some k) (Event t w))
210− , PatchTarget (p' (Some k) (Event t w)) ~ Map (Some k) (Event t w)
211− , GCompare k
212− , Patch (p' (Some k) w)
213− , PatchTarget (p' (Some k) w) ~ Map (Some k) w
214− )
215− => ( (forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a))
216− -> DMap k v
217− -> Event t (p k v)
218− -> EventWriterT t w m (DMap k (Compose ((,) (Event t w)) v'), Event t (p k (Compose ((,) (Event t w)) v')))
219− )
220− -> ((forall a. Compose ((,) (Event t w)) v' a -> v' a) -> p k (Compose ((,) (Event t w)) v') -> p k v')
221− -> ((forall a. Compose ((,) (Event t w)) v' a -> Event t w) -> p k (Compose ((,) (Event t w)) v') -> p' (Some k) (Event t w))
222− -> (Incremental t (p' (Some k) (Event t w)) -> Event t (PatchTarget (p' (Some k) w)))
223− -> (Event t (p' (Some k) (Event t w)) -> Event t (p' (Some k) w))
224− -> (forall a. k a -> v a -> EventWriterT t w m (v' a))
225− -> DMap k v
226− -> Event t (p k v)
227− -> EventWriterT t w m (DMap k v', Event t (p k v'))
228−sequenceDMapWithAdjustEventWriterTWith base mapPatch weakenPatchWith mergePatchIncremental coincidencePatch f dm0 dm' = do
229− let f' :: forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a)
230− f' k v = Compose . swap <$> runEventWriterT (f k v)
231− (children0, children') <- base f' dm0 dm'
232− let result0 = DMap.map (snd . getCompose) children0
233− result' = fforCheap children' $ mapPatch $ snd . getCompose
234− requests0 :: Map (Some k) (Event t w)
235− requests0 = weakenDMapWith (fst . getCompose) children0
236− requests' :: Event t (p' (Some k) (Event t w))
237− requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
238− e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
239− tellEvent $ fforMaybeCheap e $ \m ->
240− case Map.elems m of
241− [] -> Nothing
242− h : t -> Just $ sconcat $ h :| t
243− return (result0, result')
244−
245−instance PerformEvent t m => PerformEvent t (EventWriterT t w m) where
246− type Performable (EventWriterT t w m) = Performable m
247− performEvent_ = lift . performEvent_
248− performEvent = lift . performEvent
249−
250−instance PostBuild t m => PostBuild t (EventWriterT t w m) where
251− getPostBuild = lift getPostBuild
252−
253−instance TriggerEvent t m => TriggerEvent t (EventWriterT t w m) where
254− newTriggerEvent = lift newTriggerEvent
255− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
256− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
257−
258−instance MonadReader r m => MonadReader r (EventWriterT t w m) where
259− ask = lift ask
260− local f (EventWriterT a) = EventWriterT $ mapStateT (local f) a
261− reader = lift . reader
262−
263−instance MonadRef m => MonadRef (EventWriterT t w m) where
264− type Ref (EventWriterT t w m) = Ref m
265− newRef = lift . newRef
266− readRef = lift . readRef
267− writeRef r = lift . writeRef r
268−
269−instance MonadAtomicRef m => MonadAtomicRef (EventWriterT t w m) where
270− atomicModifyRef r = lift . atomicModifyRef r
271−
272−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (EventWriterT t w m) where
273− newEventWithTrigger = lift . newEventWithTrigger
274− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
275−
276−instance (MonadQuery t q m, Monad m) => MonadQuery t q (EventWriterT t w m) where
277− tellQueryIncremental = lift . tellQueryIncremental
278− askQueryResult = lift askQueryResult
279− queryIncremental = lift . queryIncremental
280−
281−instance DynamicWriter t w m => DynamicWriter t w (EventWriterT t v m) where
282− tellDyn = lift . tellDyn
283−
284−instance PrimMonad m => PrimMonad (EventWriterT t w m) where
285− type PrimState (EventWriterT t w m) = PrimState m
286− primitive = lift . primitive
287−
288−-- | Map a function over the output of a 'EventWriterT'.
289−withEventWriterT :: (Semigroup w, Semigroup w', Reflex t, MonadHold t m)
290− => (w -> w')
291− -> EventWriterT t w m a
292− -> EventWriterT t w' m a
293−withEventWriterT f ew = do
294− (r, e) <- lift $ do
295− (r, e) <- runEventWriterT ew
296− let e' = fmap f e
297− return (r, e')
298− tellEvent e
299− return r
300−
301−-- | Change the monad underlying an EventWriterT
302−mapEventWriterT
303− :: (forall x. m x -> n x)
304− -> EventWriterT t w m a
305− -> EventWriterT t w n a
306−mapEventWriterT f (EventWriterT a) = EventWriterT $ mapStateT f a
src/Reflex/EventWriter/Class.hsdeleted−27
@@ -1,27 +0,0 @@
1−-- | This module defines the 'EventWriter' class.
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE UndecidableInstances #-}
7−#ifdef USE_REFLEX_OPTIMIZER
8−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
9−#endif
10−module Reflex.EventWriter.Class
11− ( EventWriter (..)
12− ) where
13−
14−import Control.Monad.Reader (ReaderT, lift)
15−import Data.Semigroup (Semigroup)
16−
17−import Reflex.Class (Event)
18−
19−
20−-- | 'EventWriter' efficiently collects 'Event' values using 'tellEvent'
21−-- and combines them via 'Semigroup' to provide an 'Event' result.
22−class (Monad m, Semigroup w) => EventWriter t w m | m -> t w where
23− tellEvent :: Event t w -> m ()
24−
25−
26−instance EventWriter t w m => EventWriter t w (ReaderT r m) where
27− tellEvent = lift . tellEvent
src/Reflex/FastWeak.hsdeleted−200
@@ -1,200 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−#if GHCJS_FAST_WEAK
5−{-# LANGUAGE ForeignFunctionInterface #-}
6−{-# LANGUAGE JavaScriptFFI #-}
7−#endif
8−
9−-- |
10−-- Module:
11−-- Reflex.FastWeak
12−-- Description:
13−-- 'FastWeak' is a weak pointer to some value, and 'FastWeakTicket' ensures the value
14−-- referred to by a 'FastWeak' stays live while the ticket is held (live).
15−--
16−-- On GHC or GHCJS when not built with the @fast-weak@ cabal flag, 'FastWeak' is a wrapper
17−-- around the simple version of 'System.Mem.Weak.Weak' where the key and value are the same.
18−--
19−-- On GHCJS when built with the @fast-weak@ cabal flag, 'FastWeak' is implemented directly
20−-- in JS using @h$FastWeak@ and @h$FastWeakTicket@ which are a nonstandard part of the GHCJS RTS.
21−module Reflex.FastWeak
22− ( FastWeakTicket
23− , FastWeak
24− , mkFastWeakTicket
25− , getFastWeakTicketValue
26− , getFastWeakTicketWeak
27− , getFastWeakValue
28− , getFastWeakTicket
29− , emptyFastWeak
30−#ifdef GHCJS_FAST_WEAK
31− --TODO: Move these elsewhere
32− , unsafeFromRawJSVal
33− , unsafeToRawJSVal
34− , js_isNull
35−#endif
36− ) where
37−
38−import GHC.Exts (Any)
39−import Unsafe.Coerce
40−
41−#ifdef GHCJS_FAST_WEAK
42−import GHCJS.Types
43−#else
44−import Control.Exception (evaluate)
45−import System.IO.Unsafe
46−import System.Mem.Weak
47−#endif
48−
49−
50−#ifdef GHCJS_FAST_WEAK
51−-- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'
52−-- can be used to get the referred to value without fear of @Nothing,
53−-- and 'getFastWeakTicketWeak' can be used to get the weak version.
54−--
55−-- Implemented by way of special support in the GHCJS RTS, @h$FastWeakTicket@.
56−newtype FastWeakTicket a = FastWeakTicket JSVal
57−
58−-- | A reference to some value which can be garbage collected if there are only
59−-- weak references to the value left.
60−--
61−-- 'getFastWeakValue' can be used to try and obtain a strong reference to the value.
62−--
63−-- The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using
64−-- 'getFastWeakTicket' if the value hasn't been collected yet.
65−--
66−-- Implemented by way of special support in the GHCJS RTS, @h$FastWeak@.
67−newtype FastWeak a = FastWeak JSVal
68−
69−-- Just designed to mirror JSVal, so that we can unsafeCoerce between the two
70−data Val a = Val { unVal :: a }
71−
72−-- | Coerce a JSVal that represents the heap object of a value of type @a@ into a value of type @a@
73−unsafeFromRawJSVal :: JSVal -> a
74−unsafeFromRawJSVal v = unVal (unsafeCoerce v)
75−
76−-- | Coerce a heap object of type @a@ into a 'JSVal' which represents that object.
77−unsafeToRawJSVal :: a -> JSVal
78−unsafeToRawJSVal v = unsafeCoerce (Val v)
79−#else
80−-- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'
81−-- can be used to get the referred to value without fear of @Nothing@,
82−-- and 'getFastWeakTicketWeak' can be used to get the weak version.
83−data FastWeakTicket a = FastWeakTicket
84− { _fastWeakTicket_val :: !a
85− , _fastWeakTicket_weak :: {-# UNPACK #-} !(Weak a)
86− }
87−
88−-- | A reference to some value which can be garbage collected if there are only weak references to the value left.
89−--
90−-- 'getFastWeakValue' can be used to try and obtain a strong reference to the value.
91−--
92−-- The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using 'getFastWeakTicket'
93−-- if the value hasn't been collected yet.
94−--
95−-- Synonymous with 'Weak'.
96−type FastWeak a = Weak a
97−#endif
98−
99−-- | Return the @a@ kept alive by the given 'FastWeakTicket'.
100−--
101−-- This needs to be in IO so we know that we've relinquished the ticket.
102−getFastWeakTicketValue :: FastWeakTicket a -> IO a
103−#ifdef GHCJS_FAST_WEAK
104−getFastWeakTicketValue t = do
105− v <- js_ticketVal t
106− return $ unsafeFromRawJSVal v
107−
108−foreign import javascript unsafe "$r = $1.val;" js_ticketVal :: FastWeakTicket a -> IO JSVal
109−#else
110−getFastWeakTicketValue = return . _fastWeakTicket_val
111−#endif
112−
113−-- | Get the value referred to by a 'FastWeak' if it hasn't yet been collected,
114−-- or @Nothing@ if it has been collected.
115−getFastWeakValue :: FastWeak a -> IO (Maybe a)
116−#ifdef GHCJS_FAST_WEAK
117−getFastWeakValue w = do
118− r <- js_weakVal w
119− case js_isNull r of
120− True -> return Nothing
121− False -> return $ Just $ unsafeFromRawJSVal r
122−
123−foreign import javascript unsafe "$1 === null" js_isNull :: JSVal -> Bool
124−
125−foreign import javascript unsafe "$r = ($1.ticket === null) ? null : $1.ticket.val;" js_weakVal :: FastWeak a -> IO JSVal
126−#else
127−getFastWeakValue = deRefWeak
128−#endif
129−
130−-- | Try to create a 'FastWeakTicket' for the given 'FastWeak' which will ensure the value referred
131−-- remains alive. Returns @Just@ if the value hasn't been collected
132−-- and a ticket can therefore be obtained, @Nothing@ if it's been collected.
133−getFastWeakTicket :: forall a. FastWeak a -> IO (Maybe (FastWeakTicket a))
134−#ifdef GHCJS_FAST_WEAK
135−getFastWeakTicket w = do
136− r <- js_weakTicket w
137− case js_isNull r of
138− True -> return Nothing
139− False -> return $ Just $ FastWeakTicket r
140−
141−foreign import javascript unsafe "$r = $1.ticket;" js_weakTicket :: FastWeak a -> IO JSVal
142−#else
143−getFastWeakTicket w = do
144− deRefWeak w >>= \case
145− Nothing -> return Nothing
146− Just v -> return $ Just $ FastWeakTicket
147− { _fastWeakTicket_val = v
148− , _fastWeakTicket_weak = w
149− }
150−#endif
151−
152−-- | Create a 'FastWeakTicket' directly from a value, creating a 'FastWeak' in the process
153−-- which can be obtained with 'getFastWeakTicketValue'.
154−mkFastWeakTicket :: a -> IO (FastWeakTicket a)
155−-- I think it's fine if this is lazy - it'll retain the 'a', but so would the output; we just need to make sure it's forced before we start relying on the
156−-- associated FastWeak to actually be weak
157−#ifdef GHCJS_FAST_WEAK
158−mkFastWeakTicket v = js_fastWeakTicket (unsafeToRawJSVal v)
159−
160−foreign import javascript unsafe "$r = new h$FastWeakTicket($1);" js_fastWeakTicket :: JSVal -> IO (FastWeakTicket a)
161−#else
162−mkFastWeakTicket v = do
163− v' <- evaluate v
164− w <- mkWeakPtr v' Nothing
165− return $ FastWeakTicket
166− { _fastWeakTicket_val = v'
167− , _fastWeakTicket_weak = w
168− }
169−#endif
170−
171−-- | Demote a 'FastWeakTicket'; which ensures the value is alive, to a 'FastWeak' which doesn't.
172−-- Note that unless the ticket for the same 'FastWeak' is held in some other way
173−-- the value might be collected immediately.
174−getFastWeakTicketWeak :: FastWeakTicket a -> IO (FastWeak a)
175−-- Needs IO so that it can force the value - otherwise, could end up with a reference to the Ticket, which would retain the value
176−#ifdef GHCJS_FAST_WEAK
177−foreign import javascript unsafe "$r = $1.weak;" getFastWeakTicketWeak' :: FastWeakTicket a -> IO (FastWeak a)
178−{-# INLINE getFastWeakTicketWeak #-}
179−getFastWeakTicketWeak = getFastWeakTicketWeak'
180−#else
181−getFastWeakTicketWeak = return . _fastWeakTicket_weak
182−#endif
183−
184−-- | A weak reference that is always empty
185−emptyFastWeak :: FastWeak a
186−emptyFastWeak = unsafeCoerce w
187− where w :: FastWeak Any
188−#ifdef GHCJS_FAST_WEAK
189− w = js_emptyWeak
190−#else
191− w = unsafePerformIO $ do
192− w' <- mkWeakPtr undefined Nothing
193− finalize w'
194− return w'
195−#endif
196−{-# NOINLINE emptyFastWeak #-}
197−
198−#ifdef GHCJS_FAST_WEAK
199−foreign import javascript unsafe "$r = new h$FastWeak(null);" js_emptyWeak :: FastWeak Any
200−#endif
src/Reflex/FunctorMaybe.hsdeleted−47
@@ -1,47 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−#if MIN_VERSION_base(4,9,0)
3−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4−{-# LANGUAGE StandaloneDeriving #-}
5−#endif
6−
7−-- |
8−-- Module:
9−-- Reflex.FunctorMaybe
10−-- Description:
11−-- This module defines the FunctorMaybe class, which extends Functors with the
12−-- ability to delete values.
13−module Reflex.FunctorMaybe
14− ( FunctorMaybe (..)
15− ) where
16−
17−import Data.IntMap (IntMap)
18−import Data.Map (Map)
19−#if MIN_VERSION_base(4,9,0)
20−import Data.Semigroup (Option(..))
21−#endif
22−import Data.Witherable
23−
24−--TODO: See if there's a better class in the standard libraries already
25−
26−-- | A class for values that combines filtering and mapping using 'Maybe'.
27−-- Morally, @'FunctorMaybe' ~ KleisliFunctor 'Maybe'@.
28−{-# DEPRECATED FunctorMaybe "Use 'Filterable' from Data.Witherable instead" #-}
29−class FunctorMaybe f where
30− -- | Combined mapping and filtering function.
31− fmapMaybe :: (a -> Maybe b) -> f a -> f b
32−
33−instance FunctorMaybe Maybe where
34− fmapMaybe = mapMaybe
35−
36−#if MIN_VERSION_base(4,9,0)
37−deriving instance FunctorMaybe Option
38−#endif
39−
40−instance FunctorMaybe [] where
41− fmapMaybe = mapMaybe
42−
43−instance FunctorMaybe (Map k) where
44− fmapMaybe = mapMaybe
45−
46−instance FunctorMaybe IntMap where
47− fmapMaybe = mapMaybe
src/Reflex/Host/Class.hsdeleted−280
@@ -1,280 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RoleAnnotations #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−-- | This module provides the interface for hosting 'Reflex' engines. This
17−-- should only be necessary if you're writing a binding or some other library
18−-- that provides a core event loop.
19−module Reflex.Host.Class
20− ( ReflexHost (..)
21− , MonadSubscribeEvent (..)
22− , MonadReadEvent (..)
23− , MonadReflexCreateTrigger (..)
24− , MonadReflexHost (..)
25− , fireEvents
26− , newEventWithTriggerRef
27− , fireEventRef
28− , fireEventRefAndRead
29− ) where
30−
31−import Reflex.Class
32−
33−import Control.Monad.Fix
34−import Control.Monad.Identity
35−import Control.Monad.Ref
36−import Control.Monad.Trans
37−import Control.Monad.Trans.Cont (ContT)
38−import Control.Monad.Trans.Except (ExceptT)
39−import Control.Monad.Trans.Reader (ReaderT)
40−import Control.Monad.Trans.RWS (RWST)
41−import Control.Monad.Trans.State (StateT)
42−import qualified Control.Monad.Trans.State.Strict as Strict
43−import Control.Monad.Trans.Writer (WriterT)
44−import Data.Dependent.Sum (DSum (..))
45−import Data.GADT.Compare
46−
47−-- | Framework implementation support class for the reflex implementation
48−-- represented by @t@.
49−class ( Reflex t
50− , MonadReflexCreateTrigger t (HostFrame t)
51− , MonadSample t (HostFrame t)
52− , MonadHold t (HostFrame t)
53− , MonadFix (HostFrame t)
54− , MonadSubscribeEvent t (HostFrame t)
55− ) => ReflexHost t where
56− type EventTrigger t :: * -> *
57− type EventHandle t :: * -> *
58− type HostFrame t :: * -> *
59−
60−-- | Monad in which Events can be 'subscribed'. This forces all underlying
61−-- event sources to be initialized, so that the event will fire whenever it
62−-- ought to. Events must be subscribed before they are read using readEvent
63−class (Reflex t, Monad m) => MonadSubscribeEvent t m | m -> t where
64− -- | Subscribe to an event and set it up if needed.
65− --
66− -- This function will create a new 'EventHandle' from an 'Event'. This handle
67− -- may then be used via 'readEvent' in the read callback of
68− -- 'fireEventsAndRead'.
69− --
70− -- If the event wasn't subscribed to before (either manually or through a
71− -- dependent event or behavior) then this function will cause the event and
72− -- all dependencies of this event to be set up. For example, if the event was
73− -- created by 'newEventWithTrigger', then it's callback will be executed.
74− --
75− -- It's safe to call this function multiple times.
76− subscribeEvent :: Event t a -> m (EventHandle t a)
77−
78−-- | Monad that allows to read events' values.
79−class (ReflexHost t, Applicative m, Monad m) => MonadReadEvent t m | m -> t where
80− -- | Read the value of an 'Event' from an 'EventHandle' (created by calling
81− -- 'subscribeEvent').
82− --
83− -- After event propagation is done, all events can be in two states: either
84− -- they are firing with some value or they are not firing. In the former
85− -- case, this function returns @Just act@, where @act@ in an action to read
86− -- the current value of the event. In the latter case, the function returns
87− -- @Nothing@.
88− --
89− -- This function is normally used in the calllback for 'fireEventsAndRead'.
90− readEvent :: EventHandle t a -> m (Maybe (m a))
91−
92−-- | A monad where new events feed from external sources can be created.
93−class (Applicative m, Monad m) => MonadReflexCreateTrigger t m | m -> t where
94− -- | Creates a root 'Event' (one that is not based on any other event).
95− --
96− -- When a subscriber first subscribes to an event (building another event that
97− -- depends on the subscription) the given callback function is run and passed
98− -- a trigger. The callback function can then set up the event source in IO.
99− -- After this is done, the callback function must return an accompanying
100− -- teardown action.
101− --
102− -- Any time between setup and teardown the trigger can be used to fire the
103− -- event, by passing it to 'fireEventsAndRead'.
104− --
105− -- Note: An event may be set up multiple times. So after the teardown action
106− -- is executed, the event may still be set up again in the future.
107− newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)
108− newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k)
109−
110−-- | 'MonadReflexHost' designates monads that can run reflex frames.
111−class ( ReflexHost t
112− , MonadReflexCreateTrigger t m
113− , MonadSubscribeEvent t m
114− , MonadReadEvent t (ReadPhase m)
115− , MonadSample t (ReadPhase m)
116− , MonadHold t (ReadPhase m)
117− ) => MonadReflexHost t m | m -> t where
118− type ReadPhase m :: * -> *
119− -- | Propagate some events firings and read the values of events afterwards.
120− --
121− -- This function will create a new frame to fire the given events. It will
122− -- then update all dependent events and behaviors. After that is done, the
123− -- given callback is executed which allows to read the final values of events
124− -- and check whether they have fired in this frame or not.
125− --
126− -- All events that are given are fired at the same time.
127− --
128− -- This function is typically used in the main loop of a reflex framework
129− -- implementation. The main loop waits for external events to happen (such as
130− -- keyboard input or a mouse click) and then fires the corresponding events
131− -- using this function. The read callback can be used to read output events
132− -- and perform a corresponding response action to the external event.
133− fireEventsAndRead :: [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m a
134−
135− -- | Run a frame without any events firing.
136− --
137− -- This function should be used when you want to use 'sample' and 'hold' when
138− -- no events are currently firing. Using this function in that case can
139− -- improve performance, since the implementation can assume that no events are
140− -- firing when 'sample' or 'hold' are called.
141− --
142− -- This function is commonly used to set up the basic event network when the
143− -- application starts up.
144− runHostFrame :: HostFrame t a -> m a
145−
146−-- | Like 'fireEventsAndRead', but without reading any events.
147−fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t) Identity] -> m ()
148−fireEvents dm = fireEventsAndRead dm $ return ()
149−{-# INLINE fireEvents #-}
150−
151−-- | Create a new event and store its trigger in an 'IORef' while it's active.
152−--
153−-- An event is only active between the set up (when it's first subscribed to)
154−-- and the teardown phases (when noboby is subscribing the event anymore). This
155−-- function returns an Event and an 'IORef'. As long as the event is active, the
156−-- 'IORef' will contain 'Just' the event trigger to trigger this event. When the
157−-- event is not active, the 'IORef' will contain 'Nothing'. This allows event
158−-- sources to be more efficient, since they don't need to produce events when
159−-- nobody is listening.
160−newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
161−newEventWithTriggerRef = do
162− rt <- newRef Nothing
163− e <- newEventWithTrigger $ \t -> do
164− writeRef rt $ Just t
165− return $ writeRef rt Nothing
166− return (e, rt)
167−{-# INLINE newEventWithTriggerRef #-}
168−
169−-- | Fire the given trigger if it is not 'Nothing'.
170−fireEventRef :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> m ()
171−fireEventRef mtRef input = do
172− mt <- readRef mtRef
173− case mt of
174− Nothing -> return ()
175− Just trigger -> fireEvents [trigger :=> Identity input]
176−
177−-- | Fire the given trigger if it is not 'Nothing', and read from the given
178−-- 'EventHandle'.
179−fireEventRefAndRead :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> EventHandle t b -> m (Maybe b)
180−fireEventRefAndRead mtRef input e = do
181− mt <- readRef mtRef
182− case mt of
183− Nothing -> return Nothing -- Since we aren't firing the input, the output can't fire
184− Just trigger -> fireEventsAndRead [trigger :=> Identity input] $ do
185− mGetValue <- readEvent e
186− case mGetValue of
187− Nothing -> return Nothing
188− Just getValue -> fmap Just getValue
189−
190−
191−--------------------------------------------------------------------------------
192−-- Instances
193−--------------------------------------------------------------------------------
194−
195−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ReaderT r m) where
196− newEventWithTrigger = lift . newEventWithTrigger
197− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
198−
199−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ReaderT r m) where
200− subscribeEvent = lift . subscribeEvent
201−
202−instance MonadReflexHost t m => MonadReflexHost t (ReaderT r m) where
203− type ReadPhase (ReaderT r m) = ReadPhase m
204− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
205− runHostFrame = lift . runHostFrame
206−
207−instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (WriterT w m) where
208− newEventWithTrigger = lift . newEventWithTrigger
209− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
210−
211−instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (WriterT w m) where
212− subscribeEvent = lift . subscribeEvent
213−
214−instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (WriterT w m) where
215− type ReadPhase (WriterT w m) = ReadPhase m
216− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
217− runHostFrame = lift . runHostFrame
218−
219−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StateT s m) where
220− newEventWithTrigger = lift . newEventWithTrigger
221− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
222−
223−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (StateT r m) where
224− subscribeEvent = lift . subscribeEvent
225−
226−instance MonadReflexHost t m => MonadReflexHost t (StateT s m) where
227− type ReadPhase (StateT s m) = ReadPhase m
228− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
229− runHostFrame = lift . runHostFrame
230−
231−
232−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where
233− newEventWithTrigger = lift . newEventWithTrigger
234− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
235−
236−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (Strict.StateT r m) where
237− subscribeEvent = lift . subscribeEvent
238−
239−instance MonadReflexHost t m => MonadReflexHost t (Strict.StateT s m) where
240− type ReadPhase (Strict.StateT s m) = ReadPhase m
241− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
242− runHostFrame = lift . runHostFrame
243−
244−
245−
246−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where
247− newEventWithTrigger = lift . newEventWithTrigger
248− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
249−
250−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ContT r m) where
251− subscribeEvent = lift . subscribeEvent
252−
253−instance MonadReflexHost t m => MonadReflexHost t (ContT r m) where
254− type ReadPhase (ContT r m) = ReadPhase m
255− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
256− runHostFrame = lift . runHostFrame
257−
258−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ExceptT e m) where
259− newEventWithTrigger = lift . newEventWithTrigger
260− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
261−
262−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ExceptT r m) where
263− subscribeEvent = lift . subscribeEvent
264−
265−instance MonadReflexHost t m => MonadReflexHost t (ExceptT e m) where
266− type ReadPhase (ExceptT e m) = ReadPhase m
267− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
268− runHostFrame = lift . runHostFrame
269−
270−instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (RWST r w s m) where
271− newEventWithTrigger = lift . newEventWithTrigger
272− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
273−
274−instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (RWST r w s m) where
275− subscribeEvent = lift . subscribeEvent
276−
277−instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (RWST r w s m) where
278− type ReadPhase (RWST r w s m) = ReadPhase m
279− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
280− runHostFrame = lift . runHostFrame
src/Reflex/Network.hsdeleted−45
@@ -1,45 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE MultiParamTypeClasses #-}
3−#ifdef USE_REFLEX_OPTIMIZER
4−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5−#endif
6−-- |
7−-- Module:
8−-- Reflex.Network
9−-- Description:
10−-- This module provides combinators for building FRP graphs/networks and modifying them dynamically.
11−module Reflex.Network
12− ( networkView
13− , networkHold
14− , untilReady
15− ) where
16−
17−import Reflex.Class
18−import Reflex.Adjustable.Class
19−import Reflex.NotReady.Class
20−import Reflex.PostBuild.Class
21−
22−-- | A 'Dynamic' "network": Takes a 'Dynamic' of network-creating actions and replaces the network whenever the 'Dynamic' updates.
23−-- The returned Event of network results fires when the 'Dynamic' updates.
24−-- Note: Often, the type 'a' is an Event, in which case the return value is an Event-of-Events, where the outer 'Event' fires
25−-- when switching networks. Such an 'Event' would typically be flattened (via 'switchPromptly').
26−networkView :: (NotReady t m, Adjustable t m, PostBuild t m) => Dynamic t (m a) -> m (Event t a)
27−networkView child = do
28− postBuild <- getPostBuild
29− let newChild = leftmost [updated child, tagCheap (current child) postBuild]
30− snd <$> runWithReplace notReady newChild
31−
32−-- | Given an initial "network" and an 'Event' of network-creating actions, create a network that is recreated whenever the Event fires.
33−-- The returned Dynamic of network results occurs when the Event does.
34−-- Note: Often, the type 'a' is an Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
35−networkHold :: (Adjustable t m, MonadHold t m) => m a -> Event t (m a) -> m (Dynamic t a)
36−networkHold child0 newChild = do
37− (result0, newResult) <- runWithReplace child0 newChild
38− holdDyn result0 newResult
39−
40−-- | Render a placeholder network to be shown while another network is not yet
41−-- done building
42−untilReady :: (Adjustable t m, PostBuild t m) => m a -> m b -> m (a, Event t b)
43−untilReady a b = do
44− postBuild <- getPostBuild
45− runWithReplace a $ b <$ postBuild
src/Reflex/NotReady/Class.hsdeleted−78
@@ -1,78 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DefaultSignatures #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE TypeFamilies #-}
8−{-# LANGUAGE UndecidableInstances #-}
9−#ifdef USE_REFLEX_OPTIMIZER
10−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
11−#endif
12−module Reflex.NotReady.Class
13− ( NotReady(..)
14− ) where
15−
16−import Control.Monad.Reader (ReaderT)
17−import Control.Monad.Trans
18−import Control.Monad.Trans.Writer (WriterT)
19−
20−import Reflex.BehaviorWriter.Base (BehaviorWriterT)
21−import Reflex.Class
22−import Reflex.DynamicWriter.Base (DynamicWriterT)
23−import Reflex.EventWriter.Base (EventWriterT)
24−import Reflex.Host.Class
25−import Reflex.PerformEvent.Base (PerformEventT (..))
26−import Reflex.PostBuild.Base (PostBuildT)
27−import Reflex.Query.Base (QueryT)
28−import Reflex.Requester.Base (RequesterT)
29−import Reflex.TriggerEvent.Base (TriggerEventT)
30−
31−class Monad m => NotReady t m | m -> t where
32− notReadyUntil :: Event t a -> m ()
33− default notReadyUntil :: (MonadTrans f, m ~ f m', NotReady t m') => Event t a -> m ()
34− notReadyUntil = lift . notReadyUntil
35−
36− notReady :: m ()
37− default notReady :: (MonadTrans f, m ~ f m', NotReady t m') => m ()
38− notReady = lift notReady
39−
40−instance NotReady t m => NotReady t (ReaderT r m) where
41− notReadyUntil = lift . notReadyUntil
42− notReady = lift notReady
43−
44−instance (NotReady t m, Monoid w) => NotReady t (WriterT w m) where
45− notReadyUntil = lift . notReadyUntil
46− notReady = lift notReady
47−
48−instance NotReady t m => NotReady t (PostBuildT t m) where
49− notReadyUntil = lift . notReadyUntil
50− notReady = lift notReady
51−
52−instance NotReady t m => NotReady t (EventWriterT t w m) where
53− notReadyUntil = lift . notReadyUntil
54− notReady = lift notReady
55−
56−instance NotReady t m => NotReady t (DynamicWriterT t w m) where
57− notReadyUntil = lift . notReadyUntil
58− notReady = lift notReady
59−
60−instance NotReady t m => NotReady t (BehaviorWriterT t w m) where
61− notReadyUntil = lift . notReadyUntil
62− notReady = lift notReady
63−
64−instance NotReady t m => NotReady t (QueryT t q m) where
65− notReadyUntil = lift . notReadyUntil
66− notReady = lift notReady
67−
68−instance (ReflexHost t, NotReady t (HostFrame t)) => NotReady t (PerformEventT t m) where
69− notReadyUntil = PerformEventT . notReadyUntil
70− notReady = PerformEventT notReady
71−
72−instance NotReady t m => NotReady t (RequesterT t request response m) where
73− notReadyUntil = lift . notReadyUntil
74− notReady = lift notReady
75−
76−instance NotReady t m => NotReady t (TriggerEventT t m) where
77− notReadyUntil = lift . notReadyUntil
78− notReady = lift notReady
src/Reflex/Optimizer.hsdeleted−65
@@ -1,65 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−-- |
5−-- Module:
6−-- Reflex.Optimizer
7−-- Description:
8−-- This module provides a GHC plugin designed to improve code that uses
9−-- Reflex. Currently, it just adds an INLINABLE pragma to any top-level
10−-- definition that doesn't have an explicit inlining pragma. In the future,
11−-- additional optimizations are likely to be added.
12−module Reflex.Optimizer
13− ( plugin
14− ) where
15−
16−#ifdef ghcjs_HOST_OS
17−import Plugins
18−#else
19−import Control.Arrow
20−import CoreMonad
21−import Data.String
22−import GhcPlugins
23−
24−#if MIN_VERSION_base(4,9,0)
25−import Prelude hiding ((<>))
26−#endif
27−
28−#endif
29−
30−#ifdef ghcjs_HOST_OS
31−
32−-- | The GHCJS build of Reflex.Optimizer just throws an error; instead, the version built with GHC should be used.
33−plugin :: Plugin
34−plugin = error "The GHCJS build of Reflex.Optimizer cannot be used. Instead, build with GHC and use the result with GHCJS."
35−
36−#else
37−
38−-- | The GHC plugin itself. See "GhcPlugins" for more details.
39−plugin :: Plugin
40−plugin = defaultPlugin { installCoreToDos = install }
41−
42−install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
43−install [] p = do
44− liftIO $ putStrLn $ showSDocUnsafe $ ppr p
45− let f = \case
46− simpl@(CoreDoSimplify _ _) -> [CoreDoSpecialising, simpl]
47− x -> [x]
48− return $ makeInlinable : concatMap f p
49−install options@(_:_) p = do
50− warnMsg $ "Reflex.Optimizer: ignoring " <> fromString (show $ length options) <> " command-line options"
51− install [] p
52−
53−makeInlinable :: CoreToDo
54−makeInlinable = CoreDoPluginPass "MakeInlinable" $ \modGuts -> do
55− let f v = setIdInfo v $ let i = idInfo v in
56− setInlinePragInfo i $ let p = inlinePragInfo i in
57− if isDefaultInlinePragma p
58− then defaultInlinePragma { inl_inline = Inlinable }
59− else p
60− newBinds = flip map (mg_binds modGuts) $ \case
61− NonRec b e -> NonRec (f b) e
62− Rec bes -> Rec $ map (first f) bes
63− return $ modGuts { mg_binds = newBinds }
64−
65−#endif
src/Reflex/Patch.hsdeleted−50
@@ -1,50 +0,0 @@
1−{-# LANGUAGE TypeFamilies #-}
2−-- |
3−-- Module:
4−-- Reflex.Patch
5−-- Description:
6−-- This module defines the 'Patch' class, which is used by Reflex to manage
7−-- changes to 'Reflex.Class.Incremental' values.
8−module Reflex.Patch
9− ( module Reflex.Patch
10− , module X
11− ) where
12−
13−import Reflex.Patch.Class as X
14−import Reflex.Patch.DMap as X hiding (getDeletions)
15−import Reflex.Patch.DMapWithMove as X (PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove,
16− patchDMapWithMoveToPatchMapWithMoveWith,
17− traversePatchDMapWithMoveWithKey, unPatchDMapWithMove,
18− unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith)
19−import Reflex.Patch.IntMap as X hiding (getDeletions)
20−import Reflex.Patch.Map as X
21−import Reflex.Patch.MapWithMove as X (PatchMapWithMove, patchMapWithMoveNewElements,
22− patchMapWithMoveNewElementsMap, unPatchMapWithMove,
23− unsafePatchMapWithMove)
24−import Reflex.Patch.MapWithMove2 as X (PatchMapWithMove2, patchMapWithMove2NewElements,
25− patchMapWithMove2NewElementsMap, unPatchMapWithMove2,
26− unsafePatchMapWithMove2)
27−
28−import Data.Map.Monoidal (MonoidalMap)
29−import Data.Semigroup (Semigroup (..), (<>))
30−
31−-- | A 'Group' is a 'Monoid' where every element has an inverse.
32−class (Semigroup q, Monoid q) => Group q where
33− negateG :: q -> q
34− (~~) :: q -> q -> q
35− r ~~ s = r <> negateG s
36−
37−-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
38−class Semigroup q => Additive q where
39−
40−-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
41−newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
42−
43−instance Additive p => Patch (AdditivePatch p) where
44− type PatchTarget (AdditivePatch p) = p
45− apply (AdditivePatch p) q = Just $ p <> q
46−
47−instance (Ord k, Group q) => Group (MonoidalMap k q) where
48− negateG = fmap negateG
49−
50−instance (Ord k, Additive q) => Additive (MonoidalMap k q)
src/Reflex/Patch/MapWithMove.hsdeleted−270
@@ -1,270 +0,0 @@
1−{-# LANGUAGE DeriveFoldable #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE DeriveTraversable #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE PatternGuards #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
10−-- another
11−module Reflex.Patch.MapWithMove where
12−
13−import Reflex.Patch.Class
14−
15−import Control.Arrow
16−import Control.Monad.State
17−import Data.Foldable
18−import Data.Function
19−import Data.List
20−import Data.Map (Map)
21−import qualified Data.Map as Map
22−import Data.Maybe
23−import Data.Semigroup (Semigroup (..), (<>))
24−import qualified Data.Set as Set
25−import Data.These (These(..))
26−import Data.Tuple
27−
28−-- | Patch a DMap with additions, deletions, and moves. Invariant: If key @k1@
29−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
30−-- and vice versa. There should never be any unpaired From/To keys.
31−newtype PatchMapWithMove k v = PatchMapWithMove (Map k (NodeInfo k v)) deriving (Show, Eq, Ord, Functor, Foldable, Traversable)
32−
33−-- | Holds the information about each key: where its new value should come from,
34−-- and where its old value should go to
35−data NodeInfo k v = NodeInfo
36− { _nodeInfo_from :: !(From k v)
37− -- ^ Where do we get the new value for this key?
38− , _nodeInfo_to :: !(To k)
39− -- ^ If the old value is being kept (i.e. moved rather than deleted or
40− -- replaced), where is it going?
41− }
42− deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
43−
44−-- | Describe how a key's new value should be produced
45−data From k v
46− = From_Insert v -- ^ Insert the given value here
47− | From_Delete -- ^ Delete the existing value, if any, from here
48− | From_Move !k -- ^ Move the value here from the given key
49− deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
50−
51−-- | Describe where a key's old value will go. If this is 'Just', that means
52−-- the key's old value will be moved to the given other key; if it is 'Nothing',
53−-- that means it will be deleted.
54−type To = Maybe
55−
56−-- | Create a 'PatchMapWithMove', validating it
57−patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
58−patchMapWithMove m = if valid then Just $ PatchMapWithMove m else Nothing
59− where valid = forwardLinks == backwardLinks
60− forwardLinks = Map.mapMaybe _nodeInfo_to m
61− backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, v) ->
62− case _nodeInfo_from v of
63− From_Move from -> Just (from, to)
64− _ -> Nothing
65−
66−-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
67−patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
68−patchMapWithMoveInsertAll m = PatchMapWithMove $ flip fmap m $ \v -> NodeInfo
69− { _nodeInfo_from = From_Insert v
70− , _nodeInfo_to = Nothing
71− }
72−
73−-- | Extract the internal representation of the 'PatchMapWithMove'
74−unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
75−unPatchMapWithMove (PatchMapWithMove p) = p
76−
77−-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
78−insertMapKey :: k -> v -> PatchMapWithMove k v
79−insertMapKey k v = PatchMapWithMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
80−
81−-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
82−--
83−-- @
84−-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
85−-- @
86−moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
87−moveMapKey src dst
88− | src == dst = mempty
89− | otherwise =
90− PatchMapWithMove $ Map.fromList
91− [ (dst, NodeInfo (From_Move src) Nothing)
92− , (src, NodeInfo From_Delete (Just dst))
93− ]
94−
95−-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
96−--
97−-- @
98−-- let aMay = Map.lookup a map
99−-- bMay = Map.lookup b map
100−-- in maybe id (Map.insert a) (bMay `mplus` aMay)
101−-- . maybe id (Map.insert b) (aMay `mplus` bMay)
102−-- . Map.delete a . Map.delete b $ map
103−-- @
104−swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
105−swapMapKey src dst
106− | src == dst = mempty
107− | otherwise =
108− PatchMapWithMove $ Map.fromList
109− [ (dst, NodeInfo (From_Move src) (Just src))
110− , (src, NodeInfo (From_Move dst) (Just dst))
111− ]
112−
113−-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
114−deleteMapKey :: k -> PatchMapWithMove k v
115−deleteMapKey k = PatchMapWithMove . Map.singleton k $ NodeInfo From_Delete Nothing
116−
117−-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
118−--
119−-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
120−unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
121−unsafePatchMapWithMove = PatchMapWithMove
122−
123−-- | Apply the insertions, deletions, and moves to a given 'Map'
124−instance Ord k => Patch (PatchMapWithMove k v) where
125− type PatchTarget (PatchMapWithMove k v) = Map k v
126− apply (PatchMapWithMove p) old = Just $! insertions `Map.union` (old `Map.difference` deletions) --TODO: return Nothing sometimes --Note: the strict application here is critical to ensuring that incremental merges don't hold onto all their prerequisite events forever; can we make this more robust?
127− where insertions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
128− From_Insert v -> Just v
129− From_Move k -> Map.lookup k old
130− From_Delete -> Nothing
131− deletions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
132− From_Delete -> Just ()
133− _ -> Nothing
134−
135−-- | Returns all the new elements that will be added to the 'Map'.
136−patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
137−patchMapWithMoveNewElements = Map.elems . patchMapWithMoveNewElementsMap
138−
139−-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
140−patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
141−patchMapWithMoveNewElementsMap (PatchMapWithMove p) = Map.mapMaybe f p
142− where f ni = case _nodeInfo_from ni of
143− From_Insert v -> Just v
144− From_Move _ -> Nothing
145− From_Delete -> Nothing
146−
147−-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
148−-- its values using the given ordering function. The set keys of the 'Map' is
149−-- not changed.
150−patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
151−patchThatSortsMapWith cmp m = PatchMapWithMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
152− where unsorted = Map.toList m
153− sorted = sortBy (cmp `on` snd) unsorted
154− f (to, _) (from, _) = if to == from then Nothing else
155− Just (from, to)
156− reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
157− g (to, _) (from, _) = if to == from then Nothing else
158− let Just movingTo = Map.lookup from reverseMapping
159− in Just (to, NodeInfo (From_Move from) $ Just movingTo)
160−
161−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
162−-- will produce a 'Map' with the same values as the second 'Map' but with the
163−-- values sorted with the given ordering function.
164−patchThatChangesAndSortsMapWith :: forall k v. (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
165−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
166− where newList = Map.toList newByIndexUnsorted
167− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
168−
169−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
170−-- will produce the second 'Map'.
171−patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
172−patchThatChangesMap oldByIndex newByIndex = patch
173− where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
174− (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
175− let f k v = do
176− remainingValues <- get
177− let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
178− then Map.delete v remainingValues
179− else Map.insert v remainingKeys remainingValues
180− case Map.lookup v remainingValues of
181− Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
182− Just fromKs ->
183− if k `Set.member` fromKs
184− then do
185− putRemainingKeys $ Set.delete k fromKs
186− return $ NodeInfo (From_Move k) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
187− else do
188− (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
189− putRemainingKeys remainingKeys
190− return $ NodeInfo (From_Move fromK) $ Just undefined
191− Map.traverseWithKey f newByIndex
192− unusedOldKeys = fold unusedValuesByValue
193− pointlessMove k = \case
194− From_Move k' | k == k' -> True
195− _ -> False
196− keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
197− then Just undefined
198− else Nothing
199− patch = unsafePatchMapWithMove $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
200−
201−-- | Change the 'From' value of a 'NodeInfo'
202−nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
203−nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
204−
205−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
206−-- 'Applicative', 'Monad', etc.) action to get the new value
207−nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
208−nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
209−
210−-- | Set the 'To' field of a 'NodeInfo'
211−nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
212−nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
213−
214−-- |Helper data structure used for composing patches using the monoid instance.
215−data Fixup k v
216− = Fixup_Delete
217− | Fixup_Update (These (From k v) (To k))
218−
219−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
220−instance Ord k => Semigroup (PatchMapWithMove k v) where
221− PatchMapWithMove ma <> PatchMapWithMove mb = PatchMapWithMove m
222− where
223− connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
224− h :: (k, (Maybe k, From k v)) -> [(k, Fixup k v)]
225− h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
226− (Just toAfter, From_Move fromBefore)
227− | fromBefore == toAfter
228− -> [(toAfter, Fixup_Delete)]
229− | otherwise
230− -> [ (toAfter, Fixup_Update (This editBefore))
231− , (fromBefore, Fixup_Update (That mToAfter))
232− ]
233− (Nothing, From_Move fromBefore) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
234− (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
235− (Nothing, _) -> []
236− mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
237− mergeFixups _ (Fixup_Update a) (Fixup_Update b)
238− | This x <- a, That y <- b
239− = Fixup_Update $ These x y
240− | That y <- a, This x <- b
241− = Fixup_Update $ These x y
242− mergeFixups _ _ _ = error "PatchMapWithMove: incompatible fixups"
243− fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
244− combineNodeInfos _ nia nib = NodeInfo
245− { _nodeInfo_from = _nodeInfo_from nia
246− , _nodeInfo_to = _nodeInfo_to nib
247− }
248− applyFixup _ ni = \case
249− Fixup_Delete -> Nothing
250− Fixup_Update u -> Just $ NodeInfo
251− { _nodeInfo_from = fromMaybe (_nodeInfo_from ni) $ getHere u
252− , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
253− }
254− m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
255− getHere :: These a b -> Maybe a
256− getHere = \case
257− This a -> Just a
258− These a _ -> Just a
259− That _ -> Nothing
260− getThere :: These a b -> Maybe b
261− getThere = \case
262− This _ -> Nothing
263− These _ b -> Just b
264− That b -> Just b
265−
266−--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
267−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
268−instance Ord k => Monoid (PatchMapWithMove k v) where
269− mempty = PatchMapWithMove mempty
270− mappend = (<>)
src/Reflex/Patch/MapWithMove2.hsdeleted−245
@@ -1,245 +0,0 @@
1−{-# LANGUAGE DeriveFoldable #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE DeriveTraversable #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE PatternGuards #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE StandaloneDeriving #-}
9−{-# LANGUAGE TypeFamilies #-}
10−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
11−-- another
12−module Reflex.Patch.MapWithMove2 where
13−
14−import Reflex.Patch.Class
15−
16−import Control.Arrow
17−import Control.Monad.State
18−import Data.Foldable
19−import Data.Function
20−import Data.List
21−import Data.Map (Map)
22−import qualified Data.Map as Map
23−import Data.Maybe
24−import Data.Semigroup
25−import qualified Data.Set as Set
26−import Data.These
27−import Data.Tuple
28−
29−-- | Patch a DMap with additions, deletions, and moves. Invariant: If key @k1@
30−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
31−-- and vice versa. There should never be any unpaired From/To keys.
32−newtype PatchMapWithMove2 k p = PatchMapWithMove2 (Map k (NodeInfo k p))
33−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithMove2 k p)
34−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithMove2 k p)
35−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithMove2 k p)
36−
37−-- | Holds the information about each key: where its new value should come from,
38−-- and where its old value should go to
39−data NodeInfo k p = NodeInfo
40− { _nodeInfo_from :: !(From k p)
41− -- ^ Where do we get the new value for this key?
42− , _nodeInfo_to :: !(To k)
43− -- ^ If the old value is being kept (i.e. moved rather than deleted or
44− -- replaced), where is it going?
45− }
46−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
47−deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
48−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
49−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
50−
51−-- | Create a 'PatchMapWithMove2', validating it
52−patchMapWithMove2 :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithMove2 k p)
53−patchMapWithMove2 m = if valid then Just $ PatchMapWithMove2 m else Nothing
54− where valid = forwardLinks == backwardLinks
55− forwardLinks = Map.mapMaybe _nodeInfo_to m
56− backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
57− case _nodeInfo_from p of
58− From_Move from _ -> Just (from, to)
59− _ -> Nothing
60−
61−-- | Create a 'PatchMapWithMove2' that inserts everything in the given 'Map'
62−patchMapWithMove2InsertAll :: Map k (PatchTarget p) -> PatchMapWithMove2 k p
63−patchMapWithMove2InsertAll m = PatchMapWithMove2 $ flip fmap m $ \v -> NodeInfo
64− { _nodeInfo_from = From_Insert v
65− , _nodeInfo_to = Nothing
66− }
67−
68−-- | Extract the internal representation of the 'PatchMapWithMove2'
69−unPatchMapWithMove2 :: PatchMapWithMove2 k p -> Map k (NodeInfo k p)
70−unPatchMapWithMove2 (PatchMapWithMove2 p) = p
71−
72−-- | Warning: when using this function, you must ensure that the invariants of
73−-- 'PatchMapWithMove2' are preserved; they will not be checked.
74−unsafePatchMapWithMove2 :: Map k (NodeInfo k p) -> PatchMapWithMove2 k p
75−unsafePatchMapWithMove2 = PatchMapWithMove2
76−
77−-- | Describe how a key's new value should be produced
78−data From k p
79− = From_Insert (PatchTarget p) -- ^ Insert the given value here
80− | From_Delete -- ^ Delete the existing value, if any, from here
81− | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
82−
83−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
84−deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
85−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
86−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
87−
88−-- | Describe where a key's old value will go. If this is 'Just', that means
89−-- the key's old value will be moved to the given other key; if it is 'Nothing',
90−-- that means it will be deleted.
91−type To = Maybe
92−
93−-- | Apply the insertions, deletions, and moves to a given 'Map'
94−instance (Ord k, Patch p) => Patch (PatchMapWithMove2 k p) where
95− type PatchTarget (PatchMapWithMove2 k p) = Map k (PatchTarget p)
96− apply (PatchMapWithMove2 m) old = Just $! insertions `Map.union` (old `Map.difference` deletions) --TODO: return Nothing sometimes --Note: the strict application here is critical to ensuring that incremental merges don't hold onto all their prerequisite events forever; can we make this more robust?
97− where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
98− From_Insert v -> Just v
99− From_Move k p -> applyAlways p <$> Map.lookup k old
100− From_Delete -> Nothing
101− deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
102− From_Delete -> Just ()
103− _ -> Nothing
104−
105−-- | Returns all the new elements that will be added to the 'Map'
106−patchMapWithMove2NewElements :: PatchMapWithMove2 k p -> [PatchTarget p]
107−patchMapWithMove2NewElements = Map.elems . patchMapWithMove2NewElementsMap
108−
109−patchMapWithMove2NewElementsMap :: PatchMapWithMove2 k p -> Map k (PatchTarget p)
110−patchMapWithMove2NewElementsMap (PatchMapWithMove2 p) = Map.mapMaybe f p
111− where f ni = case _nodeInfo_from ni of
112− From_Insert v -> Just v
113− From_Move _ _ -> Nothing
114− From_Delete -> Nothing
115−
116−-- | Create a 'PatchMapWithMove2' that, if applied to the given 'Map', will sort
117−-- its values using the given ordering function. The set keys of the 'Map' is
118−-- not changed.
119−patchThatSortsMapWith :: (Ord k, Monoid p) => (PatchTarget p -> PatchTarget p -> Ordering) -> Map k (PatchTarget p) -> PatchMapWithMove2 k p
120−patchThatSortsMapWith cmp m = PatchMapWithMove2 $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
121− where unsorted = Map.toList m
122− sorted = sortBy (cmp `on` snd) unsorted
123− f (to, _) (from, _) = if to == from then Nothing else
124− Just (from, to)
125− reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
126− g (to, _) (from, _) = if to == from then Nothing else
127− let Just movingTo = Map.lookup from reverseMapping
128− in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
129−
130−-- | Create a 'PatchMapWithMove2' that, if applied to the first 'Map' provided,
131−-- will produce a 'Map' with the same values as the second 'Map' but with the
132−-- values sorted with the given ordering function.
133−patchThatChangesAndSortsMapWith :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p) => (PatchTarget p -> PatchTarget p -> Ordering) -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithMove2 k p
134−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
135− where newList = Map.toList newByIndexUnsorted
136− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
137−
138−-- | Create a 'PatchMapWithMove2' that, if applied to the first 'Map' provided,
139−-- will produce the second 'Map'.
140−patchThatChangesMap :: (Ord k, Ord (PatchTarget p), Monoid p) => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithMove2 k p
141−patchThatChangesMap oldByIndex newByIndex = patch
142− where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
143− (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
144− let f k v = do
145− remainingValues <- get
146− let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
147− then Map.delete v remainingValues
148− else Map.insert v remainingKeys remainingValues
149− case Map.lookup v remainingValues of
150− Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
151− Just fromKs ->
152− if k `Set.member` fromKs
153− then do
154− putRemainingKeys $ Set.delete k fromKs
155− return $ NodeInfo (From_Move k mempty) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
156− else do
157− (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
158− putRemainingKeys remainingKeys
159− return $ NodeInfo (From_Move fromK mempty) $ Just undefined
160− Map.traverseWithKey f newByIndex
161− unusedOldKeys = fold unusedValuesByValue
162− pointlessMove k = \case
163− From_Move k' _ | k == k' -> True
164− _ -> False
165− keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
166− then Just undefined
167− else Nothing
168− patch = unsafePatchMapWithMove2 $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
169−
170−-- | Change the 'From' value of a 'NodeInfo'
171−nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
172−nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
173−
174−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
175−-- 'Applicative', 'Monad', etc.) action to get the new value
176−nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
177−nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
178−
179−-- | Set the 'To' field of a 'NodeInfo'
180−nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
181−nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
182−
183−-- |Helper data structure used for composing patches using the monoid instance.
184−data Fixup k v
185− = Fixup_Delete
186− | Fixup_Update (These (From k v) (To k))
187−
188−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
189−instance (Ord k, Monoid p, Eq p, Patch p) => Semigroup (PatchMapWithMove2 k p) where
190− PatchMapWithMove2 ma <> PatchMapWithMove2 mb = PatchMapWithMove2 m
191− where
192− connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
193− h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
194− h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
195− (Just toAfter, From_Move fromBefore p)
196− | fromBefore == toAfter && p == mempty
197− -> [(toAfter, Fixup_Delete)]
198− | otherwise
199− -> [ (toAfter, Fixup_Update (This editBefore))
200− , (fromBefore, Fixup_Update (That mToAfter))
201− ]
202− (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
203− (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
204− (Nothing, _) -> []
205− mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
206− mergeFixups _ (Fixup_Update a) (Fixup_Update b)
207− | This x <- a, That y <- b
208− = Fixup_Update $ These x y
209− | That y <- a, This x <- b
210− = Fixup_Update $ These x y
211− mergeFixups _ _ _ = error "PatchMapWithMove2: incompatible fixups"
212− fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
213− combineNodeInfos _ nia nib = NodeInfo
214− { _nodeInfo_from = _nodeInfo_from nia
215− , _nodeInfo_to = _nodeInfo_to nib
216− }
217− applyFixup _ ni = \case
218− Fixup_Delete -> Nothing
219− Fixup_Update u -> Just $ NodeInfo
220− { _nodeInfo_from = case _nodeInfo_from ni of
221− f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
222− Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
223− Just (From_Insert v) -> From_Insert $ applyAlways p' v
224− Just From_Delete -> From_Delete
225− Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
226− _ -> error "PatchMapWithMove2: fixup for non-move From"
227− , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
228− }
229− m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
230− getHere :: These a b -> Maybe a
231− getHere = \case
232− This a -> Just a
233− These a _ -> Just a
234− That _ -> Nothing
235− getThere :: These a b -> Maybe b
236− getThere = \case
237− This _ -> Nothing
238− These _ b -> Just b
239− That b -> Just b
240−
241−--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
242−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
243−instance (Ord k, Monoid p, Eq p, Patch p) => Monoid (PatchMapWithMove2 k p) where
244− mempty = PatchMapWithMove2 mempty
245− mappend = (<>)
src/Reflex/PerformEvent/Base.hsdeleted−179
@@ -1,179 +0,0 @@
1−-- | This module provides 'PerformEventT', the standard implementation of
2−-- 'PerformEvent'.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE ExistentialQuantification #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE GADTs #-}
8−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE PartialTypeSignatures #-}
11−{-# LANGUAGE PolyKinds #-}
12−{-# LANGUAGE RankNTypes #-}
13−{-# LANGUAGE ScopedTypeVariables #-}
14−{-# LANGUAGE StandaloneDeriving #-}
15−{-# LANGUAGE TypeFamilies #-}
16−{-# LANGUAGE TypeOperators #-}
17−{-# LANGUAGE UndecidableInstances #-}
18−#ifdef USE_REFLEX_OPTIMIZER
19−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20−#endif
21−module Reflex.PerformEvent.Base
22− ( PerformEventT (..)
23− , FireCommand (..)
24− , hostPerformEventT
25− ) where
26−
27−import Reflex.Class
28−import Reflex.Adjustable.Class
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.Requester.Base
32−import Reflex.Requester.Class
33−
34−import Control.Lens
35−import Control.Monad.Exception
36−import Control.Monad.Identity
37−import Control.Monad.Primitive
38−import Control.Monad.Reader
39−import Control.Monad.Ref
40−import Data.Coerce
41−import Data.Dependent.Map (DMap)
42−import qualified Data.Dependent.Map as DMap
43−import Data.Dependent.Sum
44−import Data.IntMap.Strict (IntMap)
45−import qualified Data.IntMap.Strict as IntMap
46−import qualified Data.Semigroup as S
47−
48−-- | A function that fires events for the given 'EventTrigger's and then runs
49−-- any followup actions provided via 'PerformEvent'. The given 'ReadPhase'
50−-- action will be run once for the initial trigger execution as well as once for
51−-- each followup.
52−newtype FireCommand t m = FireCommand { runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a] } --TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?
53−
54−-- | Provides a basic implementation of 'PerformEvent'. Note that, despite the
55−-- name, 'PerformEventT' is not an instance of 'MonadTrans'.
56−newtype PerformEventT t m a = PerformEventT { unPerformEventT :: RequesterT t (HostFrame t) Identity (HostFrame t) a }
57−
58−deriving instance ReflexHost t => Functor (PerformEventT t m)
59−deriving instance ReflexHost t => Applicative (PerformEventT t m)
60−deriving instance ReflexHost t => Monad (PerformEventT t m)
61−deriving instance ReflexHost t => MonadFix (PerformEventT t m)
62−deriving instance (ReflexHost t, MonadIO (HostFrame t)) => MonadIO (PerformEventT t m)
63−deriving instance (ReflexHost t, MonadException (HostFrame t)) => MonadException (PerformEventT t m)
64−deriving instance (ReflexHost t, Monoid a) => Monoid (PerformEventT t m a)
65−deriving instance (ReflexHost t, S.Semigroup a) => S.Semigroup (PerformEventT t m a)
66−
67−instance (PrimMonad (HostFrame t), ReflexHost t) => PrimMonad (PerformEventT t m) where
68− type PrimState (PerformEventT t m) = PrimState (HostFrame t)
69− primitive = PerformEventT . lift . primitive
70−
71−instance (ReflexHost t, Ref m ~ Ref IO) => PerformEvent t (PerformEventT t m) where
72− type Performable (PerformEventT t m) = HostFrame t
73− {-# INLINABLE performEvent_ #-}
74− performEvent_ = PerformEventT . requesting_
75− {-# INLINABLE performEvent #-}
76− performEvent = PerformEventT . requestingIdentity
77−
78−instance (ReflexHost t, PrimMonad (HostFrame t)) => Adjustable t (PerformEventT t m) where
79− runWithReplace outerA0 outerA' = PerformEventT $ runWithReplaceRequesterTWith f (coerce outerA0) (coerceEvent outerA')
80− where f :: HostFrame t a -> Event t (HostFrame t b) -> RequesterT t (HostFrame t) Identity (HostFrame t) (a, Event t b)
81− f a0 a' = do
82− result0 <- lift a0
83− result' <- requestingIdentity a'
84− return (result0, result')
85− traverseIntMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseIntMapWithKeyWithAdjustRequesterTWith (defaultAdjustIntBase traverseIntMapPatchWithKey) patchIntMapNewElementsMap mergeIntIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
86− traverseDMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithKey) mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
87− traverseDMapWithKeyWithAdjustWithMove f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithMoveWithKey) mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
88−
89−defaultAdjustBase :: forall t v v2 k' p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
90− => ((forall a. k' a -> v a -> HostFrame t (v2 a)) -> p k' v -> HostFrame t (p k' v2))
91− -> (forall a. k' a -> v a -> HostFrame t (v2 a))
92− -> DMap k' v
93− -> Event t (p k' v)
94− -> RequesterT t (HostFrame t) Identity (HostFrame t) (DMap k' v2, Event t (p k' v2))
95−defaultAdjustBase traversePatchWithKey f' dm0 dm' = do
96− result0 <- lift $ DMap.traverseWithKey f' dm0
97− result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
98− return (result0, result')
99−
100−defaultAdjustIntBase :: forall t v v2 p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
101− => ((IntMap.Key -> v -> HostFrame t v2) -> p v -> HostFrame t (p v2))
102− -> (IntMap.Key -> v -> HostFrame t v2)
103− -> IntMap v
104− -> Event t (p v)
105− -> RequesterT t (HostFrame t) Identity (HostFrame t) (IntMap v2, Event t (p v2))
106−defaultAdjustIntBase traversePatchWithKey f' dm0 dm' = do
107− result0 <- lift $ IntMap.traverseWithKey f' dm0
108− result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
109− return (result0, result')
110−
111−instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where
112− {-# INLINABLE newEventWithTrigger #-}
113− newEventWithTrigger = PerformEventT . lift . newEventWithTrigger
114− {-# INLINABLE newFanEventWithTrigger #-}
115− newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f
116−
117−-- | Run a 'PerformEventT' action, returning a 'FireCommand' that allows the
118−-- caller to trigger 'Event's while ensuring that 'performEvent' actions are run
119−-- at the appropriate time.
120−{-# INLINABLE hostPerformEventT #-}
121−hostPerformEventT :: forall t m a.
122− ( Monad m
123− , MonadSubscribeEvent t m
124− , MonadReflexHost t m
125− , MonadRef m
126− , Ref m ~ Ref IO
127− )
128− => PerformEventT t m a
129− -> m (a, FireCommand t m)
130−hostPerformEventT a = do
131− (response, responseTrigger) <- newEventWithTriggerRef
132− (result, eventToPerform) <- runHostFrame $ runRequesterT (unPerformEventT a) response
133− eventToPerformHandle <- subscribeEvent eventToPerform
134− return $ (,) result $ FireCommand $ \triggers (readPhase :: ReadPhase m a') -> do
135− let go :: [DSum (EventTrigger t) Identity] -> m [a']
136− go ts = do
137− (result', mToPerform) <- fireEventsAndRead ts $ do
138− mToPerform <- sequence =<< readEvent eventToPerformHandle
139− result' <- readPhase
140− return (result', mToPerform)
141− case mToPerform of
142− Nothing -> return [result']
143− Just toPerform -> do
144− responses <- runHostFrame $ traverseRequesterData (\v -> Identity <$> v) toPerform
145− mrt <- readRef responseTrigger
146− let followupEventTriggers = case mrt of
147− Just rt -> [rt :=> Identity responses]
148− Nothing -> []
149− (result':) <$> go followupEventTriggers
150− go triggers
151−
152−instance ReflexHost t => MonadSample t (PerformEventT t m) where
153− {-# INLINABLE sample #-}
154− sample = PerformEventT . lift . sample
155−
156−instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where
157− {-# INLINABLE hold #-}
158− hold v0 v' = PerformEventT $ lift $ hold v0 v'
159− {-# INLINABLE holdDyn #-}
160− holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'
161− {-# INLINABLE holdIncremental #-}
162− holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'
163− {-# INLINABLE buildDynamic #-}
164− buildDynamic getV0 v' = PerformEventT $ lift $ buildDynamic getV0 v'
165− {-# INLINABLE headE #-}
166− headE = PerformEventT . lift . headE
167−
168−instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where
169− type Ref (PerformEventT t m) = Ref (HostFrame t)
170− {-# INLINABLE newRef #-}
171− newRef = PerformEventT . lift . newRef
172− {-# INLINABLE readRef #-}
173− readRef = PerformEventT . lift . readRef
174− {-# INLINABLE writeRef #-}
175− writeRef r = PerformEventT . lift . writeRef r
176−
177−instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where
178− {-# INLINABLE atomicModifyRef #-}
179− atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
src/Reflex/PerformEvent/Class.hsdeleted−64
@@ -1,64 +0,0 @@
1−-- | This module defines 'PerformEvent' and 'TriggerEvent', which mediate the
2−-- interaction between a "Reflex"-based program and the external side-effecting
3−-- actions such as 'IO'.
4−{-# LANGUAGE CPP #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE RankNTypes #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE TypeOperators #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−#ifdef USE_REFLEX_OPTIMIZER
15−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
16−#endif
17−module Reflex.PerformEvent.Class
18− ( PerformEvent (..)
19− , performEventAsync
20− ) where
21−
22−import Reflex.Class
23−import Reflex.TriggerEvent.Class
24−
25−import Control.Monad.Reader
26−
27−-- | 'PerformEvent' represents actions that can trigger other actions based on
28−-- 'Event's.
29−class (Reflex t, Monad (Performable m), Monad m) => PerformEvent t m | m -> t where
30− -- | The type of action to be triggered; this is often not the same type as
31− -- the triggering action.
32− type Performable m :: * -> *
33− -- | Perform the action contained in the given 'Event' whenever the 'Event'
34− -- fires. Return the result in another 'Event'. Note that the output 'Event'
35− -- will generally occur later than the input 'Event', since most 'Performable'
36− -- actions cannot be performed during 'Event' propagation.
37− performEvent :: Event t (Performable m a) -> m (Event t a)
38− -- | Like 'performEvent', but do not return the result. May have slightly
39− -- better performance.
40− performEvent_ :: Event t (Performable m ()) -> m ()
41−
42−-- | Like 'performEvent', but the resulting 'Event' occurs only when the
43−-- callback (@a -> IO ()@) is called, not when the included action finishes.
44−--
45−-- NOTE: Despite the name, 'performEventAsync' does not run its action in a
46−-- separate thread - although the action is free to invoke forkIO and then call
47−-- the callback whenever it is ready. This will work properly, even in GHCJS
48−-- (which fully implements concurrency even though JavaScript does not have
49−-- built in concurrency).
50−{-# INLINABLE performEventAsync #-}
51−performEventAsync :: (TriggerEvent t m, PerformEvent t m) => Event t ((a -> IO ()) -> Performable m ()) -> m (Event t a)
52−performEventAsync e = do
53− (eOut, triggerEOut) <- newTriggerEvent
54− performEvent_ $ fmap ($ triggerEOut) e
55− return eOut
56−
57−instance PerformEvent t m => PerformEvent t (ReaderT r m) where
58− type Performable (ReaderT r m) = ReaderT r (Performable m)
59− performEvent_ e = do
60− r <- ask
61− lift $ performEvent_ $ flip runReaderT r <$> e
62− performEvent e = do
63− r <- ask
64− lift $ performEvent $ flip runReaderT r <$> e
src/Reflex/PostBuild/Base.hsdeleted−197
@@ -1,197 +0,0 @@
1−-- | This module defines 'PostBuildT', the standard implementation of
2−-- 'PostBuild'.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE DataKinds #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RecursiveDo #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE TypeOperators #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−#ifdef USE_REFLEX_OPTIMIZER
15−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
16−#endif
17−module Reflex.PostBuild.Base
18− ( PostBuildT (..)
19− , runPostBuildT
20− -- * Internal
21− , mapIntMapWithAdjustImpl
22− , mapDMapWithAdjustImpl
23− ) where
24−
25−import Reflex.Class
26−import Reflex.Adjustable.Class
27−import Reflex.Host.Class
28−import Reflex.PerformEvent.Class
29−import Reflex.PostBuild.Class
30−import Reflex.TriggerEvent.Class
31−
32−import Control.Applicative (liftA2)
33−import Control.Monad.Exception
34−import Control.Monad.Identity
35−import Control.Monad.Primitive
36−import Control.Monad.Reader
37−import Control.Monad.Ref
38−import qualified Control.Monad.Trans.Control as TransControl
39−import Data.Dependent.Map (DMap)
40−import qualified Data.Dependent.Map as DMap
41−import Data.Functor.Compose
42−import Data.IntMap.Strict (IntMap)
43−import qualified Data.IntMap.Strict as IntMap
44−import qualified Data.Semigroup as S
45−
46−-- | Provides a basic implementation of 'PostBuild'.
47−newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException)
48−
49−-- | Run a 'PostBuildT' action. An 'Event' should be provided that fires
50−-- immediately after the action is finished running; no other 'Event's should
51−-- fire first.
52−{-# INLINABLE runPostBuildT #-}
53−runPostBuildT :: PostBuildT t m a -> Event t () -> m a
54−runPostBuildT (PostBuildT a) = runReaderT a
55−
56−-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
57−instance (Monoid a, Applicative m) => Monoid (PostBuildT t m a) where
58− mempty = pure mempty
59− mappend = liftA2 mappend
60−
61−instance (S.Semigroup a, Applicative m) => S.Semigroup (PostBuildT t m a) where
62− (<>) = liftA2 (S.<>)
63−
64−instance PrimMonad m => PrimMonad (PostBuildT x m) where
65− type PrimState (PostBuildT x m) = PrimState m
66− primitive = lift . primitive
67−
68−instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where
69− {-# INLINABLE getPostBuild #-}
70− getPostBuild = PostBuildT ask
71−
72−instance MonadSample t m => MonadSample t (PostBuildT t m) where
73− {-# INLINABLE sample #-}
74− sample = lift . sample
75−
76−instance MonadHold t m => MonadHold t (PostBuildT t m) where
77− {-# INLINABLE hold #-}
78− hold v0 = lift . hold v0
79− {-# INLINABLE holdDyn #-}
80− holdDyn v0 = lift . holdDyn v0
81− {-# INLINABLE holdIncremental #-}
82− holdIncremental v0 = lift . holdIncremental v0
83− {-# INLINABLE buildDynamic #-}
84− buildDynamic a0 = lift . buildDynamic a0
85− {-# INLINABLE headE #-}
86− headE = lift . headE
87−
88−instance PerformEvent t m => PerformEvent t (PostBuildT t m) where
89− type Performable (PostBuildT t m) = Performable m
90− {-# INLINABLE performEvent_ #-}
91− performEvent_ = lift . performEvent_
92− {-# INLINABLE performEvent #-}
93− performEvent = lift . performEvent
94−
95−instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where
96− {-# INLINABLE newEventWithTrigger #-}
97− newEventWithTrigger = PostBuildT . lift . newEventWithTrigger
98− {-# INLINABLE newFanEventWithTrigger #-}
99− newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f
100−
101−instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where
102− {-# INLINABLE newTriggerEvent #-}
103− newTriggerEvent = lift newTriggerEvent
104− {-# INLINABLE newTriggerEventWithOnComplete #-}
105− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
106− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
107−
108−instance MonadRef m => MonadRef (PostBuildT t m) where
109− type Ref (PostBuildT t m) = Ref m
110− {-# INLINABLE newRef #-}
111− newRef = lift . newRef
112− {-# INLINABLE readRef #-}
113− readRef = lift . readRef
114− {-# INLINABLE writeRef #-}
115− writeRef r = lift . writeRef r
116−
117−instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where
118− {-# INLINABLE atomicModifyRef #-}
119− atomicModifyRef r = lift . atomicModifyRef r
120−
121−instance (Reflex t, MonadHold t m, MonadFix m, Adjustable t m, PerformEvent t m) => Adjustable t (PostBuildT t m) where
122− runWithReplace a0 a' = do
123− postBuild <- getPostBuild
124− lift $ do
125− rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a'
126− let voidResult' = fmapCheap (\_ -> ()) result'
127− return result
128− {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
129− traverseIntMapWithKeyWithAdjust = mapIntMapWithAdjustImpl traverseIntMapWithKeyWithAdjust
130− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
131− traverseDMapWithKeyWithAdjust = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap
132− traverseDMapWithKeyWithAdjustWithMove = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove
133−
134−{-# INLINABLE mapIntMapWithAdjustImpl #-}
135−mapIntMapWithAdjustImpl :: forall t m v v' p. (Reflex t, MonadFix m, MonadHold t m, Functor p)
136− => ( (IntMap.Key -> (Event t (), v) -> m v')
137− -> IntMap (Event t (), v)
138− -> Event t (p (Event t (), v))
139− -> m (IntMap v', Event t (p v'))
140− )
141− -> (IntMap.Key -> v -> PostBuildT t m v')
142− -> IntMap v
143− -> Event t (p v)
144− -> PostBuildT t m (IntMap v', Event t (p v'))
145−mapIntMapWithAdjustImpl base f dm0 dm' = do
146− postBuild <- getPostBuild
147− let loweredDm0 = fmap ((,) postBuild) dm0
148− f' :: IntMap.Key -> (Event t (), v) -> m v'
149− f' k (e, v) = do
150− runPostBuildT (f k v) e
151− lift $ do
152− rec (result0, result') <- base f' loweredDm0 loweredDm'
153− cohortDone <- numberOccurrencesFrom_ 1 result'
154− numberedDm' <- numberOccurrencesFrom 1 dm'
155− let postBuild' = fanInt $ fmapCheap (`IntMap.singleton` ()) cohortDone
156− loweredDm' = flip pushAlways numberedDm' $ \(n, p) -> do
157− return $ fmap ((,) (selectInt postBuild' n)) p
158− return (result0, result')
159−
160−{-# INLINABLE mapDMapWithAdjustImpl #-}
161−mapDMapWithAdjustImpl :: forall t m k v v' p. (Reflex t, MonadFix m, MonadHold t m)
162− => ( (forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a))
163− -> DMap k (Compose ((,) (Bool, Event t ())) v)
164− -> Event t (p k (Compose ((,) (Bool, Event t ())) v))
165− -> m (DMap k v', Event t (p k v'))
166− )
167− -> ((forall a. v a -> Compose ((,) (Bool, Event t ())) v a) -> p k v -> p k (Compose ((,) (Bool, Event t ())) v))
168− -> (forall a. k a -> v a -> PostBuildT t m (v' a))
169− -> DMap k v
170− -> Event t (p k v)
171− -> PostBuildT t m (DMap k v', Event t (p k v'))
172−mapDMapWithAdjustImpl base mapPatch f dm0 dm' = do
173− postBuild <- getPostBuild
174− let loweredDm0 = DMap.map (Compose . (,) (False, postBuild)) dm0
175− f' :: forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a)
176− f' k (Compose ((shouldHeadE, e), v)) = do
177− eOnce <- if shouldHeadE
178− then headE e --TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence
179− else return e
180− runPostBuildT (f k v) eOnce
181− lift $ do
182− rec (result0, result') <- base f' loweredDm0 loweredDm'
183− let voidResult' = fmapCheap (\_ -> ()) result'
184− let loweredDm' = ffor dm' $ mapPatch (Compose . (,) (True, voidResult'))
185− return (result0, result')
186−
187−--------------------------------------------------------------------------------
188−-- Deprecated functionality
189−--------------------------------------------------------------------------------
190−
191−-- | Deprecated
192−instance TransControl.MonadTransControl (PostBuildT t) where
193− type StT (PostBuildT t) a = TransControl.StT (ReaderT (Event t ())) a
194− {-# INLINABLE liftWith #-}
195− liftWith = TransControl.defaultLiftWith PostBuildT unPostBuildT
196− {-# INLINABLE restoreT #-}
197− restoreT = TransControl.defaultRestoreT PostBuildT
src/Reflex/PostBuild/Class.hsdeleted−42
@@ -1,42 +0,0 @@
1−-- | This module defines 'PostBuild', which indicates that an action will be
2−-- notified when it, and any action it's a part of, has finished executing.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE DataKinds #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE FunctionalDependencies #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE TypeOperators #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−#ifdef USE_REFLEX_OPTIMIZER
13−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
14−#endif
15−module Reflex.PostBuild.Class
16− ( PostBuild (..)
17− ) where
18−
19−import Reflex.Class
20−
21−import Control.Monad.Reader
22−import Control.Monad.State
23−import qualified Control.Monad.State.Strict as Strict
24−
25−-- | 'PostBuild' represents an action that is notified via an 'Event' when it
26−-- has finished executing. Note that the specific definition of "finished" is
27−-- determined by the instance of 'PostBuild', but the intent is to allow
28−-- 'Behavior's and 'Dynamic's to be safely sampled, regardless of where they
29−-- were created, when the post-build 'Event' fires. The post-build 'Event' will
30−-- fire exactly once for an given action.
31−class (Reflex t, Monad m) => PostBuild t m | m -> t where
32− -- | Retrieve the post-build 'Event' for this action.
33− getPostBuild :: m (Event t ())
34−
35−instance PostBuild t m => PostBuild t (ReaderT r m) where
36− getPostBuild = lift getPostBuild
37−
38−instance PostBuild t m => PostBuild t (StateT s m) where
39− getPostBuild = lift getPostBuild
40−
41−instance PostBuild t m => PostBuild t (Strict.StateT s m) where
42− getPostBuild = lift getPostBuild
src/Reflex/Profiled.hsdeleted−219
@@ -1,219 +0,0 @@
1−{-# LANGUAGE EmptyDataDecls #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE InstanceSigs #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE StandaloneDeriving #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−-- |
12−-- Module:
13−-- Reflex.Profiled
14−-- Description:
15−-- This module contains an instance of the 'Reflex' class that provides
16−-- profiling/cost-center information.
17−module Reflex.Profiled where
18−
19−import Control.Lens hiding (children)
20−import Control.Monad
21−import Control.Monad.Exception
22−import Control.Monad.Fix
23−import Control.Monad.Primitive
24−import Control.Monad.Reader
25−import Control.Monad.Ref
26−import Control.Monad.State.Strict (StateT, execStateT, modify)
27−import Data.Coerce
28−import Data.Dependent.Map (DMap, GCompare)
29−import Data.FastMutableIntMap
30−import Data.IORef
31−import Data.List
32−import Data.Map (Map)
33−import qualified Data.Map.Strict as Map
34−import Data.Monoid ((<>))
35−import Data.Ord
36−import qualified Data.Semigroup as S
37−import Data.Type.Coercion
38−import Foreign.Ptr
39−import GHC.Foreign
40−import GHC.IO.Encoding
41−import GHC.Stack
42−import Reflex.Class
43−import Reflex.Host.Class
44−import Reflex.PerformEvent.Class
45−
46−import System.IO.Unsafe
47−import Unsafe.Coerce
48−
49−data ProfiledTimeline t
50−
51−{-# NOINLINE profilingData #-}
52−profilingData :: IORef (Map (Ptr CostCentreStack) Int)
53−profilingData = unsafePerformIO $ newIORef Map.empty
54−
55−data CostCentreTree = CostCentreTree
56− { _costCentreTree_ownEntries :: !Int
57− , _costCentreTree_cumulativeEntries :: !Int
58− , _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
59− }
60− deriving (Show, Eq, Ord)
61−
62−instance S.Semigroup CostCentreTree where
63− (CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
64− CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
65−
66−instance Monoid CostCentreTree where
67− mempty = CostCentreTree 0 0 mempty
68− mappend = (S.<>)
69−
70−getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
71−getCostCentreStack = go []
72− where go l ccs = if ccs == nullPtr
73− then return l
74− else do
75− cc <- ccsCC ccs
76− parent <- ccsParent ccs
77− go (cc : l) parent
78−
79−toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
80−toCostCentreTree ccs n = do
81− ccList <- getCostCentreStack ccs
82− return $ foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty) ccList
83−
84−getCostCentreTree :: IO CostCentreTree
85−getCostCentreTree = do
86− vals <- readIORef profilingData
87− mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
88−
89−formatCostCentreTree :: CostCentreTree -> IO String
90−formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
91− where go :: Int -> CostCentreTree -> StateT [String] IO ()
92− go depth cct = do
93− let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
94− indent = mconcat $ replicate depth " "
95− forM_ children $ \(cc, childCct) -> do
96− lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
97− mdl <- liftIO $ peekCString utf8 =<< ccModule cc
98− loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
99− let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
100− modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
101− go (succ depth) childCct
102−
103−showProfilingData :: IO ()
104−showProfilingData = do
105− putStr =<< formatCostCentreTree =<< getCostCentreTree
106−
107−writeProfilingData :: FilePath -> IO ()
108−writeProfilingData p = do
109− writeFile p =<< formatCostCentreTree =<< getCostCentreTree
110−
111−newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
112− deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
113−
114−profileEvent :: Reflex t => Event t a -> Event t a
115−profileEvent e = unsafePerformIO $ do
116− stack <- getCurrentCCS e
117− let f x = unsafePerformIO $ do
118− modifyIORef' profilingData $ Map.insertWith (+) stack 1
119− return $ return $ Just x
120− return $ pushCheap f e
121−
122−--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
123−
124−instance Reflex t => Reflex (ProfiledTimeline t) where
125− newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
126− newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
127− newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
128− newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
129− type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
130− type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
131− never = Event_Profiled never
132− constant = Behavior_Profiled . constant
133− push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
134− pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
135− pull = Behavior_Profiled . pull . coerce
136− merge :: forall k. GCompare k => DMap k (Event (ProfiledTimeline t)) -> Event (ProfiledTimeline t) (DMap k Identity)
137− merge = Event_Profiled . merge . (unsafeCoerce :: DMap k (Event (ProfiledTimeline t)) -> DMap k (Event t))
138− fan (Event_Profiled e) = EventSelector $ coerce $ select (fan $ profileEvent e)
139− switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
140− coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
141− current (Dynamic_Profiled d) = coerce $ current d
142− updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
143− unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
144− unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
145− mergeIncremental = Event_Profiled . mergeIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchDMap k (Event (ProfiledTimeline t))) -> Incremental t (PatchDMap k (Event t)))
146− mergeIncrementalWithMove = Event_Profiled . mergeIncrementalWithMove . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchDMapWithMove k (Event (ProfiledTimeline t))) -> Incremental t (PatchDMapWithMove k (Event t)))
147− currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
148− updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
149− incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
150− behaviorCoercion (c :: Coercion a b) = case behaviorCoercion c :: Coercion (Behavior t a) (Behavior t b) of
151− Coercion -> unsafeCoerce (Coercion :: Coercion (Behavior (ProfiledTimeline t) a) (Behavior (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
152− eventCoercion (c :: Coercion a b) = case eventCoercion c :: Coercion (Event t a) (Event t b) of
153− Coercion -> unsafeCoerce (Coercion :: Coercion (Event (ProfiledTimeline t) a) (Event (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
154− dynamicCoercion (c :: Coercion a b) = case dynamicCoercion c :: Coercion (Dynamic t a) (Dynamic t b) of
155− Coercion -> unsafeCoerce (Coercion :: Coercion (Dynamic (ProfiledTimeline t) a) (Dynamic (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
156− mergeIntIncremental = Event_Profiled . mergeIntIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchIntMap (Event (ProfiledTimeline t) a)) -> Incremental t (PatchIntMap (Event t a)))
157− fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
158−
159−deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
160−deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
161−deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
162−
163−instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
164− hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
165− holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
166− holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
167− buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
168− headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
169−
170−instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
171− sample (Behavior_Profiled b) = ProfiledM $ sample b
172−
173−instance MonadTrans ProfiledM where
174− lift = ProfiledM
175−
176−instance MonadIO m => MonadIO (ProfiledM m) where
177− liftIO = lift . liftIO
178−
179−instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
180− type Performable (ProfiledM m) = Performable m
181− performEvent_ = lift . performEvent_ . coerce
182− performEvent = lift . fmap coerce . performEvent . coerce
183−
184−instance MonadRef m => MonadRef (ProfiledM m) where
185− type Ref (ProfiledM m) = Ref m
186− newRef = lift . newRef
187− readRef = lift . readRef
188− writeRef r = lift . writeRef r
189−
190−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
191− newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
192− newFanEventWithTrigger f = do
193− es <- lift $ newFanEventWithTrigger f
194− return $ EventSelector $ \k -> coerce $ select es k
195−
196−instance MonadReader r m => MonadReader r (ProfiledM m) where
197− ask = lift ask
198− local f (ProfiledM a) = ProfiledM $ local f a
199− reader = lift . reader
200−
201−instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
202− type EventTrigger (ProfiledTimeline t) = EventTrigger t
203− type EventHandle (ProfiledTimeline t) = EventHandle t
204− type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
205−
206−instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
207− subscribeEvent = lift . subscribeEvent . coerce
208−
209−instance PrimMonad m => PrimMonad (ProfiledM m) where
210− type PrimState (ProfiledM m) = PrimState m
211− primitive = lift . primitive
212−
213−instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
214− type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
215− fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
216− runHostFrame = lift . runHostFrame . coerce
217−
218−instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
219− readEvent = lift . fmap coerce . readEvent
src/Reflex/Pure.hsdeleted−208
@@ -1,208 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE EmptyDataDecls #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE InstanceSigs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TypeFamilies #-}
8−#ifdef USE_REFLEX_OPTIMIZER
9−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10−#endif
11−
12−-- There are two expected orphan instances in this module:
13−-- * MonadSample (Pure t) ((->) t)
14−-- * MonadHold (Pure t) ((->) t)
15−{-# OPTIONS_GHC -fno-warn-orphans #-}
16−-- |
17−-- Module: Reflex.Pure
18−-- Description:
19−-- This module provides a pure implementation of Reflex, which is intended to
20−-- serve as a reference for the semantics of the Reflex class. All
21−-- implementations of Reflex should produce the same results as this
22−-- implementation, although performance and laziness/strictness may differ.
23−module Reflex.Pure
24− ( Pure
25− , Behavior (..)
26− , Event (..)
27− , Dynamic (..)
28− , Incremental (..)
29− ) where
30−
31−#if !MIN_VERSION_base(4,8,0)
32−import Control.Applicative
33−#endif
34−
35−import Control.Monad
36−import Data.Dependent.Map (DMap, GCompare)
37−import qualified Data.Dependent.Map as DMap
38−import Data.Functor.Identity
39−import Data.IntMap (IntMap)
40−import qualified Data.IntMap as IntMap
41−import Data.Maybe
42−import Data.MemoTrie
43−import Data.Monoid
44−import Data.Type.Coercion
45−import Reflex.Class
46−
47−-- | A completely pure-functional 'Reflex' timeline, identifying moments in time
48−-- with the type @/t/@.
49−data Pure t
50−
51−-- | The 'Enum' instance of @/t/@ must be dense: for all @/x :: t/@, there must not exist
52−-- any @/y :: t/@ such that @/'pred' x < y < x/@. The 'HasTrie' instance will be used
53−-- exclusively to memoize functions of @/t/@, not for any of its other capabilities.
54−instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where
55−
56− newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }
57− newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }
58− newtype Dynamic (Pure t) a = Dynamic { unDynamic :: t -> (a, Maybe a) }
59− newtype Incremental (Pure t) p = Incremental { unIncremental :: t -> (PatchTarget p, Maybe p) }
60−
61− type PushM (Pure t) = (->) t
62− type PullM (Pure t) = (->) t
63−
64− never :: Event (Pure t) a
65− never = Event $ \_ -> Nothing
66−
67− constant :: a -> Behavior (Pure t) a
68− constant x = Behavior $ \_ -> x
69−
70− push :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
71− push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t
72−
73− pushCheap :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
74− pushCheap = push
75−
76− pull :: PullM (Pure t) a -> Behavior (Pure t) a
77− pull = Behavior . memo
78−
79− -- [UNUSED_CONSTRAINT]: The following type signature for merge will produce a
80− -- warning because the GCompare instance is not used; however, removing the
81− -- GCompare instance produces a different warning, due to that constraint
82− -- being present in the original class definition
83−
84− --merge :: GCompare k => DMap k (Event (Pure t)) -> Event (Pure t) (DMap k Identity)
85− merge events = Event $ memo $ \t ->
86− let currentOccurrences = DMap.mapMaybeWithKey (\_ (Event a) -> Identity <$> a t) events
87− in if DMap.null currentOccurrences
88− then Nothing
89− else Just currentOccurrences
90−
91− fan :: GCompare k => Event (Pure t) (DMap k Identity) -> EventSelector (Pure t) k
92− fan e = EventSelector $ \k -> Event $ \t -> unEvent e t >>= fmap runIdentity . DMap.lookup k
93−
94− switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a
95− switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
96−
97− coincidence :: Event (Pure t) (Event (Pure t) a) -> Event (Pure t) a
98− coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
99−
100− current :: Dynamic (Pure t) a -> Behavior (Pure t) a
101− current d = Behavior $ \t -> fst $ unDynamic d t
102−
103− updated :: Dynamic (Pure t) a -> Event (Pure t) a
104− updated d = Event $ \t -> snd $ unDynamic d t
105−
106− unsafeBuildDynamic :: PullM (Pure t) a -> Event (Pure t) a -> Dynamic (Pure t) a
107− unsafeBuildDynamic readV0 v' = Dynamic $ \t -> (readV0 t, unEvent v' t)
108−
109− -- See UNUSED_CONSTRAINT, above.
110−
111− --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p
112− --a) -> Incremental (Pure t) p a
113− unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)
114−
115− mergeIncremental = mergeIncrementalImpl
116− mergeIncrementalWithMove = mergeIncrementalImpl
117−
118− currentIncremental i = Behavior $ \t -> fst $ unIncremental i t
119−
120− updatedIncremental i = Event $ \t -> snd $ unIncremental i t
121−
122− incrementalToDynamic i = Dynamic $ \t ->
123− let (old, mPatch) = unIncremental i t
124− e = case mPatch of
125− Nothing -> Nothing
126− Just patch -> apply patch old
127− in (old, e)
128− behaviorCoercion Coercion = Coercion
129− eventCoercion Coercion = Coercion
130− dynamicCoercion Coercion = Coercion
131−
132− fanInt e = EventSelectorInt $ \k -> Event $ \t -> unEvent e t >>= IntMap.lookup k
133−
134− mergeIntIncremental = mergeIntIncrementalImpl
135−
136−mergeIncrementalImpl :: (PatchTarget p ~ DMap k (Event (Pure t)), GCompare k) => Incremental (Pure t) p -> Event (Pure t) (DMap k Identity)
137−mergeIncrementalImpl i = Event $ \t ->
138− let results = DMap.mapMaybeWithKey (\_ (Event e) -> Identity <$> e t) $ fst $ unIncremental i t
139− in if DMap.null results
140− then Nothing
141− else Just results
142−
143−mergeIntIncrementalImpl :: (PatchTarget p ~ IntMap (Event (Pure t) a)) => Incremental (Pure t) p -> Event (Pure t) (IntMap a)
144−mergeIntIncrementalImpl i = Event $ \t ->
145− let results = IntMap.mapMaybeWithKey (\_ (Event e) -> e t) $ fst $ unIncremental i t
146− in if IntMap.null results
147− then Nothing
148− else Just results
149−
150−instance Functor (Dynamic (Pure t)) where
151− fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t
152− in (f cur, fmap f upd)
153−
154−instance Applicative (Dynamic (Pure t)) where
155− pure a = Dynamic $ \_ -> (a, Nothing)
156− (<*>) = ap
157−
158−instance Monad (Dynamic (Pure t)) where
159− return = pure
160− (x :: Dynamic (Pure t) a) >>= (f :: a -> Dynamic (Pure t) b) = Dynamic $ \t ->
161− let (curX :: a, updX :: Maybe a) = unDynamic x t
162− (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t
163− (updInner :: Maybe b, updBoth :: Maybe b) = case updX of
164− Nothing -> (Nothing, Nothing)
165− Just nextX -> let (c, u) = unDynamic (f nextX) t
166− in (Just c, u)
167− in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])
168−
169−instance MonadSample (Pure t) ((->) t) where
170−
171− sample :: Behavior (Pure t) a -> (t -> a)
172− sample = unBehavior
173−
174−instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
175−
176− hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a
177− hold initialValue e initialTime = Behavior f
178− where f = memo $ \sampleTime ->
179− -- Really, the sampleTime should never be prior to the initialTime,
180− -- because that would mean the Behavior is being sampled before
181− -- being created.
182− if sampleTime <= initialTime
183− then initialValue
184− else let lastTime = pred sampleTime
185− in fromMaybe (f lastTime) $ unEvent e lastTime
186−
187− holdDyn v0 = buildDynamic (return v0)
188−
189− buildDynamic :: (t -> a) -> Event (Pure t) a -> t -> Dynamic (Pure t) a
190− buildDynamic initialValue e initialTime =
191− let Behavior f = hold (initialValue initialTime) e initialTime
192− in Dynamic $ \t -> (f t, unEvent e t)
193−
194− holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p
195− holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)
196− where f = memo $ \sampleTime ->
197− -- Really, the sampleTime should never be prior to the initialTime,
198− -- because that would mean the Behavior is being sampled before
199− -- being created.
200− if sampleTime <= initialTime
201− then initialValue
202− else let lastTime = pred sampleTime
203− lastValue = f lastTime
204− in case unEvent e lastTime of
205− Nothing -> lastValue
206− Just x -> fromMaybe lastValue $ apply x lastValue
207−
208− headE = slowHeadE
src/Reflex/Query/Base.hsdeleted−342
@@ -1,342 +0,0 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3−{-# LANGUAGE InstanceSigs #-}
4−{-# LANGUAGE KindSignatures #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−{-# LANGUAGE StandaloneDeriving #-}
12−
13−module Reflex.Query.Base
14− ( QueryT (..)
15− , runQueryT
16− , mapQuery
17− , mapQueryResult
18− , dynWithQueryT
19− , withQueryT
20− , mapQueryT
21− ) where
22−
23−import Control.Applicative (liftA2)
24−import Control.Monad.Exception
25−import Control.Monad.Fix
26−import Control.Monad.Primitive
27−import Control.Monad.Reader
28−import Control.Monad.Ref
29−import Control.Monad.State.Strict
30−import Data.Align
31−import Data.Dependent.Map (DMap, DSum (..))
32−import qualified Data.Dependent.Map as DMap
33−import Data.Foldable
34−import Data.Functor.Compose
35−import Data.Functor.Misc
36−import Data.IntMap (IntMap)
37−import qualified Data.IntMap as IntMap
38−import Data.Map (Map)
39−import qualified Data.Map as Map
40−import Data.Monoid ((<>))
41−import qualified Data.Semigroup as S
42−import Data.Some (Some)
43−import qualified Data.Some as Some
44−import Data.These
45−
46−import Reflex.Class
47−import Reflex.Adjustable.Class
48−import Reflex.DynamicWriter.Class
49−import Reflex.EventWriter.Base
50−import Reflex.EventWriter.Class
51−import Reflex.Host.Class
52−import qualified Reflex.Patch.MapWithMove as MapWithMove
53−import Reflex.PerformEvent.Class
54−import Reflex.PostBuild.Class
55−import Reflex.Query.Class
56−import Reflex.Requester.Class
57−import Reflex.TriggerEvent.Class
58−
59−newtype QueryT t q m a = QueryT { unQueryT :: StateT [Behavior t q] (EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m)) a }
60− deriving (Functor, Applicative, Monad, MonadException, MonadFix, MonadIO, MonadAtomicRef)
61−
62−deriving instance MonadHold t m => MonadHold t (QueryT t q m)
63−deriving instance MonadSample t m => MonadSample t (QueryT t q m)
64−
65−runQueryT :: (MonadFix m, Additive q, Group q, Reflex t) => QueryT t q m a -> Dynamic t (QueryResult q) -> m (a, Incremental t (AdditivePatch q))
66−runQueryT (QueryT a) qr = do
67− ((r, bs), es) <- runReaderT (runEventWriterT (runStateT a mempty)) qr
68− return (r, unsafeBuildIncremental (foldlM (\b c -> (b <>) <$> sample c) mempty bs) (fmapCheap AdditivePatch es))
69−
70−newtype QueryTLoweredResult t q v = QueryTLoweredResult (v, [Behavior t q])
71−
72−getQueryTLoweredResultValue :: QueryTLoweredResult t q v -> v
73−getQueryTLoweredResultValue (QueryTLoweredResult (v, _)) = v
74−
75−getQueryTLoweredResultWritten :: QueryTLoweredResult t q v -> [Behavior t q]
76−getQueryTLoweredResultWritten (QueryTLoweredResult (_, w)) = w
77−
78−maskMempty :: (Eq a, Monoid a) => a -> Maybe a
79−maskMempty x = if x == mempty then Nothing else Just x
80−
81−instance (Reflex t, MonadFix m, Group q, Additive q, Query q, Eq q, MonadHold t m, Adjustable t m) => Adjustable t (QueryT t q m) where
82− runWithReplace (QueryT a0) a' = do
83− ((r0, bs0), r') <- QueryT $ lift $ runWithReplace (runStateT a0 []) $ fmapCheap (flip runStateT [] . unQueryT) a'
84− let sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
85− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
86− bs' = fmapCheap snd $ r'
87− bbs <- hold bs0 bs'
88− let patches = flip pushCheap bs' $ \newBs -> do
89− oldBs <- sample bbs
90− maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
91− QueryT $ modify $ (:) $ pull $ sampleBs =<< sample bbs
92− QueryT $ lift $ tellEvent patches
93− return (r0, fmapCheap fst r')
94−
95− traverseIntMapWithKeyWithAdjust :: forall v v'. (IntMap.Key -> v -> QueryT t q m v') -> IntMap v -> Event t (PatchIntMap v) -> QueryT t q m (IntMap v', Event t (PatchIntMap v'))
96− traverseIntMapWithKeyWithAdjust f im0 im' = do
97− let f' :: IntMap.Key -> v -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (QueryTLoweredResult t q v')
98− f' k v = fmap QueryTLoweredResult $ flip runStateT [] $ unQueryT $ f k v
99− (result0, result') <- QueryT $ lift $ traverseIntMapWithKeyWithAdjust f' im0 im'
100− let liftedResult0 = IntMap.map getQueryTLoweredResultValue result0
101− liftedResult' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
102− IntMap.map (fmap getQueryTLoweredResultValue) p
103− liftedBs0 :: IntMap [Behavior t q]
104− liftedBs0 = IntMap.map getQueryTLoweredResultWritten result0
105− liftedBs' :: Event t (PatchIntMap [Behavior t q])
106− liftedBs' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
107− IntMap.map (fmap getQueryTLoweredResultWritten) p
108− sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
109− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
110− accumBehaviors :: forall m'. MonadHold t m'
111− => IntMap [Behavior t q]
112− -> PatchIntMap [Behavior t q]
113− -> m' ( Maybe (IntMap [Behavior t q])
114− , Maybe (AdditivePatch q))
115− -- f accumulates the child behavior state we receive from running traverseIntMapWithKeyWithAdjust for the underlying monad.
116− -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
117− -- bs0 is a Map denoting the behaviors of the current children.
118− -- pbs is a PatchMap denoting an update to the behaviors of the current children
119− accumBehaviors bs0 pbs@(PatchIntMap bs') = do
120− let p k bs = case IntMap.lookup k bs0 of
121− Nothing -> case bs of
122− -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
123− Nothing -> return mempty
124− -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
125− Just newBs -> sampleBs newBs
126− Just oldBs -> case bs of
127− -- If the update is to delete the state for a child that already exists, the patch is the negation of the child's current state
128− Nothing -> negateG <$> sampleBs oldBs
129− -- If the update is to update the state for a child that already exists, the patch is the negation of sampling the child's current state
130− -- composed with the sampling the child's new state.
131− Just newBs -> (~~) <$> sampleBs newBs <*> sampleBs oldBs
132− -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
133− -- child patches and wrap them in AdditivePatch.
134− patch <- AdditivePatch . fold <$> IntMap.traverseWithKey p bs'
135− return (apply pbs bs0, Just patch)
136− (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
137− tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
138− return (liftedResult0, liftedResult')
139−
140− traverseDMapWithKeyWithAdjust :: forall (k :: * -> *) v v'. (DMap.GCompare k) => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMap k v) -> QueryT t q m (DMap k v', Event t (PatchDMap k v'))
141− traverseDMapWithKeyWithAdjust f dm0 dm' = do
142− let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
143− f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
144− (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjust f' dm0 dm'
145− let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
146− liftedResult' = fforCheap result' $ \(PatchDMap p) -> PatchDMap $
147− mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (getQueryTLoweredResultValue . getCompose) mr)) p
148− liftedBs0 :: Map (Some k) [Behavior t q]
149− liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some.This k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
150− liftedBs' :: Event t (PatchMap (Some k) [Behavior t q])
151− liftedBs' = fforCheap result' $ \(PatchDMap p) -> PatchMap $
152− Map.fromDistinctAscList $ (\(k :=> ComposeMaybe mr) -> (Some.This k, fmap (getQueryTLoweredResultWritten . getCompose) mr)) <$> DMap.toList p
153− sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
154− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
155− accumBehaviors :: forall m'. MonadHold t m'
156− => Map (Some k) [Behavior t q]
157− -> PatchMap (Some k) [Behavior t q]
158− -> m' ( Maybe (Map (Some k) [Behavior t q])
159− , Maybe (AdditivePatch q))
160− -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjust for the underlying monad.
161− -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
162− -- bs0 is a Map denoting the behaviors of the current children.
163− -- pbs is a PatchMap denoting an update to the behaviors of the current children
164− accumBehaviors bs0 pbs@(PatchMap bs') = do
165− let p k bs = case Map.lookup k bs0 of
166− Nothing -> case bs of
167− -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
168− Nothing -> return Nothing
169− -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
170− Just newBs -> maskMempty <$> sampleBs newBs
171− Just oldBs -> case bs of
172− -- If the update is to delete the state for a child that already exists, the patch is the negation of the child's current state
173− Nothing -> maskMempty . negateG <$> sampleBs oldBs
174− -- If the update is to update the state for a child that already exists, the patch is the negation of sampling the child's current state
175− -- composed with the sampling the child's new state.
176− Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
177− -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
178− -- child patches and wrap them in AdditivePatch.
179− patch <- fold <$> Map.traverseWithKey p bs'
180− return (apply pbs bs0, AdditivePatch <$> patch)
181− (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
182− tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
183− return (liftedResult0, liftedResult')
184−
185− traverseDMapWithKeyWithAdjustWithMove :: forall (k :: * -> *) v v'. (DMap.GCompare k) => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMapWithMove k v) -> QueryT t q m (DMap k v', Event t (PatchDMapWithMove k v'))
186− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
187− let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
188− f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
189− (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjustWithMove f' dm0 dm'
190− let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
191− liftedResult' = fforCheap result' $ mapPatchDMapWithMove (getQueryTLoweredResultValue . getCompose)
192− liftedBs0 :: Map (Some k) [Behavior t q]
193− liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some.This k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
194− liftedBs' :: Event t (PatchMapWithMove (Some k) [Behavior t q])
195− liftedBs' = fforCheap result' $ weakenPatchDMapWithMoveWith (getQueryTLoweredResultWritten . getCompose) {- \(PatchDMap p) -> PatchMapWithMove $
196− Map.fromDistinctAscList $ (\(k :=> mr) -> (Some.This k, fmap (fmap (getQueryTLoweredResultWritten . getCompose)) mr)) <$> DMap.toList p -}
197− sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
198− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
199− accumBehaviors' :: forall m'. MonadHold t m'
200− => Map (Some k) [Behavior t q]
201− -> PatchMapWithMove (Some k) [Behavior t q]
202− -> m' ( Maybe (Map (Some k) [Behavior t q])
203− , Maybe (AdditivePatch q))
204− -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjustWithMove for the underlying monad.
205− -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
206− -- bs0 is a Map denoting the behaviors of the current children.
207− -- pbs is a PatchMapWithMove denoting an update to the behaviors of the current children
208− accumBehaviors' bs0 pbs = do
209− let bs' = unPatchMapWithMove pbs
210− p k bs = case Map.lookup k bs0 of
211− Nothing -> case MapWithMove._nodeInfo_from bs of
212− -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
213− MapWithMove.From_Delete -> return Nothing
214− -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
215− MapWithMove.From_Insert newBs -> maskMempty <$> sampleBs newBs
216− MapWithMove.From_Move k' -> case Map.lookup k' bs0 of
217− Nothing -> return Nothing
218− Just newBs -> maskMempty <$> sampleBs newBs
219− Just oldBs -> case MapWithMove._nodeInfo_from bs of
220− -- If the update is to delete the state for a child that already exists, the patch is the negation of the child's current state
221− MapWithMove.From_Delete -> maskMempty . negateG <$> sampleBs oldBs
222− -- If the update is to update the state for a child that already exists, the patch is the negation of sampling the child's current state
223− -- composed with the sampling the child's new state.
224− MapWithMove.From_Insert newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
225− MapWithMove.From_Move k'
226− | k' == k -> return Nothing
227− | otherwise -> case Map.lookup k' bs0 of
228− -- If we are moving from a non-existent key, that is a delete
229− Nothing -> maskMempty . negateG <$> sampleBs oldBs
230− Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
231− -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
232− -- child patches and wrap them in AdditivePatch.
233− patch <- fold <$> Map.traverseWithKey p bs'
234− return (apply pbs bs0, AdditivePatch <$> patch)
235− (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors' liftedBs0 liftedBs'
236− tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
237− return (liftedResult0, liftedResult')
238−
239−instance MonadTrans (QueryT t q) where
240− lift = QueryT . lift . lift . lift
241−
242−instance PrimMonad m => PrimMonad (QueryT t q m) where
243− type PrimState (QueryT t q m) = PrimState m
244− primitive = lift . primitive
245−
246−instance PostBuild t m => PostBuild t (QueryT t q m) where
247− getPostBuild = lift getPostBuild
248−
249−instance (MonadAsyncException m) => MonadAsyncException (QueryT t q m) where
250− mask f = QueryT $ mask $ \unMask -> unQueryT $ f $ QueryT . unMask . unQueryT
251−
252−instance TriggerEvent t m => TriggerEvent t (QueryT t q m) where
253− newTriggerEvent = lift newTriggerEvent
254− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
255− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
256−
257−instance PerformEvent t m => PerformEvent t (QueryT t q m) where
258− type Performable (QueryT t q m) = Performable m
259− performEvent_ = lift . performEvent_
260− performEvent = lift . performEvent
261−
262−instance MonadRef m => MonadRef (QueryT t q m) where
263− type Ref (QueryT t q m) = Ref m
264− newRef = QueryT . newRef
265− readRef = QueryT . readRef
266− writeRef r = QueryT . writeRef r
267−
268−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (QueryT t q m) where
269− newEventWithTrigger = QueryT . newEventWithTrigger
270− newFanEventWithTrigger a = QueryT . lift $ newFanEventWithTrigger a
271−
272−-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
273−instance (Monoid a, Monad m) => Monoid (QueryT t q m a) where
274− mempty = pure mempty
275− mappend = (<>)
276−
277−instance (S.Semigroup a, Monad m) => S.Semigroup (QueryT t q m a) where
278− (<>) = liftA2 (S.<>)
279−
280−-- | withQueryT's QueryMorphism argument needs to be a group homomorphism in order to behave correctly
281−withQueryT :: (MonadFix m, PostBuild t m, Group q, Group q', Additive q, Additive q', Query q')
282− => QueryMorphism q q'
283− -> QueryT t q m a
284− -> QueryT t q' m a
285−withQueryT f a = do
286− r' <- askQueryResult
287− (result, q) <- lift $ runQueryT a $ mapQueryResult f <$> r'
288− tellQueryIncremental $ unsafeBuildIncremental
289− (fmap (mapQuery f) (sample (currentIncremental q)))
290− (fmapCheap (AdditivePatch . mapQuery f . unAdditivePatch) $ updatedIncremental q)
291− return result
292−
293−-- | Maps a function over a 'QueryT' that can change the underlying monad
294−mapQueryT :: (forall b. m b -> n b) -> QueryT t q m a -> QueryT t q n a
295−mapQueryT f (QueryT a) = QueryT $ mapStateT (mapEventWriterT (mapReaderT f)) a
296−
297−-- | dynWithQueryT's (Dynamic t QueryMorphism) argument needs to be a group homomorphism at all times in order to behave correctly
298−dynWithQueryT :: (MonadFix m, PostBuild t m, Group q, Additive q, Group q', Additive q', Query q')
299− => Dynamic t (QueryMorphism q q')
300− -> QueryT t q m a
301− -> QueryT t q' m a
302−dynWithQueryT f q = do
303− r' <- askQueryResult
304− (result, q') <- lift $ runQueryT q $ zipDynWith mapQueryResult f r'
305− tellQueryIncremental $ zipDynIncrementalWith mapQuery f q'
306− return result
307− where zipDynIncrementalWith g da ib =
308− let eab = align (updated da) (updatedIncremental ib)
309− ec = flip push eab $ \case
310− This a -> do
311− aOld <- sample $ current da
312− b <- sample $ currentIncremental ib
313− return $ Just $ AdditivePatch (g a b ~~ g aOld b)
314− That (AdditivePatch b) -> do
315− a <- sample $ current da
316− return $ Just $ AdditivePatch $ g a b
317− These a (AdditivePatch b) -> do
318− aOld <- sample $ current da
319− bOld <- sample $ currentIncremental ib
320− return $ Just $ AdditivePatch $ mconcat [ g a bOld, negateG (g aOld bOld), g a b]
321− in unsafeBuildIncremental (g <$> sample (current da) <*> sample (currentIncremental ib)) ec
322−
323−instance (Monad m, Group q, Additive q, Query q, Reflex t) => MonadQuery t q (QueryT t q m) where
324− tellQueryIncremental q = do
325− QueryT (modify (currentIncremental q:))
326− QueryT (lift (tellEvent (fmapCheap unAdditivePatch (updatedIncremental q))))
327− askQueryResult = QueryT ask
328− queryIncremental q = do
329− tellQueryIncremental q
330− zipDynWith crop (incrementalToDynamic q) <$> askQueryResult
331−
332−instance Requester t m => Requester t (QueryT t q m) where
333− type Request (QueryT t q m) = Request m
334− type Response (QueryT t q m) = Response m
335− requesting = lift . requesting
336− requesting_ = lift . requesting_
337−
338−instance EventWriter t w m => EventWriter t w (QueryT t q m) where
339− tellEvent = lift . tellEvent
340−
341−instance DynamicWriter t w m => DynamicWriter t w (QueryT t q m) where
342− tellDyn = lift . tellDyn
src/Reflex/Query/Class.hsdeleted−119
@@ -1,119 +0,0 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE TypeFamilies #-}
8−{-# LANGUAGE UndecidableInstances #-}
9−-- |
10−-- Module:
11−-- Reflex.Query.Class
12−-- Description:
13−-- A class that ties together queries to some data source and their results,
14−-- providing methods for requesting data from the source and accumulating
15−-- streamed results.
16−module Reflex.Query.Class
17− ( Query (..)
18− , QueryMorphism (..)
19− , SelectedCount (..)
20− , combineSelectedCounts
21−
22− , MonadQuery (..)
23− , tellQueryDyn
24− , queryDyn
25− , mapQuery
26− , mapQueryResult
27− ) where
28−
29−import Control.Category (Category)
30−import qualified Control.Category as Cat
31−import Control.Monad.Reader
32−import Data.Bits
33−import Data.Data
34−import Data.Ix
35−import Data.Map.Monoidal (MonoidalMap)
36−import qualified Data.Map.Monoidal as MonoidalMap
37−import Data.Semigroup (Semigroup(..))
38−import Foreign.Storable
39−
40−import Reflex.Class
41−
42−-- | A 'Query' can be thought of as a declaration of interest in some set of data.
43−-- A 'QueryResult' is the set of data associated with that interest set.
44−-- The @crop@ function provides a way to determine what part of a given 'QueryResult'
45−-- is relevant to a given 'Query'.
46−class (Monoid (QueryResult a), Semigroup (QueryResult a)) => Query a where
47− type QueryResult a :: *
48− crop :: a -> QueryResult a -> QueryResult a
49−
50−instance (Ord k, Query v) => Query (MonoidalMap k v) where
51− type QueryResult (MonoidalMap k v) = MonoidalMap k (QueryResult v)
52− crop q r = MonoidalMap.intersectionWith (flip crop) r q
53−
54−-- | QueryMorphism's must be group homomorphisms when acting on the query type
55−-- and compatible with the query relationship when acting on the query result.
56−data QueryMorphism q q' = QueryMorphism
57− { _queryMorphism_mapQuery :: q -> q'
58− , _queryMorphism_mapQueryResult :: QueryResult q' -> QueryResult q
59− }
60−
61−instance Category QueryMorphism where
62− id = QueryMorphism id id
63− qm . qm' = QueryMorphism
64− { _queryMorphism_mapQuery = mapQuery qm . mapQuery qm'
65− , _queryMorphism_mapQueryResult = mapQueryResult qm' . mapQueryResult qm
66− }
67−
68−-- | Apply a 'QueryMorphism' to a 'Query'
69−mapQuery :: QueryMorphism q q' -> q -> q'
70−mapQuery = _queryMorphism_mapQuery
71−
72−-- | Map a 'QueryMorphism' to a 'QueryResult'
73−mapQueryResult :: QueryMorphism q q' -> QueryResult q' -> QueryResult q
74−mapQueryResult = _queryMorphism_mapQueryResult
75−
76−-- | This type can be used to track of the frequency of interest in a given 'Query'. See note on
77−-- 'combineSelectedCounts'
78−newtype SelectedCount = SelectedCount { unSelectedCount :: Int }
79− deriving (Eq, Ord, Show, Read, Integral, Num, Bounded, Enum, Real, Ix, Bits, FiniteBits, Storable, Data)
80−
81−instance Semigroup SelectedCount where
82− SelectedCount a <> SelectedCount b = SelectedCount (a + b)
83−
84−instance Monoid SelectedCount where
85− mempty = SelectedCount 0
86− mappend = (<>)
87−
88−instance Group SelectedCount where
89− negateG (SelectedCount a) = SelectedCount (negate a)
90−
91−instance Additive SelectedCount
92−
93−-- | The Semigroup/Monoid/Group instances for a Query containing 'SelectedCount's should use
94−-- this function which returns Nothing if the result is 0. This allows the pruning of leaves
95−-- of the 'Query' that are no longer wanted.
96−combineSelectedCounts :: SelectedCount -> SelectedCount -> Maybe SelectedCount
97−combineSelectedCounts (SelectedCount i) (SelectedCount j) = if i == negate j then Nothing else Just $ SelectedCount (i + j)
98−
99−-- | A class that allows sending of 'Query's and retrieval of 'QueryResult's. See 'queryDyn' for a commonly
100−-- used interface.
101−class (Group q, Additive q, Query q) => MonadQuery t q m | m -> q t where
102− tellQueryIncremental :: Incremental t (AdditivePatch q) -> m ()
103− askQueryResult :: m (Dynamic t (QueryResult q))
104− queryIncremental :: Incremental t (AdditivePatch q) -> m (Dynamic t (QueryResult q))
105−
106−instance (Monad m, MonadQuery t q m) => MonadQuery t q (ReaderT r m) where
107− tellQueryIncremental = lift . tellQueryIncremental
108− askQueryResult = lift askQueryResult
109− queryIncremental = lift . queryIncremental
110−
111−-- | Produce and send an 'Incremental' 'Query' from a 'Dynamic' 'Query'.
112−tellQueryDyn :: (Reflex t, MonadQuery t q m) => Dynamic t q -> m ()
113−tellQueryDyn d = tellQueryIncremental $ unsafeBuildIncremental (sample (current d)) $ attachWith (\old new -> AdditivePatch $ new ~~ old) (current d) (updated d)
114−
115−-- | Retrieve 'Dynamic'ally updating 'QueryResult's for a 'Dynamic'ally updating 'Query'.
116−queryDyn :: (Reflex t, Monad m, MonadQuery t q m) => Dynamic t q -> m (Dynamic t (QueryResult q))
117−queryDyn q = do
118− tellQueryDyn q
119− zipDynWith crop q <$> askQueryResult
src/Reflex/Requester/Base.hsdeleted−538
@@ -1,538 +0,0 @@
1−-- | This module provides 'RequesterT', the standard implementation of
2−-- 'Requester'.
3−{-# LANGUAGE AllowAmbiguousTypes #-}
4−{-# LANGUAGE CPP #-}
5−{-# LANGUAGE EmptyDataDecls #-}
6−{-# LANGUAGE ExistentialQuantification #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10−{-# LANGUAGE MultiParamTypeClasses #-}
11−{-# LANGUAGE Rank2Types #-}
12−{-# LANGUAGE RecursiveDo #-}
13−{-# LANGUAGE ScopedTypeVariables #-}
14−{-# LANGUAGE StandaloneDeriving #-}
15−{-# LANGUAGE TypeFamilies #-}
16−{-# LANGUAGE TypeOperators #-}
17−{-# LANGUAGE UndecidableInstances #-}
18−#ifdef USE_REFLEX_OPTIMIZER
19−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20−#endif
21−module Reflex.Requester.Base
22− ( RequesterT (..)
23− , runRequesterT
24− , withRequesterT
25− , runWithReplaceRequesterTWith
26− , traverseIntMapWithKeyWithAdjustRequesterTWith
27− , traverseDMapWithKeyWithAdjustRequesterTWith
28− , RequesterData
29− , RequesterDataKey
30− , traverseRequesterData
31− , forRequesterData
32− , requesterDataToList
33− , singletonRequesterData
34− , matchResponsesWithRequests
35− , multiEntry
36− , unMultiEntry
37− , requesting'
38− ) where
39−
40−import Reflex.Class
41−import Reflex.Adjustable.Class
42−import Reflex.Dynamic
43−import Reflex.Host.Class
44−import Reflex.PerformEvent.Class
45−import Reflex.PostBuild.Class
46−import Reflex.Requester.Class
47−import Reflex.TriggerEvent.Class
48−
49−import Control.Applicative (liftA2)
50−import Control.Monad.Exception
51−import Control.Monad.Identity
52−import Control.Monad.Primitive
53−import Control.Monad.Reader
54−import Control.Monad.Ref
55−import Control.Monad.State.Strict
56−import Data.Bits
57−import Data.Coerce
58−import Data.Dependent.Map (DMap, DSum (..))
59−import qualified Data.Dependent.Map as DMap
60−import Data.Functor.Compose
61−import Data.Functor.Misc
62−import Data.IntMap.Strict (IntMap)
63−import qualified Data.IntMap.Strict as IntMap
64−import Data.Map (Map)
65−import qualified Data.Map as Map
66−import Data.Monoid ((<>))
67−import Data.Proxy
68−import qualified Data.Semigroup as S
69−import Data.Some (Some)
70−import qualified Data.Some as Some
71−import Data.Type.Equality
72−import Data.Unique.Tag
73−
74−import GHC.Exts (Any)
75−import Unsafe.Coerce
76−
77−--TODO: Make this module type-safe
78−
79−newtype TagMap (f :: * -> *) = TagMap (IntMap Any)
80−
81−newtype RequesterData f = RequesterData (TagMap (Entry f))
82−
83−data RequesterDataKey a where
84− RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a
85− RequesterDataKey_Multi :: {-# UNPACK #-} !(MyTag Multi) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a --TODO: Don't put a second Int here (or in the other Multis); use a single Int instead
86− RequesterDataKey_Multi2 :: {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
87− RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
88−
89−singletonRequesterData :: RequesterDataKey a -> f a -> RequesterData f
90−singletonRequesterData rdk v = case rdk of
91− RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v
92− RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v
93− RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
94− RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
95−
96−requesterDataToList :: RequesterData f -> [DSum RequesterDataKey f]
97−requesterDataToList (RequesterData m) = do
98− k :=> Entry e <- tagMapToList m
99− case myKeyType k of
100− MyTagType_Single -> return $ RequesterDataKey_Single k :=> e
101− MyTagType_Multi -> do
102− (k', e') <- IntMap.toList e
103− k'' :=> e'' <- requesterDataToList e'
104− return $ RequesterDataKey_Multi k k' k'' :=> e''
105− MyTagType_Multi2 -> do
106− (k', e') <- Map.toList e
107− (k'', e'') <- IntMap.toList e'
108− k''' :=> e''' <- requesterDataToList e''
109− return $ RequesterDataKey_Multi2 k k' k'' k''' :=> e'''
110− MyTagType_Multi3 -> do
111− (k', e') <- IntMap.toList e
112− (k'', e'') <- IntMap.toList e'
113− k''' :=> e''' <- requesterDataToList e''
114− return $ RequesterDataKey_Multi3 k k' k'' k''' :=> e'''
115−
116−singletonTagMap :: forall f a. MyTag a -> f a -> TagMap f
117−singletonTagMap (MyTag k) v = TagMap $ IntMap.singleton k $ (unsafeCoerce :: f a -> Any) v
118−
119−tagMapToList :: forall f. TagMap f -> [DSum MyTag f]
120−tagMapToList (TagMap m) = f <$> IntMap.toList m
121− where f :: (Int, Any) -> DSum MyTag f
122− f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v
123−
124−traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g)
125−traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m
126− where
127− g :: Int -> Any -> t Any
128− g k v = (unsafeCoerce :: g a -> Any) <$> f (MyTag k) ((unsafeCoerce :: Any -> f a) v)
129−
130−-- | Runs in reverse to accommodate for the fact that we accumulate it in reverse
131−traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response)
132−traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order
133− where go :: forall x. MyTag x -> Entry request x -> m (Entry response x)
134− go k (Entry request) = Entry <$> case myKeyType k of
135− MyTagType_Single -> f request
136− MyTagType_Multi -> traverse (traverseRequesterData f) request
137− MyTagType_Multi2 -> traverse (traverse (traverseRequesterData f)) request
138− MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request
139−
140−-- | 'traverseRequesterData' with its arguments flipped
141−forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response)
142−forRequesterData r f = traverseRequesterData f r
143−
144−data MyTagType :: * -> * where
145− MyTagType_Single :: MyTagType (Single a)
146− MyTagType_Multi :: MyTagType Multi
147− MyTagType_Multi2 :: MyTagType (Multi2 k)
148− MyTagType_Multi3 :: MyTagType Multi3
149−
150−myKeyType :: MyTag x -> MyTagType x
151−myKeyType (MyTag k) = case k .&. 0x3 of
152− 0x0 -> unsafeCoerce MyTagType_Single
153− 0x1 -> unsafeCoerce MyTagType_Multi
154− 0x2 -> unsafeCoerce MyTagType_Multi2
155− 0x3 -> unsafeCoerce MyTagType_Multi3
156− t -> error $ "Reflex.Requester.Base.myKeyType: no such key type" <> show t
157−
158−data Single a
159−data Multi
160−data Multi2 (k :: * -> *)
161−data Multi3
162−
163−class MyTagTypeOffset x where
164− myTagTypeOffset :: proxy x -> Int
165−
166−instance MyTagTypeOffset (Single a) where
167− myTagTypeOffset _ = 0x0
168−
169−instance MyTagTypeOffset Multi where
170− myTagTypeOffset _ = 0x1
171−
172−instance MyTagTypeOffset (Multi2 k) where
173− myTagTypeOffset _ = 0x2
174−
175−instance MyTagTypeOffset Multi3 where
176− myTagTypeOffset _ = 0x3
177−
178−type family EntryContents request a where
179− EntryContents request (Single a) = request a
180− EntryContents request Multi = IntMap (RequesterData request)
181− EntryContents request (Multi2 k) = Map (Some k) (IntMap (RequesterData request))
182− EntryContents request Multi3 = IntMap (IntMap (RequesterData request))
183−
184−newtype Entry request x = Entry { unEntry :: EntryContents request x }
185−
186−{-# INLINE singleEntry #-}
187−singleEntry :: f a -> Entry f (Single a)
188−singleEntry = Entry
189−
190−{-# INLINE multiEntry #-}
191−multiEntry :: IntMap (RequesterData f) -> Entry f Multi
192−multiEntry = Entry
193−
194−{-# INLINE unMultiEntry #-}
195−unMultiEntry :: Entry f Multi -> IntMap (RequesterData f)
196−unMultiEntry = unEntry
197−
198−-- | We use a hack here to pretend we have x ~ request a; we don't want to use a GADT, because GADTs (even with zero-size existential contexts) can't be newtypes
199−-- WARNING: This type should never be exposed. In particular, this is extremely unsound if a MyTag from one run of runRequesterT is ever compared against a MyTag from another
200−newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum)
201−
202−newtype MyTagWrap (f :: * -> *) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum)
203−
204−{-# INLINE castMyTagWrap #-}
205−castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x)
206−castMyTagWrap = coerce
207−
208−instance GEq MyTag where
209− (MyTag a) `geq` (MyTag b) =
210− if a == b
211− then Just $ unsafeCoerce Refl
212− else Nothing
213−
214−instance GCompare MyTag where
215− (MyTag a) `gcompare` (MyTag b) =
216− case a `compare` b of
217− LT -> GLT
218− EQ -> unsafeCoerce GEQ
219− GT -> GGT
220−
221−instance GEq (MyTagWrap f) where
222− (MyTagWrap a) `geq` (MyTagWrap b) =
223− if a == b
224− then Just $ unsafeCoerce Refl
225− else Nothing
226−
227−instance GCompare (MyTagWrap f) where
228− (MyTagWrap a) `gcompare` (MyTagWrap b) =
229− case a `compare` b of
230− LT -> GLT
231− EQ -> unsafeCoerce GEQ
232− GT -> GGT
233−
234−data RequesterState t (request :: * -> *) = RequesterState
235− { _requesterState_nextMyTag :: {-# UNPACK #-} !Int -- Starts at -4 and goes down by 4 each time, to accommodate two 'type' bits at the bottom
236− , _requesterState_requests :: ![(Int, Event t Any)]
237− }
238−
239−-- | A basic implementation of 'Requester'.
240−newtype RequesterT t request (response :: * -> *) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a }
241− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
242−-- MonadAsyncException can't be derived on ghc-8.0.1; we use base-4.9.1 as a proxy for ghc-8.0.2
243−#if MIN_VERSION_base(4,9,1)
244− , MonadAsyncException
245−#endif
246− )
247−
248−deriving instance MonadSample t m => MonadSample t (RequesterT t request response m)
249−deriving instance MonadHold t m => MonadHold t (RequesterT t request response m)
250−deriving instance PostBuild t m => PostBuild t (RequesterT t request response m)
251−deriving instance TriggerEvent t m => TriggerEvent t (RequesterT t request response m)
252−
253−instance PrimMonad m => PrimMonad (RequesterT t request response m) where
254− type PrimState (RequesterT t request response m) = PrimState m
255− primitive = lift . primitive
256−
257−-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
258−instance (Monoid a, Monad m) => Monoid (RequesterT t request response m a) where
259− mempty = pure mempty
260− mappend = liftA2 mappend
261−
262−instance (S.Semigroup a, Monad m) => S.Semigroup (RequesterT t request response m a) where
263− (<>) = liftA2 (S.<>)
264−
265−
266−-- | Run a 'RequesterT' action. The resulting 'Event' will fire whenever
267−-- requests are made, and responses should be provided in the input 'Event'.
268−-- The 'Tag' keys will be used to return the responses to the same place the
269−-- requests were issued.
270−runRequesterT :: (Reflex t, Monad m)
271− => RequesterT t request response m a
272− -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse
273− -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild
274−runRequesterT (RequesterT a) responses = do
275− (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $
276− coerceEvent responses
277− return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s)
278−
279−-- | Map a function over the request and response of a 'RequesterT'
280−withRequesterT
281− :: (Reflex t, MonadFix m)
282− => (forall x. req x -> req' x) -- ^ The function to map over the request
283− -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response
284− -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed
285− -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT'
286−withRequesterT freq frsp child = do
287− rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp'
288− (a, req) <- lift $ runRequesterT child rsp
289− rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $
290− fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req
291− return a
292−
293−instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where
294− type Request (RequesterT t request response m) = request
295− type Response (RequesterT t request response m) = response
296− requesting = fmap coerceEvent . responseFromTag . castMyTagWrap <=< tagRequest . (coerceEvent :: Event t (request a) -> Event t (Entry request (Single a)))
297− requesting_ = void . tagRequest . fmapCheap singleEntry
298−
299−{-# INLINE tagRequest #-}
300−tagRequest :: forall m x t request response. (Monad m, MyTagTypeOffset x) => Event t (Entry request x) -> RequesterT t request response m (MyTagWrap request (Entry request x))
301−tagRequest req = do
302− old <- RequesterT get
303− let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x)
304− t = MyTagWrap n
305− RequesterT $ put $ RequesterState
306− { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4
307− , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old
308− }
309− return t
310−
311−{-# INLINE responseFromTag #-}
312−responseFromTag :: Monad m => MyTagWrap response (Entry response x) -> RequesterT t request response m (Event t (Entry response x))
313−responseFromTag (MyTagWrap t) = do
314− responses :: EventSelectorInt t Any <- RequesterT ask
315− return $ (unsafeCoerce :: Event t Any -> Event t (Entry response x)) $ selectInt responses t
316−
317−instance MonadTrans (RequesterT t request response) where
318− lift = RequesterT . lift . lift
319−
320−instance PerformEvent t m => PerformEvent t (RequesterT t request response m) where
321− type Performable (RequesterT t request response m) = Performable m
322− performEvent_ = lift . performEvent_
323− performEvent = lift . performEvent
324−
325−instance MonadRef m => MonadRef (RequesterT t request response m) where
326− type Ref (RequesterT t request response m) = Ref m
327− newRef = lift . newRef
328− readRef = lift . readRef
329− writeRef r = lift . writeRef r
330−
331−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequesterT t request response m) where
332− newEventWithTrigger = lift . newEventWithTrigger
333− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
334−
335−instance MonadReader r m => MonadReader r (RequesterT t request response m) where
336− ask = lift ask
337− local f (RequesterT a) = RequesterT $ mapStateT (mapReaderT $ local f) a
338− reader = lift . reader
339−
340−instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where
341− runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
342− traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental
343− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
344− traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental
345− traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove
346−
347−requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x))
348−requesting' = responseFromTag . castMyTagWrap <=< tagRequest
349−
350−{-# INLINABLE runWithReplaceRequesterTWith #-}
351−runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m
352− , MonadFix m
353− )
354− => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))
355− -> RequesterT t request response m a
356− -> Event t (RequesterT t request response m b)
357− -> RequesterT t request response m (a, Event t b)
358−runWithReplaceRequesterTWith f a0 a' = do
359− rec na' <- numberOccurrencesFrom 1 a'
360− responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here
361− let responses' = fanInt responses
362− ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na'
363− requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v'
364− return (result0, fmapCheap (fst . snd) v')
365−
366−{-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-}
367−traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p.
368− ( Reflex t
369− , MonadHold t m
370− , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))
371− , Patch (p (Event t (IntMap (RequesterData request))))
372− , Functor p
373− , MonadFix m
374− )
375− => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))
376− -> IntMap (IntMap.Key, v)
377− -> Event t (p (IntMap.Key, v))
378− -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))
379− )
380− -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))
381− -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))
382− -> (IntMap.Key -> v -> RequesterT t request response m v')
383− -> IntMap v
384− -> Event t (p v)
385− -> RequesterT t request response m (IntMap v', Event t (p v'))
386−traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do
387− rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
388− let responses :: EventSelectorInt t (IntMap (RequesterData response))
389− responses = fanInt $ fmapCheap unpack response
390− unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response))
391− unpack = unEntry
392− pack :: IntMap (IntMap (RequesterData request)) -> Entry request Multi3
393− pack = Entry
394− f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v')
395− f' k (n, v) = do
396− (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ selectInt responses k --TODO: Instead of doing mapMaybeCheap, can we share a fanInt across all instances of a given key, or at least the ones that are adjacent in time?
397− return (fmapCheap (IntMap.singleton n) myRequests, result)
398− ndm' <- numberOccurrencesFrom 1 dm'
399− (children0, children') <- base f' (fmap ((,) 0) dm0) $ fmap (\(n, dm) -> fmap ((,) n) dm) ndm' --TODO: Avoid this somehow, probably by adding some sort of per-cohort information passing to Adjustable
400− let result0 = fmap snd children0
401− result' = fforCheap children' $ fmap snd
402− requests0 :: IntMap (Event t (IntMap (RequesterData request)))
403− requests0 = fmap fst children0
404− requests' :: Event t (p (Event t (IntMap (RequesterData request))))
405− requests' = fforCheap children' $ fmap fst
406− promptRequests :: Event t (IntMap (IntMap (RequesterData request)))
407− promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
408− requests <- holdIncremental requests0 requests'
409− return (result0, result')
410−
411−{-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-}
412−traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'.
413− ( GCompare k
414− , Reflex t
415− , MonadHold t m
416− , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))
417− , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))
418− , MonadFix m
419− )
420− => (forall k' v1 v2. GCompare k'
421− => (forall a. k' a -> v1 a -> m (v2 a))
422− -> DMap k' v1
423− -> Event t (p k' v1)
424− -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))
425− )
426− -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)
427− -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)
428− -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)
429− -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))
430− -> (forall a. k a -> v a -> RequesterT t request response m (v' a))
431− -> DMap k v
432− -> Event t (p k v)
433− -> RequesterT t request response m (DMap k v', Event t (p k v'))
434−traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do
435− rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
436− let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response)))
437− responses = fanMap $ fmapCheap unpack response
438− unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response))
439− unpack = unEntry
440− pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k)
441− pack = Entry
442− f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a)
443− f' k (Compose (n, v)) = do
444− (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some.This k))
445− return $ Compose (fmapCheap (IntMap.singleton n) myRequests, result)
446− ndm' <- numberOccurrencesFrom 1 dm'
447− (children0, children') <- base f' (DMap.map (\v -> Compose (0, v)) dm0) $ fmap (\(n, dm) -> mapPatch (\v -> Compose (n, v)) dm) ndm'
448− let result0 = DMap.map (snd . getCompose) children0
449− result' = fforCheap children' $ mapPatch $ snd . getCompose
450− requests0 :: Map (Some k) (Event t (IntMap (RequesterData request)))
451− requests0 = weakenDMapWith (fst . getCompose) children0
452− requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request))))
453− requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
454− promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request)))
455− promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
456− requests <- holdIncremental requests0 requests'
457− return (result0, result')
458−
459−data Decoder rawResponse response =
460− forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)
461−
462−-- | Matches incoming responses with previously-sent requests
463−-- and uses the provided request "decoder" function to process
464−-- incoming responses.
465−matchResponsesWithRequests
466− :: forall t rawRequest rawResponse request response m.
467− ( MonadFix m
468− , MonadHold t m
469− , Reflex t
470− )
471− => (forall a. request a -> (rawRequest, rawResponse -> response a))
472− -- ^ Given a request (from 'Requester'), produces the wire format of the
473− -- request and a function used to process the associated response
474− -> Event t (RequesterData request)
475− -- ^ The outgoing requests
476− -> Event t (Int, rawResponse)
477− -- ^ The incoming responses, tagged by an identifying key
478− -> m ( Event t (Map Int rawRequest)
479− , Event t (RequesterData response)
480− )
481− -- ^ A map of outgoing wire-format requests and an event of responses keyed
482− -- by the 'RequesterData' key of the associated outgoing request
483−matchResponsesWithRequests f send recv = do
484− rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing
485− waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <-
486− holdIncremental mempty $ leftmost
487− [ fmap (\(_, outstanding, _) -> outstanding) outgoing
488− , snd <$> incoming
489− ]
490− let outgoing = processOutgoing nextId send
491− incoming = processIncoming waitingFor recv
492− return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming)
493− where
494− -- Tags each outgoing request with an identifying integer key
495− -- and returns the next available key, a map of response decoders
496− -- for requests for which there are outstanding responses, and the
497− -- raw requests to be sent out.
498− processOutgoing
499− :: Behavior t Int
500− -- The next available key
501− -> Event t (RequesterData request)
502− -- The outgoing request
503− -> Event t ( Int
504− , PatchMap Int (Decoder rawResponse response)
505− , Map Int rawRequest )
506− -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests
507− processOutgoing nextId out = flip pushAlways out $ \dm -> do
508− oldNextId <- sample nextId
509− let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do
510− n <- get
511− put $ succ n
512− let (rawReq, rspF) = f v
513− return (n, rawReq, Decoder k rspF)
514− patchWaitingFor = PatchMap $ Map.fromList $
515− (\(n, _, dec) -> (n, Just dec)) <$> result
516− toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result
517− return (newNextId, patchWaitingFor, toSend)
518− -- Looks up the each incoming raw response in a map of response
519− -- decoders and returns the decoded response and a patch that can
520− -- be used to clear the ID of the consumed response out of the queue
521− -- of expected responses.
522− processIncoming
523− :: Incremental t (PatchMap Int (Decoder rawResponse response))
524− -- A map of outstanding expected responses
525− -> Event t (Int, rawResponse)
526− -- A incoming response paired with its identifying key
527− -> Event t (RequesterData response, PatchMap Int v)
528− -- The decoded response and a patch that clears the outstanding responses queue
529− processIncoming waitingFor inc = flip push inc $ \(n, rawRsp) -> do
530− wf <- sample $ currentIncremental waitingFor
531− case Map.lookup n wf of
532− Nothing -> return Nothing -- TODO How should lookup failures be handled here? They shouldn't ever happen..
533− Just (Decoder k rspF) -> do
534− let rsp = rspF rawRsp
535− return $ Just
536− ( singletonRequesterData k rsp
537− , PatchMap $ Map.singleton n Nothing
538− )
src/Reflex/Requester/Class.hsdeleted−73
@@ -1,73 +0,0 @@
1−-- | This module defines 'Requester', which indicates that an action can make
2−-- requests and receive responses to them. Typically, this is used for things
3−-- like a WebSocket, where it's desirable to collect many potential sources of
4−-- events and send them over a single channel, then distribute the results back
5−-- out efficiently to their original request sites.
6−{-# LANGUAGE CPP #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE RecursiveDo #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−module Reflex.Requester.Class
17− ( Requester (..)
18− , withRequesting
19− , requestingIdentity
20− ) where
21−
22−import Control.Monad.Identity
23−import Control.Monad.Reader
24−import qualified Control.Monad.State.Lazy as Lazy
25−import Control.Monad.State.Strict
26−import Reflex.Class
27−
28−-- | A 'Requester' action can trigger requests of type @Request m a@ based on
29−-- 'Event's, and receive responses of type @Response m a@ in return. Note that
30−-- the @a@ type can vary within the 'Requester' action, but will be linked for a
31−-- given request. For example, if @Request m@ is 'IO' and @Response m@ is
32−-- 'Identity', then 'requestingIdentity' has the same type as
33−-- 'Reflex.PerformEvent.Class.performEvent'.
34−class (Reflex t, Monad m) => Requester t m | m -> t where
35− -- | The type of requests that this 'Requester' can emit
36− type Request m :: * -> *
37− -- | The type of responses that this 'Requester' can receive
38− type Response m :: * -> *
39− -- | Emit a request whenever the given 'Event' fires, and return responses in
40− -- the resulting 'Event'.
41− requesting :: Event t (Request m a) -> m (Event t (Response m a))
42− -- | Emit a request whenever the given 'Event' fires, and ignore all responses.
43− requesting_ :: Event t (Request m a) -> m ()
44−
45−
46−instance Requester t m => Requester t (ReaderT r m) where
47− type Request (ReaderT r m) = Request m
48− type Response (ReaderT r m) = Response m
49− requesting = lift . requesting
50− requesting_ = lift . requesting_
51−
52−instance Requester t m => Requester t (StateT s m) where
53− type Request (StateT s m) = Request m
54− type Response (StateT s m) = Response m
55− requesting = lift . requesting
56− requesting_ = lift . requesting_
57−
58−instance Requester t m => Requester t (Lazy.StateT s m) where
59− type Request (Lazy.StateT s m) = Request m
60− type Response (Lazy.StateT s m) = Response m
61− requesting = lift . requesting
62− requesting_ = lift . requesting_
63−
64−-- | Emit a request whenever the given 'Event' fires, and unwrap the responses
65−-- before returning them. @Response m@ must be 'Identity'.
66−requestingIdentity :: (Requester t m, Response m ~ Identity) => Event t (Request m a) -> m (Event t a)
67−requestingIdentity = fmap coerceEvent . requesting
68−
69−withRequesting :: (Requester t m, MonadFix m) => (Event t (Response m a) -> m (Event t (Request m a), r)) -> m r
70−withRequesting f = do
71− rec response <- requesting request
72− (request, result) <- f response
73− return result
src/Reflex/Spider.hsdeleted−20
@@ -1,20 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−-- |
3−-- Module:
4−-- Reflex.Spider
5−-- Description:
6−-- This module exports all of the user-facing functionality of the 'Spider' 'Reflex' engine
7−module Reflex.Spider
8− ( Spider
9− , SpiderTimeline
10− , Global
11− , SpiderHost
12− , runSpiderHost
13− , runSpiderHostForTimeline
14− , newSpiderTimeline
15− , withSpiderTimeline
16− -- * Deprecated
17− , SpiderEnv
18− ) where
19−
20−import Reflex.Spider.Internal
src/Reflex/Spider/Internal.hsdeleted−2641
@@ -1,2641 +0,0 @@
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 MultiParamTypeClasses #-}
13−{-# LANGUAGE MultiWayIf #-}
14−{-# LANGUAGE RankNTypes #-}
15−{-# LANGUAGE RoleAnnotations #-}
16−{-# LANGUAGE ScopedTypeVariables #-}
17−{-# LANGUAGE TypeFamilies #-}
18−{-# LANGUAGE TypeOperators #-}
19−{-# LANGUAGE UndecidableInstances #-}
20−#ifdef USE_REFLEX_OPTIMIZER
21−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
22−#endif
23−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
24−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
25−module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
26−
27−#if MIN_VERSION_base(4,10,0)
28−import Control.Applicative (liftA2)
29−#endif
30−import Control.Concurrent
31−import Control.Exception
32−import Control.Monad hiding (forM, forM_, mapM, mapM_)
33−import Control.Monad.Exception
34−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
35−import Control.Monad.Primitive
36−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
37−import Control.Monad.Ref
38−import Data.Align
39−import Data.Coerce
40−import Data.Dependent.Map (DMap, DSum (..))
41−import qualified Data.Dependent.Map as DMap
42−import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
43−import qualified Data.FastMutableIntMap as FastMutableIntMap
44−import Data.Foldable hiding (concat, elem, sequence_)
45−import Data.Functor.Constant
46−import Data.Functor.Misc
47−import Data.Functor.Product
48−import Data.GADT.Compare
49−import Data.IntMap.Strict (IntMap)
50−import qualified Data.IntMap.Strict as IntMap
51−import Data.IORef
52−import Data.Maybe hiding (mapMaybe)
53−import Data.Monoid ((<>))
54−import Data.Proxy
55−import Data.These
56−import Data.Traversable
57−import Data.Witherable (Filterable, mapMaybe)
58−import GHC.Exts
59−import GHC.IORef (IORef (..))
60−import GHC.Stack
61−import Reflex.FastWeak
62−import System.IO.Unsafe
63−import System.Mem.Weak
64−import Unsafe.Coerce
65−
66−#ifdef DEBUG_CYCLES
67−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
68−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
69−import qualified Data.List.NonEmpty as NonEmpty
70−import Data.Monoid (mempty)
71−import Data.Tree (Forest, Tree (..), drawForest)
72−#endif
73−
74−import Data.FastWeakBag (FastWeakBag)
75−import qualified Data.FastWeakBag as FastWeakBag
76−import Data.Reflection
77−import Data.Some (Some)
78−import qualified Data.Some as Some
79−import Data.Type.Coercion
80−import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
81−import qualified Data.WeakBag as WeakBag
82−import qualified Reflex.Class
83−import qualified Reflex.Class as R
84−import qualified Reflex.Host.Class
85−import Reflex.NotReady.Class
86−import Reflex.Patch
87−import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
88−
89−#ifdef DEBUG_TRACE_EVENTS
90−import qualified Data.ByteString.Char8 as BS8
91−import System.IO (stderr)
92−#endif
93−
94−#ifdef DEBUG_TRACE_EVENTS
95−
96−withStackOneLine :: (BS8.ByteString -> a) -> a
97−withStackOneLine expr = unsafePerformIO $ do
98− stack <- currentCallStack
99− return (expr (BS8.pack (unwords (reverse stack))))
100−
101−#endif
102−
103−debugPropagate :: Bool
104−
105−debugInvalidateHeight :: Bool
106−
107−debugInvalidate :: Bool
108−
109−#ifdef DEBUG
110−
111−#define DEBUG_NODEIDS
112−
113−debugPropagate = True
114−
115−debugInvalidateHeight = False
116−
117−debugInvalidate = True
118−
119−class HasNodeId a where
120− getNodeId :: a -> Int
121−
122−instance HasNodeId (Hold x p a) where
123− getNodeId = holdNodeId
124−
125−instance HasNodeId (PushSubscribed x a b) where
126− getNodeId = pushSubscribedNodeId
127−
128−instance HasNodeId (SwitchSubscribed x a) where
129− getNodeId = switchSubscribedNodeId
130−
131−instance HasNodeId (FanSubscribed x a) where
132− getNodeId = fanSubscribedNodeId
133−
134−instance HasNodeId (CoincidenceSubscribed x a) where
135− getNodeId = coincidenceSubscribedNodeId
136−
137−instance HasNodeId (RootSubscribed x a) where
138− getNodeId = rootSubscribedNodeId
139−
140−instance HasNodeId (Pull x a) where
141− getNodeId = pullNodeId
142−
143−{-# INLINE showNodeId #-}
144−showNodeId :: HasNodeId a => a -> String
145−showNodeId = ("#"<>) . show . getNodeId
146−
147−showSubscriberType :: Subscriber x a -> String
148−showSubscriberType = \case
149− SubscriberPush _ _ -> "SubscriberPush"
150− SubscriberMerge _ _ -> "SubscriberMerge"
151− SubscriberFan _ -> "SubscriberFan"
152− SubscriberMergeChange _ -> "SubscriberMergeChange"
153− SubscriberHold _ -> "SubscriberHold"
154− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
155− SubscriberSwitch _ -> "SubscriberSwitch"
156− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
157− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
158− SubscriberHandle -> "SubscriberHandle"
159−
160−showEventType :: Event x a -> String
161−showEventType = \case
162− EventRoot _ _ -> "EventRoot"
163− EventNever -> "EventNever"
164− EventPush _ -> "EventPush"
165− EventMerge _ -> "EventMerge"
166− EventFan _ _ -> "EventFan"
167− EventSwitch _ -> "EventSwitch"
168− EventCoincidence _ -> "EventCoincidence"
169− EventHold _ -> "EventHold"
170− EventDyn _ -> "EventDyn"
171− EventHoldIdentity _ -> "EventHoldIdentity"
172− EventDynIdentity _ -> "EventDynIdentity"
173−
174−#else
175−
176−debugPropagate = False
177−
178−debugInvalidateHeight = False
179−
180−debugInvalidate = False
181−
182−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
183−{-# INLINE showNodeId #-}
184−showNodeId :: a -> String
185−showNodeId _ = ""
186−
187−#endif
188−
189−#ifdef DEBUG_NODEIDS
190−{-# NOINLINE nextNodeIdRef #-}
191−nextNodeIdRef :: IORef Int
192−nextNodeIdRef = unsafePerformIO $ newIORef 1
193−
194−newNodeId :: IO Int
195−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
196−
197−{-# NOINLINE unsafeNodeId #-}
198−unsafeNodeId :: a -> Int
199−unsafeNodeId a = unsafePerformIO $ do
200− touch a
201− newNodeId
202−#endif
203−
204−--------------------------------------------------------------------------------
205−-- EventSubscription
206−--------------------------------------------------------------------------------
207−
208−--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
209−-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
210−data EventSubscription x = EventSubscription
211− { _eventSubscription_unsubscribe :: !(IO ())
212− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
213− }
214−
215−unsubscribe :: EventSubscription x -> IO ()
216−unsubscribe (EventSubscription u _) = u
217−
218−--------------------------------------------------------------------------------
219−-- Event
220−--------------------------------------------------------------------------------
221−
222−newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
223−
224−{-# INLINE subscribeAndRead #-}
225−subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
226−subscribeAndRead = unEvent
227−
228−{-# RULES
229−"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
230−"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
231−"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
232− #-}
233−
234−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
235−-- caching; if the computation function is very cheap, this is (much) more
236−-- efficient than 'push'
237−{-# INLINE [1] pushCheap #-}
238−pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
239−pushCheap !f e = Event $ \sub -> do
240− (subscription, occ) <- subscribeAndRead e $ sub
241− { subscriberPropagate = \a -> do
242− mb <- f a
243− mapM_ (subscriberPropagate sub) mb
244− }
245− occ' <- join <$> mapM f occ
246− return (subscription, occ')
247−
248−-- | A subscriber that never triggers other 'Event's
249−{-# INLINE terminalSubscriber #-}
250−terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
251−terminalSubscriber p = Subscriber
252− { subscriberPropagate = p
253− , subscriberInvalidateHeight = \_ -> return ()
254− , subscriberRecalculateHeight = \_ -> return ()
255− }
256−
257−-- | Subscribe to an Event only for the duration of one occurrence
258−{-# INLINE subscribeAndReadHead #-}
259−subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
260−subscribeAndReadHead e sub = do
261− subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
262− (subscription, occ) <- subscribeAndRead e $ sub
263− { subscriberPropagate = \a -> do
264− liftIO $ unsubscribe =<< readIORef subscriptionRef
265− subscriberPropagate sub a
266− }
267− liftIO $ case occ of
268− Nothing -> writeIORef subscriptionRef $! subscription
269− Just _ -> unsubscribe subscription
270− return (subscription, occ)
271−
272−--TODO: Make this lazy in its input event
273−headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
274−headE originalE = do
275− parent <- liftIO $ newIORef $ Just originalE
276− defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
277− let clearParent = liftIO $ writeIORef parent Nothing
278− (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
279− when (isJust occ) clearParent
280− return $ Event $ \sub -> do
281− liftIO (readIORef parent) >>= \case
282− Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
283− Just e -> subscribeAndReadHead e sub
284−
285−data CacheSubscribed x a
286− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
287− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
288− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
289− }
290−
291−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
292−-- repeatedly
293−--
294−--TODO: Try a caching strategy where we subscribe directly to the parent when
295−--there's only one subscriber, and then build our own FastWeakBag only when a second
296−--subscriber joins
297−{-# NOINLINE [0] cacheEvent #-}
298−cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
299−cacheEvent e =
300−#ifdef DEBUG_TRACE_EVENTS
301− withStackOneLine $ \callSite -> Event $
302−#else
303− Event $
304−#endif
305− let mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
306− !mSubscribedRef = unsafeNewIORef e emptyFastWeak
307− in \sub -> {-# SCC "cacheEvent" #-} do
308−#ifdef DEBUG_TRACE_EVENTS
309− unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
310−#endif
311− subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
312− Just subscribedTicket -> return subscribedTicket
313− Nothing -> do
314− subscribers <- liftIO FastWeakBag.empty
315− occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
316− (parentSub, occ) <- subscribeAndRead e $ Subscriber
317− { subscriberPropagate = \a -> do
318− liftIO $ writeIORef occRef $ Just a
319− scheduleClear occRef
320− propagateFast a subscribers
321− , subscriberInvalidateHeight = \old -> do
322− FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
323− , subscriberRecalculateHeight = \new -> do
324− FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
325− }
326− when (isJust occ) $ do
327− liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
328− scheduleClear occRef
329− let !subscribed = CacheSubscribed
330− { _cacheSubscribed_subscribers = subscribers
331− , _cacheSubscribed_parent = parentSub
332− , _cacheSubscribed_occurrence = occRef
333− }
334− subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
335− liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
336− return subscribedTicket
337− liftIO $ do
338− subscribed <- getFastWeakTicketValue subscribedTicket
339− ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
340− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
341− let es = EventSubscription
342− { _eventSubscription_unsubscribe = do
343− FastWeakBag.remove ticket
344− isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
345− when isEmpty $ do
346− writeIORef mSubscribedRef emptyFastWeak
347− unsubscribe $ _cacheSubscribed_parent subscribed
348− touch ticket
349− touch subscribedTicket
350− , _eventSubscription_subscribed = EventSubscribed
351− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
352− , eventSubscribedRetained = toAny subscribedTicket
353− }
354− }
355− return (es, occ)
356−
357−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
358−subscribe e s = fst <$> subscribeAndRead e s
359−
360−{-# INLINE wrap #-}
361−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
362−wrap tag getSpecificSubscribed sub = do
363− (sln, subd, occ) <- getSpecificSubscribed sub
364− let es = tag subd
365− return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
366−
367−eventRoot :: GCompare k => k a -> Root x k -> Event x a
368−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
369−
370−eventNever :: Event x a
371−eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
372−
373−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
374−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
375−
376−eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
377−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
378−
379−eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
380−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
381−
382−eventHold :: Hold x p -> Event x p
383−eventHold !h = Event $ subscribeHoldEvent h
384−
385−eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
386−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
387−
388−{-# INLINE subscribeCoincidenceInner #-}
389−subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
390−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
391− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
392− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
393− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
394− let height = max innerHeight outerHeight
395− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
396− return (innerOcc, height, innerSubd)
397−
398−--------------------------------------------------------------------------------
399−-- Subscriber
400−--------------------------------------------------------------------------------
401−
402−data Subscriber x a = Subscriber
403− { subscriberPropagate :: !(a -> EventM x ())
404− , subscriberInvalidateHeight :: !(Height -> IO ())
405− , subscriberRecalculateHeight :: !(Height -> IO ())
406− }
407−
408−--TODO: Move this comment to WeakBag
409−-- These function are constructor functions that are marked NOINLINE so they are
410−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
411−-- so any weak references that are attached to the constructors will have their
412−-- finalizer run. Using the opaque constructor, does not see the
413−-- constructor application, so it behaves like an IORef and cannot be fused away.
414−--
415−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
416−-- the weak pointer to it in some cases.
417−
418−newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
419−newSubscriberHold h = return $ Subscriber
420− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
421− , subscriberInvalidateHeight = \_ -> return ()
422− , subscriberRecalculateHeight = \_ -> return ()
423− }
424−
425−newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
426−newSubscriberFan subscribed = return $ Subscriber
427− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
428− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
429− tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
430− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
431− scheduleClear $ fanSubscribedOccurrence subscribed
432− let f _ (Pair (Identity v) subsubs) = do
433− propagate v $ _fanSubscribedChildren_list subsubs
434− return $ Constant ()
435− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
436− return ()
437− , subscriberInvalidateHeight = \old -> do
438− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
439− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
440− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
441− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
442− , subscriberRecalculateHeight = \new -> do
443− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
444− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
445− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
446− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
447− }
448−
449−newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
450−newSubscriberSwitch subscribed = return $ Subscriber
451− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
452− tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
453− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
454− scheduleClear $ switchSubscribedOccurrence subscribed
455− propagate a $ switchSubscribedSubscribers subscribed
456− , subscriberInvalidateHeight = \_ -> do
457− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
458− oldHeight <- readIORef $ switchSubscribedHeight subscribed
459− when (oldHeight /= invalidHeight) $ do
460− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
461− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
462− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
463− , subscriberRecalculateHeight = \new -> do
464− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
465− updateSwitchHeight new subscribed
466− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
467− }
468−
469−newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
470−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
471− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
472− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
473− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
474− tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
475− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
476− tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
477− tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
478− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
479− scheduleClear $ coincidenceSubscribedInnerParent subscribed
480− case occ of
481− Nothing -> do
482− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
483− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
484− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
485− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
486− Just o -> do -- Since it's already firing, no need to adjust height
487− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
488− scheduleClear $ coincidenceSubscribedOccurrence subscribed
489− propagate o $ coincidenceSubscribedSubscribers subscribed
490− , subscriberInvalidateHeight = \_ -> do
491− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
492− invalidateCoincidenceHeight subscribed
493− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
494− , subscriberRecalculateHeight = \_ -> do
495− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
496− recalculateCoincidenceHeight subscribed
497− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
498− }
499−
500−newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
501−newSubscriberCoincidenceInner subscribed = return $ Subscriber
502− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
503− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
504− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
505− case occ of
506− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
507− Nothing -> do
508− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
509− scheduleClear $ coincidenceSubscribedOccurrence subscribed
510− propagate a $ coincidenceSubscribedSubscribers subscribed
511− , subscriberInvalidateHeight = \_ -> do
512− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
513− invalidateCoincidenceHeight subscribed
514− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
515− , subscriberRecalculateHeight = \_ -> do
516− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
517− recalculateCoincidenceHeight subscribed
518− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
519− }
520−
521−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
522−invalidateSubscriberHeight = flip subscriberInvalidateHeight
523−
524−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
525−recalculateSubscriberHeight = flip subscriberRecalculateHeight
526−
527−-- | Propagate everything at the current height
528−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
529−propagate a subscribers = withIncreasedDepth $ do
530− -- 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
531− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
532− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
533−
534−-- | Propagate everything at the current height
535−propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
536−propagateFast a subscribers = withIncreasedDepth $ do
537− -- 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
538− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
539− FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
540−
541−--------------------------------------------------------------------------------
542−-- EventSubscribed
543−--------------------------------------------------------------------------------
544−
545−toAny :: a -> Any
546−toAny = unsafeCoerce
547−
548−data EventSubscribed x = EventSubscribed
549− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
550− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
551−#ifdef DEBUG_CYCLES
552− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
553− , eventSubscribedHasOwnHeightRef :: !Bool
554− , eventSubscribedWhoCreated :: !(IO [String])
555−#endif
556− }
557−
558−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
559−eventSubscribedRoot !r = EventSubscribed
560− { eventSubscribedHeightRef = zeroRef
561− , eventSubscribedRetained = toAny r
562−#ifdef DEBUG_CYCLES
563− , eventSubscribedGetParents = return []
564− , eventSubscribedHasOwnHeightRef = False
565− , eventSubscribedWhoCreated = return ["root"]
566−#endif
567− }
568−
569−eventSubscribedNever :: EventSubscribed x
570−eventSubscribedNever = EventSubscribed
571− { eventSubscribedHeightRef = zeroRef
572− , eventSubscribedRetained = toAny ()
573−#ifdef DEBUG_CYCLES
574− , eventSubscribedGetParents = return []
575− , eventSubscribedHasOwnHeightRef = False
576− , eventSubscribedWhoCreated = return ["never"]
577−#endif
578− }
579−
580−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
581−eventSubscribedFan !subscribed = EventSubscribed
582− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
583− , eventSubscribedRetained = toAny subscribed
584−#ifdef DEBUG_CYCLES
585− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
586− , eventSubscribedHasOwnHeightRef = False
587− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
588−#endif
589− }
590−
591−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
592−eventSubscribedSwitch !subscribed = EventSubscribed
593− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
594− , eventSubscribedRetained = toAny subscribed
595−#ifdef DEBUG_CYCLES
596− , eventSubscribedGetParents = do
597− s <- readIORef $ switchSubscribedCurrentParent subscribed
598− return [Some.This $ _eventSubscription_subscribed s]
599− , eventSubscribedHasOwnHeightRef = True
600− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
601−#endif
602− }
603−
604−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
605−eventSubscribedCoincidence !subscribed = EventSubscribed
606− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
607− , eventSubscribedRetained = toAny subscribed
608−#ifdef DEBUG_CYCLES
609− , eventSubscribedGetParents = do
610− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
611− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
612− innerParents = maybeToList $ fmap Some.This innerSubscription
613− return $ outerParent : innerParents
614− , eventSubscribedHasOwnHeightRef = True
615− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
616−#endif
617− }
618−
619−getEventSubscribedHeight :: EventSubscribed x -> IO Height
620−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
621−
622−#ifdef DEBUG_CYCLES
623−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
624−whoCreatedEventSubscribed = eventSubscribedWhoCreated
625−
626−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
627−walkInvalidHeightParents s0 = do
628− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
629− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
630− when (h == invalidHeight) $ do
631− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
632− modify (Some.This s :)
633− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
634− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
635− return subscribers
636−#endif
637−
638−{-# INLINE subscribeHoldEvent #-}
639−subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
640−subscribeHoldEvent = subscribeAndRead . holdEvent
641−
642−--------------------------------------------------------------------------------
643−-- Behavior
644−--------------------------------------------------------------------------------
645−
646−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
647−
648−behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
649−behaviorHold !h = Behavior $ readHoldTracked h
650−
651−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
652−behaviorHoldIdentity = behaviorHold
653−
654−behaviorConst :: a -> Behavior x a
655−behaviorConst !a = Behavior $ return a
656−
657−behaviorPull :: Pull x a -> Behavior x a
658−behaviorPull !p = Behavior $ do
659− val <- liftIO $ readIORef $ pullValue p
660− case val of
661− Just subscribed -> do
662− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
663− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
664− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
665− return $ pullSubscribedValue subscribed
666− Nothing -> do
667− i <- liftIO $ newInvalidatorPull p
668− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
669− parentsRef <- liftIO $ newIORef []
670− holdInits <- askBehaviorHoldInits
671− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
672− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
673− parents <- liftIO $ readIORef parentsRef
674− let subscribed = PullSubscribed
675− { pullSubscribedValue = a
676− , pullSubscribedInvalidators = invsRef
677− , pullSubscribedOwnInvalidator = i
678− , pullSubscribedParents = parents
679− }
680− liftIO $ writeIORef (pullValue p) $ Just subscribed
681− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
682− return a
683−
684−behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
685−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
686−
687−{-# INLINE readHoldTracked #-}
688−readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
689−readHoldTracked h = do
690− result <- liftIO $ readIORef $ holdValue h
691− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
692− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
693− liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
694− return result
695−
696−{-# INLINABLE readBehaviorUntracked #-}
697−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
698−readBehaviorUntracked b = do
699− holdInits <- getDeferralQueue
700− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
701−
702−--------------------------------------------------------------------------------
703−-- Dynamic
704−--------------------------------------------------------------------------------
705−
706−data Dynamic x p = Dynamic
707− { dynamicCurrent :: !(Behavior x (PatchTarget p))
708− , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
709− }
710−
711−dynamicHold :: Hold x p -> Dynamic x p
712−dynamicHold !h = Dynamic
713− { dynamicCurrent = behaviorHold h
714− , dynamicUpdated = eventHold h
715− }
716−
717−dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
718−dynamicHoldIdentity = dynamicHold
719−
720−dynamicConst :: PatchTarget p -> Dynamic x p
721−dynamicConst !a = Dynamic
722− { dynamicCurrent = behaviorConst a
723− , dynamicUpdated = eventNever
724− }
725−
726−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
727−dynamicDyn !d = Dynamic
728− { dynamicCurrent = behaviorDyn d
729− , dynamicUpdated = eventDyn d
730− }
731−
732−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
733−dynamicDynIdentity = dynamicDyn
734−
735−--------------------------------------------------------------------------------
736−-- Combinators
737−--------------------------------------------------------------------------------
738−
739−--TODO: Figure out why certain things are not 'representational', then make them
740−--representational so we can use coerce
741−
742−--type role Hold representational
743−data Hold x p
744− = Hold { holdValue :: !(IORef (PatchTarget p))
745− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
746− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
747− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
748−#ifdef DEBUG_NODEIDS
749− , holdNodeId :: Int
750−#endif
751− }
752−
753−-- | A statically allocated 'SpiderTimeline'
754−data Global
755−
756−{-# NOINLINE globalSpiderTimelineEnv #-}
757−globalSpiderTimelineEnv :: SpiderTimelineEnv Global
758−globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
759−
760−-- | Stores all global data relevant to a particular Spider timeline; only one
761−-- value should exist for each type @x@
762−data SpiderTimelineEnv x = SpiderTimelineEnv
763− { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
764− , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
765−#ifdef DEBUG
766− , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
767−#endif
768− }
769−type role SpiderTimelineEnv nominal
770−
771−instance Eq (SpiderTimelineEnv x) where
772− _ == _ = True -- Since only one exists of each type
773−
774−instance GEq SpiderTimelineEnv where
775− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
776− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
777− else Nothing
778−
779−data EventEnv x
780− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
781− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
782− , eventEnvDynInits :: !(IORef [SomeDynInit x])
783− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
784− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
785− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
786− , eventEnvIntClears :: !(IORef [SomeIntClear])
787− , eventEnvRootClears :: !(IORef [SomeRootClear])
788− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
789− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
790− , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
791− }
792−
793−{-# INLINE runEventM #-}
794−runEventM :: EventM x a -> IO a
795−runEventM = unEventM
796−
797−asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
798−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
799−
800−class MonadIO m => Defer a m where
801− getDeferralQueue :: m (IORef [a])
802−
803−{-# INLINE defer #-}
804−defer :: Defer a m => a -> m ()
805−defer a = do
806− q <- getDeferralQueue
807− liftIO $ modifyIORef' q (a:)
808−
809−instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
810− {-# INLINE getDeferralQueue #-}
811− getDeferralQueue = asksEventEnv eventEnvAssignments
812−
813−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
814− {-# INLINE getDeferralQueue #-}
815− getDeferralQueue = asksEventEnv eventEnvHoldInits
816−
817−instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
818− {-# INLINE getDeferralQueue #-}
819− getDeferralQueue = asksEventEnv eventEnvDynInits
820−
821−instance Defer (SomeHoldInit x) (BehaviorM x) where
822− {-# INLINE getDeferralQueue #-}
823− getDeferralQueue = BehaviorM $ asks snd
824−
825−instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
826− {-# INLINE getDeferralQueue #-}
827− getDeferralQueue = asksEventEnv eventEnvMergeUpdates
828−
829−instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
830− {-# INLINE getDeferralQueue #-}
831− getDeferralQueue = asksEventEnv eventEnvMergeInits
832−
833−class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
834− getCurrentHeight :: m Height
835− scheduleMerge :: Height -> EventM x () -> m ()
836−
837−instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
838− {-# INLINE getCurrentHeight #-}
839− getCurrentHeight = do
840− heightRef <- asksEventEnv eventEnvCurrentHeight
841− liftIO $ readIORef heightRef
842− {-# INLINE scheduleMerge #-}
843− scheduleMerge height subscribed = do
844− delayedRef <- asksEventEnv eventEnvDelayedMerges
845− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
846−
847−class HasSpiderTimeline x where
848− -- | Retrieve the current SpiderTimelineEnv
849− spiderTimeline :: SpiderTimelineEnv x
850−
851−instance HasSpiderTimeline Global where
852− spiderTimeline = globalSpiderTimelineEnv
853−
854−putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
855−putCurrentHeight h = do
856− heightRef <- asksEventEnv eventEnvCurrentHeight
857− liftIO $ writeIORef heightRef $! h
858−
859−instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
860− {-# INLINE getDeferralQueue #-}
861− getDeferralQueue = asksEventEnv eventEnvClears
862−
863−{-# INLINE scheduleClear #-}
864−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
865−scheduleClear r = defer $ SomeClear r
866−
867−instance HasSpiderTimeline x => Defer SomeIntClear (EventM x) where
868− {-# INLINE getDeferralQueue #-}
869− getDeferralQueue = asksEventEnv eventEnvIntClears
870−
871−{-# INLINE scheduleIntClear #-}
872−scheduleIntClear :: Defer SomeIntClear m => IORef (IntMap a) -> m ()
873−scheduleIntClear r = defer $ SomeIntClear r
874−
875−instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
876− {-# INLINE getDeferralQueue #-}
877− getDeferralQueue = asksEventEnv eventEnvRootClears
878−
879−{-# INLINE scheduleRootClear #-}
880−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
881−scheduleRootClear r = defer $ SomeRootClear r
882−
883−instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
884− {-# INLINE getDeferralQueue #-}
885− getDeferralQueue = asksEventEnv eventEnvResetCoincidences
886−
887−-- Note: hold cannot examine its event until after the phase is over
888−{-# INLINE [1] hold #-}
889−hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
890−hold v0 e = do
891− valRef <- liftIO $ newIORef v0
892− invsRef <- liftIO $ newIORef []
893− parentRef <- liftIO $ newIORef Nothing
894−#ifdef DEBUG_NODEIDS
895− nodeId <- liftIO newNodeId
896−#endif
897− let h = Hold
898− { holdValue = valRef
899− , holdInvalidators = invsRef
900− , holdEvent = e
901− , holdParent = parentRef
902−#ifdef DEBUG_NODEIDS
903− , holdNodeId = nodeId
904−#endif
905− }
906− defer $ SomeHoldInit h
907− return h
908−
909−{-# INLINE getHoldEventSubscription #-}
910−getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
911−getHoldEventSubscription h = do
912− ep <- liftIO $ readIORef $ holdParent h
913− case ep of
914− Just subd -> return subd
915− Nothing -> do
916− let e = holdEvent h
917− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
918− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
919− liftIO $ writeIORef subscriptionRef $! subscription
920− case occ of
921− Nothing -> return ()
922− Just o -> do
923− old <- liftIO $ readIORef $ holdValue h
924− case apply o old of
925− Nothing -> return ()
926− Just new -> do
927− -- Need to evaluate these so that we don't retain the Hold itself
928− v <- liftIO $ evaluate $ holdValue h
929− i <- liftIO $ evaluate $ holdInvalidators h
930− defer $ SomeAssignment v i new
931− liftIO $ writeIORef (holdParent h) $ Just subscription
932− return subscription
933−
934−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
935−
936−--type role BehaviorM representational
937−-- BehaviorM can sample behaviors
938−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
939−
940−instance Monad (BehaviorM x) where
941− {-# INLINE (>>=) #-}
942− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
943− {-# INLINE (>>) #-}
944− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
945− {-# INLINE return #-}
946− return x = BehaviorM $ return x
947− {-# INLINE fail #-}
948− fail s = BehaviorM $ fail s
949−
950−data BehaviorSubscribed x a
951− = forall p. BehaviorSubscribedHold (Hold x p)
952− | BehaviorSubscribedPull (PullSubscribed x a)
953−
954−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
955−
956−--type role PullSubscribed representational
957−data PullSubscribed x a
958− = PullSubscribed { pullSubscribedValue :: !a
959− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
960− , pullSubscribedOwnInvalidator :: !(Invalidator x)
961− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
962− }
963−
964−--type role Pull representational
965−data Pull x a
966− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
967− , pullCompute :: !(BehaviorM x a)
968−#ifdef DEBUG_NODEIDS
969− , pullNodeId :: Int
970−#endif
971− }
972−
973−data Invalidator x
974− = forall a. InvalidatorPull (Pull x a)
975− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
976−
977−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
978− { rootSubscribedKey :: !(k a)
979− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
980− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
981− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
982− , rootSubscribedUninit :: IO ()
983− , 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?
984−#ifdef DEBUG_NODEIDS
985− , rootSubscribedNodeId :: Int
986−#endif
987− }
988−
989−data Root x (k :: * -> *)
990− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
991− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
992− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
993− }
994−
995−data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
996−
997−data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
998−
999−data SomeMergeUpdate x = SomeMergeUpdate
1000− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1001− , _someMergeUpdate_invalidateHeight :: !(IO ())
1002− , _someMergeUpdate_recalculateHeight :: !(IO ())
1003− }
1004−
1005−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1006−
1007−-- EventM can do everything BehaviorM can, plus create holds
1008−newtype EventM x a = EventM { unEventM :: 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
1009−
1010−newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1011−
1012−data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1013− { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1014− , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1015− }
1016−
1017−data HeightBag = HeightBag
1018− { _heightBag_size :: {-# UNPACK #-} !Int
1019− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1020− }
1021− deriving (Show, Read, Eq, Ord)
1022−
1023−heightBagEmpty :: HeightBag
1024−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1025−
1026−heightBagSize :: HeightBag -> Int
1027−heightBagSize = _heightBag_size
1028−
1029−heightBagFromList :: [Height] -> HeightBag
1030−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1031−
1032−heightBagAdd :: Height -> HeightBag -> HeightBag
1033−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1034−
1035−heightBagRemove :: Height -> HeightBag -> HeightBag
1036−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1037− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1038− Just old -> HeightBag (pred s) $ case old of
1039− 0 -> IntMap.delete h c
1040− _ -> IntMap.insert h (pred old) c
1041−
1042−heightBagMax :: HeightBag -> Height
1043−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1044− Just ((h, _), _) -> Height h
1045− Nothing -> zeroHeight
1046−
1047−heightBagVerify :: HeightBag -> HeightBag
1048−#ifdef DEBUG
1049−heightBagVerify b@(HeightBag s c) = if
1050− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1051− -> error $ "heightBagVerify: size doesn't match: " <> show b
1052− | unHeight invalidHeight `IntMap.member` c
1053− -> error $ "heightBagVerify: contains invalid height: " <> show b
1054− | otherwise -> b
1055−#else
1056−heightBagVerify = id
1057−#endif
1058−
1059−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1060− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1061− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1062− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1063− }
1064−
1065−data FanSubscribed (x :: *) k
1066− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1067− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1068− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1069− , fanSubscribedParent :: !(EventSubscription x)
1070−#ifdef DEBUG_NODEIDS
1071− , fanSubscribedNodeId :: Int
1072−#endif
1073− }
1074−
1075−data Fan x k
1076− = Fan { fanParent :: !(Event x (DMap k Identity))
1077− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1078− }
1079−
1080−data SwitchSubscribed x a
1081− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1082− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1083− , switchSubscribedHeight :: !(IORef Height)
1084− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1085− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1086− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1087− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1088− , switchSubscribedParent :: !(Behavior x (Event x a))
1089− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1090− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1091−#ifdef DEBUG_NODEIDS
1092− , switchSubscribedNodeId :: Int
1093−#endif
1094− }
1095−
1096−data Switch x a
1097− = Switch { switchParent :: !(Behavior x (Event x a))
1098− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1099− }
1100−
1101−#ifdef USE_TEMPLATE_HASKELL
1102−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1103−#endif
1104−data CoincidenceSubscribed x a
1105− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1106− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1107− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1108− , coincidenceSubscribedHeight :: !(IORef Height)
1109− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1110− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1111− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1112− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1113−#ifdef DEBUG_NODEIDS
1114− , coincidenceSubscribedNodeId :: Int
1115−#endif
1116− }
1117−
1118−data Coincidence x a
1119− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1120− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1121− }
1122−
1123−{-# NOINLINE newInvalidatorSwitch #-}
1124−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1125−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1126−
1127−{-# NOINLINE newInvalidatorPull #-}
1128−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1129−newInvalidatorPull p = return $! InvalidatorPull p
1130−
1131−instance HasSpiderTimeline x => Filterable (Event x) where
1132− mapMaybe f = push $ return . f
1133−
1134−instance HasSpiderTimeline x => Align (Event x) where
1135− nil = eventNever
1136−#if MIN_VERSION_these(0, 8, 0)
1137−instance HasSpiderTimeline x => Semialign (Event x) where
1138−#endif
1139− align ea eb = mapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1140−
1141−data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1142− | BuildDyn !(EventM x (PatchTarget p), Event x p)
1143− | HoldDyn !(Hold x p)
1144−
1145−newtype Dyn x p = Dyn { unDyn :: IORef (DynType x p) }
1146−
1147−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1148−newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1149−
1150−--TODO: Avoid the duplication between this and R.zipDynWith
1151−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1152−zipDynWith f da db =
1153− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1154− ec = flip push eab $ \o -> do
1155− (a, b) <- case o of
1156− This (Identity a) -> do
1157− b <- readBehaviorUntracked $ dynamicCurrent db
1158− return (a, b)
1159− That (Identity b) -> do
1160− a <- readBehaviorUntracked $ dynamicCurrent da
1161− return (a, b)
1162− These (Identity a) (Identity b) -> return (a, b)
1163− return $ Just $ Identity $ f a b
1164− in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1165−
1166−buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1167−buildDynamic readV0 v' = do
1168− result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1169− let !d = Dyn result
1170− defer $ SomeDynInit d
1171− return d
1172−
1173−unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1174−unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ UnsafeDyn x
1175− where x = (readV0, v')
1176−
1177−-- ResultM can read behaviors and events
1178−type ResultM = EventM
1179−
1180−{-# NOINLINE unsafeNewIORef #-}
1181−unsafeNewIORef :: a -> b -> IORef b
1182−unsafeNewIORef a b = unsafePerformIO $ do
1183− touch a
1184− newIORef b
1185−
1186−instance HasSpiderTimeline x => Functor (Event x) where
1187− fmap f = push $ return . Just . f
1188−
1189−instance Functor (Behavior x) where
1190− fmap f = pull . fmap f . readBehaviorTracked
1191−
1192−{-# INLINE push #-}
1193−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1194−push f e = cacheEvent (pushCheap f e)
1195−
1196−{-# INLINABLE pull #-}
1197−pull :: BehaviorM x a -> Behavior x a
1198−pull a = behaviorPull $ Pull
1199− { pullCompute = a
1200− , pullValue = unsafeNewIORef a Nothing
1201−#ifdef DEBUG_NODEIDS
1202− , pullNodeId = unsafeNodeId a
1203−#endif
1204− }
1205−
1206−{-# INLINABLE switch #-}
1207−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1208−switch a = eventSwitch $ Switch
1209− { switchParent = a
1210− , switchSubscribed = unsafeNewIORef a Nothing
1211− }
1212−
1213−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1214−coincidence a = eventCoincidence $ Coincidence
1215− { coincidenceParent = a
1216− , coincidenceSubscribed = unsafeNewIORef a Nothing
1217− }
1218−
1219−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1220−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1221−run roots after = do
1222− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1223− let t = spiderTimeline :: SpiderTimelineEnv x
1224− result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1225− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1226− occBefore <- liftIO $ do
1227− occBefore <- readIORef occRef
1228− writeIORef occRef $! DMap.insert k a occBefore
1229− return occBefore
1230− if DMap.null occBefore
1231− then do scheduleRootClear occRef
1232− return $ Just r
1233− else return Nothing
1234− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1235− propagate a subscribersRef
1236− delayedRef <- asksEventEnv eventEnvDelayedMerges
1237− let go = do
1238− delayed <- liftIO $ readIORef delayedRef
1239− case IntMap.minViewWithKey delayed of
1240− Nothing -> return ()
1241− Just ((currentHeight, cur), future) -> do
1242− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1243− putCurrentHeight $ Height currentHeight
1244− liftIO $ writeIORef delayedRef $! future
1245− sequence_ cur
1246− go
1247− go
1248− putCurrentHeight maxBound
1249− after
1250− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1251− return result
1252−
1253−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1254−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1255− height <- liftIO $ readIORef heightRef
1256− currentHeight <- getCurrentHeight
1257− case height `compare` currentHeight of
1258− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1259− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1260− EQ -> a
1261−
1262−data SomeClear = forall a. SomeClear {-# UNPACK #-} !(IORef (Maybe a))
1263−
1264−data SomeIntClear = forall a. SomeIntClear {-# UNPACK #-} !(IORef (IntMap a))
1265−
1266−data SomeRootClear = forall k. SomeRootClear {-# UNPACK #-} !(IORef (DMap k Identity))
1267−
1268−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1269−
1270−debugFinalize :: Bool
1271−debugFinalize = False
1272−
1273−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1274−mkWeakPtrWithDebug x debugNote = do
1275− x' <- evaluate x
1276− mkWeakPtr x' $
1277− if debugFinalize
1278− then Just $ putStrLn $ "finalizing: " ++ debugNote
1279− else Nothing
1280−
1281−type WeakList a = [Weak a]
1282−
1283−{-# INLINE withIncreasedDepth #-}
1284−#ifdef DEBUG
1285−withIncreasedDepth :: CanTrace x m => m a -> m a
1286−withIncreasedDepth a = do
1287− spiderTimeline <- askSpiderTimelineEnv
1288− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1289− result <- a
1290− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1291− return result
1292−#else
1293−withIncreasedDepth :: m a -> m a
1294−withIncreasedDepth = id
1295−#endif
1296−
1297−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1298−
1299−{-# INLINE tracePropagate #-}
1300−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1301−tracePropagate p = traceWhen p debugPropagate
1302−
1303−{-# INLINE traceInvalidate #-}
1304−traceInvalidate :: String -> IO ()
1305−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1306−
1307−{-# INLINE traceWhen #-}
1308−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1309−traceWhen p b message = traceMWhen p b $ return message
1310−
1311−{-# INLINE traceMWhen #-}
1312−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1313−traceMWhen _ b getMessage = when b $ do
1314− message <- getMessage
1315−#ifdef DEBUG
1316− spiderTimeline <- askSpiderTimelineEnv
1317− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1318−#else
1319− let d = 0
1320−#endif
1321− liftIO $ putStrLn $ replicate d ' ' <> message
1322−
1323−whoCreatedIORef :: IORef a -> IO [String]
1324−whoCreatedIORef (IORef a) = whoCreated $! a
1325−
1326−#ifdef DEBUG_CYCLES
1327−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1328−groupByHead = \case
1329− [] -> []
1330− (x :| xs) : t -> case groupByHead t of
1331− [] -> [(x, xs :| [])]
1332− l@((y, yss) : t')
1333− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1334− | otherwise -> (x, xs :| []) : l
1335−
1336−listsToForest :: Eq a => [[a]] -> Forest a
1337−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1338−#endif
1339−
1340−{-# INLINE propagateSubscriberHold #-}
1341−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1342−propagateSubscriberHold h a = do
1343− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1344− invalidators <- liftIO $ readIORef $ holdInvalidators h
1345− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1346− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1347− case {-# SCC "apply" #-} apply a v of
1348− Nothing -> return ()
1349− Just v' -> do
1350− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1351− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1352− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1353− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1354−
1355−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1356−
1357−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1358−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1359−
1360−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1361−askInvalidator = do
1362− (!m, _) <- BehaviorM ask
1363− case m of
1364− Nothing -> return Nothing
1365− Just (!wi, _) -> return $ Just wi
1366−
1367−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1368−askParentsRef = do
1369− (!m, _) <- BehaviorM ask
1370− case m of
1371− Nothing -> return Nothing
1372− Just (_, !p) -> return $ Just p
1373−
1374−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1375−askBehaviorHoldInits = do
1376− (_, !his) <- BehaviorM ask
1377− return his
1378−
1379−{-# INLINE getDynHold #-}
1380−getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1381−getDynHold d = do
1382− mh <- liftIO $ readIORef $ unDyn d
1383− case mh of
1384− HoldDyn h -> return h
1385− UnsafeDyn (readV0, v') -> do
1386− holdInits <- getDeferralQueue
1387− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1388− hold' v0 v'
1389− BuildDyn (readV0, v') -> do
1390− v0 <- liftIO $ runEventM readV0
1391− hold' v0 v'
1392− where
1393− hold' v0 v' = do
1394− h <- hold v0 v'
1395− liftIO $ writeIORef (unDyn d) $ HoldDyn h
1396− return h
1397−
1398−
1399−-- Always refers to 0
1400−{-# NOINLINE zeroRef #-}
1401−zeroRef :: IORef Height
1402−zeroRef = unsafePerformIO $ newIORef zeroHeight
1403−
1404−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1405−getRootSubscribed k r sub = do
1406− mSubscribed <- readIORef $ rootSubscribed r
1407− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1408− case DMap.lookup k mSubscribed of
1409− Just subscribed -> {-# SCC "hitRoot" #-} do
1410− sln <- subscribeRootSubscribed subscribed sub
1411− occ <- getOcc
1412− return (sln, subscribed, occ)
1413− Nothing -> {-# SCC "missRoot" #-} do
1414− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1415− let !cached = rootSubscribed r
1416− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1417− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1418− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1419− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1420− writeIORef uninitRef $! uninit
1421− let !subscribed = RootSubscribed
1422− { rootSubscribedKey = k
1423− , rootSubscribedCachedSubscribed = cached
1424− , rootSubscribedOccurrence = getOcc
1425− , rootSubscribedSubscribers = subs
1426− , rootSubscribedUninit = uninit
1427− , rootSubscribedWeakSelf = weakSelf
1428−#ifdef DEBUG_NODEIDS
1429− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1430−#endif
1431− }
1432− -- If we die at the same moment that all our children die, they will
1433− -- try to clean us up but will fail because their Weak reference to us
1434− -- will also be dead. So, if we are dying, check if there are any
1435− -- children; since children don't bother cleaning themselves up if
1436− -- their parents are already dead, I don't think there's a race
1437− -- condition here. However, if there are any children, then we can
1438− -- infer that we need to clean ourselves up, so we do.
1439− finalCleanup = do
1440− cs <- readIORef $ _weakBag_children subs
1441− when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1442− writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1443− 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
1444− occ <- getOcc
1445− return (sln, subscribed, occ)
1446−
1447−#ifdef USE_TEMPLATE_HASKELL
1448−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1449−#endif
1450−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1451−cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1452− rootSubscribedUninit self
1453− modifyIORef' cached $ DMap.delete k
1454−
1455−{-# INLINE subscribeRootSubscribed #-}
1456−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1457−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1458−
1459−newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1460−
1461−data FanInt x a = FanInt
1462− { _fanInt_subscribers :: {-# UNPACK #-} !(FastMutableIntMap (FastWeakBag (Subscriber x a))) --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1463− , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1464− , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1465− }
1466−
1467−newFanInt :: IO (FanInt x a)
1468−newFanInt = do
1469− subscribers <- FastMutableIntMap.newEmpty --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1470− subscriptionRef <- newIORef $ error "fanInt: no subscription"
1471− occRef <- newIORef $ error "fanInt: no occurrence"
1472− return $ FanInt
1473− { _fanInt_subscribers = subscribers
1474− , _fanInt_subscriptionRef = subscriptionRef
1475− , _fanInt_occRef = occRef
1476− }
1477−
1478−{-# NOINLINE unsafeNewFanInt #-}
1479−unsafeNewFanInt :: b -> FanInt x a
1480−unsafeNewFanInt b = unsafePerformIO $ do
1481− touch b
1482− newFanInt
1483−
1484−fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1485−fanInt p =
1486− let self = unsafeNewFanInt p
1487− in EventSelectorInt $ \k -> Event $ \sub -> do
1488− isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1489− when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1490− (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1491− { subscriberPropagate = \m -> do
1492− liftIO $ writeIORef (_fanInt_occRef self) m
1493− scheduleIntClear $ _fanInt_occRef self
1494− FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1495− FastWeakBag.traverse b $ \s -> do
1496− subscriberPropagate s v
1497− , subscriberInvalidateHeight = \old -> do
1498− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1499− FastWeakBag.traverse b $ \s -> do
1500− subscriberInvalidateHeight s old
1501− , subscriberRecalculateHeight = \new -> do
1502− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1503− FastWeakBag.traverse b $ \s -> do
1504− subscriberRecalculateHeight s new
1505− }
1506− liftIO $ do
1507− writeIORef (_fanInt_subscriptionRef self) subscription
1508− writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1509− scheduleIntClear $ _fanInt_occRef self
1510− liftIO $ do
1511− b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1512− Nothing -> do
1513− b <- FastWeakBag.empty
1514− FastMutableIntMap.insert (_fanInt_subscribers self) k b
1515− return b
1516− Just b -> return b
1517− t <- liftIO $ FastWeakBag.insert sub b
1518− currentOcc <- readIORef (_fanInt_occRef self)
1519− (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1520− return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1521−
1522−{-# INLINABLE getFanSubscribed #-}
1523−getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a)
1524−getFanSubscribed k f sub = do
1525− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1526− case mSubscribed of
1527− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1528− sln <- subscribeFanSubscribed k subscribed sub
1529− occ <- readIORef $ fanSubscribedOccurrence subscribed
1530− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1531− Nothing -> {-# SCC "missFan" #-} do
1532− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1533− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1534− s <- liftIO $ newSubscriberFan subscribedUnsafe
1535− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1536− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1537− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1538− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1539− occRef <- liftIO $ newIORef parentOcc
1540− when (isJust parentOcc) $ scheduleClear occRef
1541− let subscribed = FanSubscribed
1542− { fanSubscribedCachedSubscribed = fanSubscribed f
1543− , fanSubscribedOccurrence = occRef
1544− , fanSubscribedParent = subscription
1545− , fanSubscribedSubscribers = subscribersRef
1546−#ifdef DEBUG_NODEIDS
1547− , fanSubscribedNodeId = unsafeNodeId f
1548−#endif
1549− }
1550− let !self = (k, subscribed)
1551− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1552− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1553− liftIO $ writeIORef subscribedRef $! subscribed
1554− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1555− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1556−
1557−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1558−cleanupFanSubscribed (k, subscribed) = do
1559− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1560− let reducedSubscribers = DMap.delete k subscribers
1561− if DMap.null reducedSubscribers
1562− then do
1563− unsubscribe $ fanSubscribedParent subscribed
1564− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1565− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1566− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1567−
1568−{-# INLINE subscribeFanSubscribed #-}
1569−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1570−subscribeFanSubscribed k subscribed sub = do
1571− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1572− case DMap.lookup k subscribers of
1573− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1574− let !self = (k, subscribed)
1575− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1576− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1577− writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeFanSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1578− return sln
1579− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1580−
1581−{-# INLINABLE getSwitchSubscribed #-}
1582−getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1583−getSwitchSubscribed s sub = do
1584− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1585− case mSubscribed of
1586− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1587− sln <- subscribeSwitchSubscribed subscribed sub
1588− occ <- readIORef $ switchSubscribedOccurrence subscribed
1589− return (sln, subscribed, occ)
1590− Nothing -> {-# SCC "missSwitch" #-} do
1591− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1592− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1593− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1594− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1595− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1596− wiRef <- liftIO $ newIORef wi
1597− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1598− holdInits <- getDeferralQueue
1599− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1600− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1601− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1602− subscriptionRef <- liftIO $ newIORef subscription
1603− occRef <- liftIO $ newIORef parentOcc
1604− when (isJust parentOcc) $ scheduleClear occRef
1605− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1606− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1607− let !subscribed = SwitchSubscribed
1608− { switchSubscribedCachedSubscribed = switchSubscribed s
1609− , switchSubscribedOccurrence = occRef
1610− , switchSubscribedHeight = heightRef
1611− , switchSubscribedSubscribers = subs
1612− , switchSubscribedOwnInvalidator = i
1613− , switchSubscribedOwnWeakInvalidator = wiRef
1614− , switchSubscribedBehaviorParents = parentsRef
1615− , switchSubscribedParent = switchParent s
1616− , switchSubscribedCurrentParent = subscriptionRef
1617− , switchSubscribedWeakSelf = weakSelf
1618−#ifdef DEBUG_NODEIDS
1619− , switchSubscribedNodeId = unsafeNodeId s
1620−#endif
1621− }
1622− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1623− liftIO $ writeIORef subscribedRef $! subscribed
1624− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1625− return (slnForSub, subscribed, parentOcc)
1626−
1627−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1628−cleanupSwitchSubscribed subscribed = do
1629− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1630− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1631− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1632−
1633−{-# INLINE subscribeSwitchSubscribed #-}
1634−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1635−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1636−
1637−{-# INLINABLE getCoincidenceSubscribed #-}
1638−getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1639−getCoincidenceSubscribed c sub = do
1640− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1641− case mSubscribed of
1642− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1643− sln <- subscribeCoincidenceSubscribed subscribed sub
1644− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1645− return (sln, subscribed, occ)
1646− Nothing -> {-# SCC "missCoincidence" #-} do
1647− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1648− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1649− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1650− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1651− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1652− (occ, height, mInnerSubd) <- case outerOcc of
1653− Nothing -> return (Nothing, outerHeight, Nothing)
1654− Just o -> do
1655− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1656− return (occ, height, Just innerSubd)
1657− occRef <- liftIO $ newIORef occ
1658− when (isJust occ) $ scheduleClear occRef
1659− heightRef <- liftIO $ newIORef height
1660− innerSubdRef <- liftIO $ newIORef mInnerSubd
1661− scheduleClear innerSubdRef
1662− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1663− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1664− let subscribed = CoincidenceSubscribed
1665− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1666− , coincidenceSubscribedOccurrence = occRef
1667− , coincidenceSubscribedHeight = heightRef
1668− , coincidenceSubscribedSubscribers = subs
1669− , coincidenceSubscribedOuter = subOuter
1670− , coincidenceSubscribedOuterParent = outerSubscription
1671− , coincidenceSubscribedInnerParent = innerSubdRef
1672− , coincidenceSubscribedWeakSelf = weakSelf
1673−#ifdef DEBUG_NODEIDS
1674− , coincidenceSubscribedNodeId = unsafeNodeId c
1675−#endif
1676− }
1677− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1678− liftIO $ writeIORef subscribedRef $! subscribed
1679− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1680− return (slnForSub, subscribed, occ)
1681−
1682−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1683−cleanupCoincidenceSubscribed subscribed = do
1684− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1685− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1686−
1687−{-# INLINE subscribeCoincidenceSubscribed #-}
1688−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1689−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1690−
1691−{-# INLINE merge #-}
1692−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1693−merge d = cacheEvent (mergeCheap d)
1694−
1695−{-# INLINE mergeWithMove #-}
1696−mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1697−mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1698−
1699−{-# INLINE [1] mergeCheap #-}
1700−mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1701−mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1702− where
1703− updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1704− updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1705− let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1706− (mOldSubd, newPs) <- case me of
1707− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1708− Just e -> do
1709− let s = subscriber $ return k
1710− subscription@(EventSubscription _ subd) <- subscribe e s
1711− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1712− let newParent = MergeSubscribedParent subscription
1713− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1714− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1715− forM_ mOldSubd $ \oldSubd -> do
1716− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1717− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1718− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1719− foldM f ([], oldParents) $ DMap.toList p
1720− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1721− getInitialSubscribers initialParents subscriber = do
1722− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1723− let s = subscriber $ return k
1724− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1725− height <- liftIO $ getEventSubscribedHeight parentSubd
1726− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1727− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1728− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1729− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1730− )
1731− destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1732− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1733−
1734−{-# INLINE [1] mergeCheapWithMove #-}
1735−mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1736−mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1737− where
1738− updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1739− updateMe subscriber heightBagRef oldParents p = do
1740− -- Prepare new parents for insertion
1741− let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1742− subscribeParent k e = do
1743− keyRef <- liftIO $ newIORef k
1744− let s = subscriber $ liftIO $ readIORef keyRef
1745− subscription@(EventSubscription _ subd) <- subscribe e s
1746− liftIO $ do
1747− newParentHeight <- getEventSubscribedHeight subd
1748− modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1749− return $ MergeSubscribedParentWithMove subscription keyRef
1750− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1751− -- Collect old parents for deletion and update the keys of moved parents
1752− let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1753− moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1754− Nothing -> do
1755− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1756− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1757− return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1758− Just toKey -> do
1759− liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1760− return Nothing
1761− toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1762− return (toDelete, applyAlways p' oldParents)
1763− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1764− getInitialSubscribers initialParents subscriber = do
1765− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1766− keyRef <- liftIO $ newIORef k
1767− let s = subscriber $ liftIO $ readIORef keyRef
1768− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1769− height <- liftIO $ getEventSubscribedHeight parentSubd
1770− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1771− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1772− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1773− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1774− )
1775− destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1776− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1777−
1778−type MergeUpdateFunc k x p s
1779− = (forall a. EventM x (k a) -> Subscriber x a)
1780− -> IORef HeightBag
1781− -> DMap k s
1782− -> p
1783− -> EventM x ([EventSubscription x], DMap k s)
1784−
1785−type MergeInitFunc k x s
1786− = DMap k (Event x)
1787− -> (forall a. EventM x (k a) -> Subscriber x a)
1788− -> EventM x (DMap k Identity, [Height], DMap k s)
1789−
1790−type MergeDestroyFunc k s
1791− = DMap k s
1792− -> IO ()
1793−
1794−data Merge x k s = Merge
1795− { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1796− , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1797− , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1798− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1799− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1800− }
1801−
1802−invalidateMergeHeight :: Merge x k s -> IO ()
1803−invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1804−
1805−invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1806−invalidateMergeHeight' heightRef sub = do
1807− oldHeight <- readIORef heightRef
1808− when (oldHeight /= invalidHeight) $ do -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1809− writeIORef heightRef $! invalidHeight
1810− subscriberInvalidateHeight sub oldHeight
1811−
1812−
1813−revalidateMergeHeight :: Merge x k s -> IO ()
1814−revalidateMergeHeight m = do
1815− currentHeight <- readIORef $ _merge_heightRef m
1816− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1817− heights <- readIORef $ _merge_heightBagRef m
1818− parents <- readIORef $ _merge_parentsRef m
1819− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1820− case heightBagSize heights `compare` DMap.size parents of
1821− LT -> return ()
1822− EQ -> do
1823− let height = succHeight $ heightBagMax heights
1824− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1825− writeIORef (_merge_heightRef m) $! height
1826− subscriberRecalculateHeight (_merge_sub m) height
1827− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1828−
1829−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1830−scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1831− vals <- liftIO $ readIORef $ _merge_accumRef m
1832− liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us, it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
1833− --TODO: Assert that m is not empty
1834− subscriberPropagate (_merge_sub m) vals
1835−
1836−mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1837−mergeSubscriber m getKey = Subscriber
1838− { subscriberPropagate = \a -> do
1839− oldM <- liftIO $ readIORef $ _merge_accumRef m
1840− k <- getKey
1841− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1842− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1843− liftIO $ writeIORef (_merge_accumRef m) $! newM
1844− when (DMap.null oldM) $ do -- Only schedule the firing once
1845− height <- liftIO $ readIORef $ _merge_heightRef m
1846− --TODO: assertions about height
1847− currentHeight <- getCurrentHeight
1848− when (height <= currentHeight) $ do
1849− if height /= invalidHeight
1850− then do
1851− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1852− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1853− else liftIO $ do
1854−#ifdef DEBUG_CYCLES
1855− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1856− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1857− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1858−#else
1859− let cycleInfo = ""
1860−#endif
1861− error $ "Causality loop found" <> cycleInfo
1862− scheduleMergeSelf m height
1863− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1864− modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1865− invalidateMergeHeight m
1866− , subscriberRecalculateHeight = \new -> do
1867− modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1868− revalidateMergeHeight m
1869− }
1870−
1871−--TODO: Be able to run as much of this as possible promptly
1872−updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1873−updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1874− where updateMe = do
1875− oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1876− (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1877− liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1878− return subscriptionsToKill
1879−
1880−{-# INLINE mergeCheap' #-}
1881−mergeCheap' :: forall k x p s. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k (Event x)) => MergeInitFunc k x s -> MergeUpdateFunc k x p s -> MergeDestroyFunc k s -> Dynamic x p -> Event x (DMap k Identity)
1882−mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1883− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1884− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1885− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1886− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1887− parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1888− let m = Merge
1889− { _merge_parentsRef = parentsRef
1890− , _merge_heightBagRef = heightBagRef
1891− , _merge_heightRef = heightRef
1892− , _merge_sub = sub
1893− , _merge_accumRef = accumRef
1894− }
1895− (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1896− let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1897− myHeight = if invalidHeight `elem` heights
1898− then invalidHeight
1899− else succHeight $ heightBagMax myHeightBag
1900− currentHeight <- getCurrentHeight
1901− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1902− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1903− else (Nothing, dm)
1904− unless (DMap.null accum) $ do
1905− scheduleMergeSelf m myHeight
1906− liftIO $ writeIORef accumRef $! accum
1907− liftIO $ writeIORef heightRef $! myHeight
1908− liftIO $ writeIORef heightBagRef $! myHeightBag
1909− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1910− liftIO $ writeIORef parentsRef $! initialParentState
1911− defer $ SomeMergeInit $ do
1912− let s = Subscriber
1913− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1914− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1915− defer $ updateMerge m updateFunc a
1916− , subscriberInvalidateHeight = \_ -> return ()
1917− , subscriberRecalculateHeight = \_ -> return ()
1918− }
1919− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1920− forM_ change $ \c -> defer $ updateMerge m updateFunc c
1921− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1922− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1923− -- its subscription.
1924− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1925− let unsubscribeAll = destroy =<< readIORef parentsRef
1926− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1927− , occ
1928− )
1929−
1930−mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1931−mergeInt = cacheEvent . mergeIntCheap
1932−
1933−{-# INLINABLE mergeIntCheap #-}
1934−mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1935−mergeIntCheap d = Event $ \sub -> do
1936− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1937− accum <- liftIO $ FastMutableIntMap.newEmpty
1938− heightRef <- liftIO $ newIORef zeroHeight
1939− heightBagRef <- liftIO $ newIORef heightBagEmpty
1940− parents <- liftIO $ FastMutableIntMap.newEmpty
1941− let scheduleSelf = do
1942− height <- liftIO $ readIORef $ heightRef
1943− scheduleMerge' height heightRef $ do
1944− vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1945− subscriberPropagate sub vals
1946− invalidateMyHeight = do
1947− invalidateMergeHeight' heightRef sub
1948− recalculateMyHeight = do
1949− currentHeight <- readIORef heightRef
1950− when (currentHeight == invalidHeight) $ do --TODO: This will almost always be true; can we get rid of this check and just proceed to the next one always?
1951− heights <- readIORef heightBagRef
1952− numParents <- FastMutableIntMap.size parents
1953− case heightBagSize heights `compare` numParents of
1954− LT -> return ()
1955− EQ -> do
1956− let height = succHeight $ heightBagMax heights
1957− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1958− writeIORef heightRef $! height
1959− subscriberRecalculateHeight sub height
1960− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1961− mySubscriber k = Subscriber
1962− { subscriberPropagate = \a -> do
1963− wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1964− liftIO $ FastMutableIntMap.insert accum k a
1965− when wasEmpty scheduleSelf
1966− , subscriberInvalidateHeight = \old -> do
1967− modifyIORef' heightBagRef $ heightBagRemove old
1968− invalidateMyHeight
1969− , subscriberRecalculateHeight = \new -> do
1970− modifyIORef' heightBagRef $ heightBagAdd new
1971− recalculateMyHeight
1972− }
1973− forM_ (IntMap.toList initialParents) $ \(k, p) -> do
1974− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
1975− liftIO $ do
1976− forM_ parentOcc $ FastMutableIntMap.insert accum k
1977− FastMutableIntMap.insert parents k subscription
1978− height <- getEventSubscribedHeight parentSubd
1979− if height == invalidHeight
1980− then writeIORef heightRef invalidHeight
1981− else do
1982− modifyIORef' heightBagRef $ heightBagAdd height
1983− modifyIORef' heightRef $ \oldHeight ->
1984− if oldHeight == invalidHeight
1985− then invalidHeight
1986− else max (succHeight height) oldHeight
1987− myHeight <- liftIO $ readIORef heightRef
1988− currentHeight <- getCurrentHeight
1989− isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1990− occ <- if currentHeight >= myHeight -- If we should have fired by now
1991− then if isEmpty
1992− then return Nothing
1993− else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
1994− else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
1995− return Nothing
1996− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1997− defer $ SomeMergeInit $ do
1998− let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
1999− where
2000− u = do
2001− let f k newParent = do
2002− subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2003− newParentHeight <- liftIO $ getEventSubscribedHeight subd
2004− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2005− return subscription
2006− newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2007− oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2008− liftIO $ for_ oldParents $ \oldParent -> do
2009− oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2010− modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2011− return $ IntMap.elems oldParents
2012− let s = Subscriber
2013− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2014− tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2015− defer $ updateMe a
2016− , subscriberInvalidateHeight = \_ -> return ()
2017− , subscriberRecalculateHeight = \_ -> return ()
2018− }
2019− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2020− forM_ change $ \c -> defer $ updateMe c
2021− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2022− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2023− -- its subscription.
2024− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2025− let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2026− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2027− , occ
2028− )
2029−
2030−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2031−
2032−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2033−fan e =
2034− let f = Fan
2035− { fanParent = e
2036− , fanSubscribed = unsafeNewIORef e Nothing
2037− }
2038− in EventSelector $ \k -> eventFan k f
2039−
2040−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2041−runHoldInits holdInitRef dynInitRef mergeInitRef = do
2042− holdInits <- liftIO $ readIORef holdInitRef
2043− dynInits <- liftIO $ readIORef dynInitRef
2044− mergeInits <- liftIO $ readIORef mergeInitRef
2045− unless (null holdInits && null dynInits && null mergeInits) $ do
2046− liftIO $ writeIORef holdInitRef []
2047− liftIO $ writeIORef dynInitRef []
2048− liftIO $ writeIORef mergeInitRef []
2049− mapM_ initHold holdInits
2050− mapM_ initDyn dynInits
2051− mapM_ unSomeMergeInit mergeInits
2052− runHoldInits holdInitRef dynInitRef mergeInitRef
2053−
2054−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2055−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2056−
2057−initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2058−initDyn (SomeDynInit d) = void $ getDynHold d
2059−
2060−newEventEnv :: IO (EventEnv x)
2061−newEventEnv = do
2062− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2063− holdInitRef <- newIORef []
2064− dynInitRef <- newIORef []
2065− mergeUpdateRef <- newIORef []
2066− mergeInitRef <- newIORef []
2067− heightRef <- newIORef zeroHeight
2068− toClearRef <- newIORef []
2069− toClearIntRef <- newIORef []
2070− toClearRootRef <- newIORef []
2071− coincidenceInfosRef <- newIORef []
2072− delayedRef <- newIORef IntMap.empty
2073− return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2074−
2075−clearEventEnv :: EventEnv x -> IO ()
2076−clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2077− writeIORef toAssignRef []
2078− writeIORef holdInitRef []
2079− writeIORef dynInitRef []
2080− writeIORef mergeUpdateRef []
2081− writeIORef mergeInitRef []
2082− writeIORef heightRef zeroHeight
2083− writeIORef toClearRef []
2084− writeIORef toClearIntRef []
2085− writeIORef toClearRootRef []
2086− writeIORef coincidenceInfosRef []
2087− writeIORef delayedRef IntMap.empty
2088−
2089−-- | Run an event action outside of a frame
2090−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2091−runFrame a = SpiderHost $ do
2092− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2093− let go = do
2094− result <- a
2095− runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
2096− return result
2097− result <- runEventM go
2098− toClear <- readIORef $ eventEnvClears env
2099− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
2100− toClearInt <- readIORef $ eventEnvIntClears env
2101− forM_ toClearInt $ \(SomeIntClear ref) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2102− toClearRoot <- readIORef $ eventEnvRootClears env
2103− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2104− toAssign <- readIORef $ eventEnvAssignments env
2105− toReconnectRef <- newIORef []
2106− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2107− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2108− writeIORef vRef v
2109− when debugInvalidate $ putStrLn $ "Invalidating Hold"
2110− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2111− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2112− writeIORef (eventEnvMergeUpdates env) []
2113− when debugPropagate $ putStrLn "Updating merges"
2114− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2115− when debugPropagate $ putStrLn "Updating merges done"
2116− toReconnect <- readIORef toReconnectRef
2117− clearEventEnv env
2118− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2119− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2120− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2121− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2122− finalize wi
2123− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2124− wi' <- mkWeakPtrWithDebug i "wi'"
2125− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2126− writeIORef (switchSubscribedBehaviorParents subscribed) []
2127− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2128− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2129− runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits 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
2130− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2131− sub <- newSubscriberSwitch subscribed
2132− subscription <- unSpiderHost $ runFrame $ {-# SCC "subscribeSwitch" #-} subscribe e sub --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
2133− {-
2134− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2135− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2136− EventRoot _ -> "EventRoot"
2137− EventNever -> "EventNever"
2138− _ -> "something else"
2139− -}
2140− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2141− return oldSubscription
2142− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2143− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2144− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2145− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2146− parentHeight <- getEventSubscribedHeight subd'
2147− myHeight <- readIORef $ switchSubscribedHeight subscribed
2148− when (parentHeight /= myHeight) $ do
2149− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2150− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2151− mapM_ _someMergeUpdate_invalidateHeight mergeUpdates --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
2152− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2153− unsubscribe subscription
2154− mapM_ invalidateCoincidenceHeight mcs
2155− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2156− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2157− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2158− height <- calculateSwitchHeight subscribed
2159− updateSwitchHeight height subscribed
2160− return result
2161−
2162−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2163−
2164−{-# INLINE zeroHeight #-}
2165−zeroHeight :: Height
2166−zeroHeight = Height 0
2167−
2168−{-# INLINE invalidHeight #-}
2169−invalidHeight :: Height
2170−invalidHeight = Height (-1000)
2171−
2172−#ifdef DEBUG_CYCLES
2173−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2174−{-# INLINE invalidHeightBeingTraversed #-}
2175−invalidHeightBeingTraversed :: Height
2176−invalidHeightBeingTraversed = Height (-1001)
2177−#endif
2178−
2179−{-# INLINE succHeight #-}
2180−succHeight :: Height -> Height
2181−succHeight h@(Height a) =
2182− if h == invalidHeight
2183− then invalidHeight
2184− else Height $ succ a
2185−
2186−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2187−invalidateCoincidenceHeight subscribed = do
2188− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2189− when (oldHeight /= invalidHeight) $ do
2190− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2191− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2192−
2193−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2194−updateSwitchHeight new subscribed = do
2195− oldHeight <- readIORef $ switchSubscribedHeight subscribed
2196− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2197− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2198− writeIORef (switchSubscribedHeight subscribed) $! new
2199− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2200−
2201−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2202−recalculateCoincidenceHeight subscribed = do
2203− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2204− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2205− height <- calculateCoincidenceHeight subscribed
2206− when (height /= invalidHeight) $ do
2207− writeIORef (coincidenceSubscribedHeight subscribed) $! height
2208− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2209−
2210−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2211−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2212−
2213−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2214−calculateCoincidenceHeight subscribed = do
2215− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2216− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2217− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2218−
2219−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2220−
2221−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2222−invalidate toReconnectRef wis = do
2223− forM_ wis $ \wi -> do
2224− mi <- deRefWeak wi
2225− case mi of
2226− Nothing -> do
2227− traceInvalidate "invalidate Dead"
2228− return () --TODO: Should we clean this up here?
2229− Just i -> do
2230− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2231− case i of
2232− InvalidatorPull p -> do
2233− traceInvalidate $ "invalidate: Pull" <> showNodeId p
2234− mVal <- readIORef $ pullValue p
2235− forM_ mVal $ \val -> do
2236− writeIORef (pullValue p) Nothing
2237− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2238− InvalidatorSwitch subscribed -> do
2239− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2240− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2241− 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
2242−
2243−--------------------------------------------------------------------------------
2244−-- Reflex integration
2245−--------------------------------------------------------------------------------
2246−
2247−-- | Designates the default, global Spider timeline
2248−data SpiderTimeline x
2249−type role SpiderTimeline nominal
2250−
2251−-- | The default, global Spider environment
2252−type Spider = SpiderTimeline Global
2253−
2254−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2255− {-# INLINABLE sample #-}
2256− sample (SpiderBehavior b) = readBehaviorUntracked b
2257−
2258−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2259− {-# INLINABLE hold #-}
2260− hold = holdSpiderEventM
2261− {-# INLINABLE holdDyn #-}
2262− holdDyn = holdDynSpiderEventM
2263− {-# INLINABLE holdIncremental #-}
2264− holdIncremental = holdIncrementalSpiderEventM
2265− {-# INLINABLE buildDynamic #-}
2266− buildDynamic = buildDynamicSpiderEventM
2267− {-# INLINABLE headE #-}
2268− headE = R.slowHeadE
2269−-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2270−
2271−instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2272− {-# INLINABLE sample #-}
2273− sample = coerce . readBehaviorTracked . unSpiderBehavior
2274−
2275−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2276− {-# INLINABLE sample #-}
2277− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2278−
2279−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2280− {-# INLINABLE hold #-}
2281− hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2282− {-# INLINABLE holdDyn #-}
2283− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2284− {-# INLINABLE holdIncremental #-}
2285− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2286− {-# INLINABLE buildDynamic #-}
2287− buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2288− {-# INLINABLE headE #-}
2289− headE = R.slowHeadE
2290−-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2291−
2292−instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2293− {-# INLINE return #-}
2294− return = pure
2295− {-# INLINE (>>=) #-}
2296− x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2297− {-# INLINE (>>) #-}
2298− (>>) = (*>)
2299− {-# INLINE fail #-}
2300− fail _ = error "Dynamic does not support 'fail'"
2301−
2302−{-# INLINABLE newJoinDyn #-}
2303−newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2304−newJoinDyn d =
2305− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2306− eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2307− eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2308− eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2309− v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2310− in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2311−
2312−instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2313− fmap = mapDynamicSpider
2314− x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2315−
2316−mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2317−mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2318−{-# INLINE [1] mapDynamicSpider #-}
2319−
2320−instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2321− pure = SpiderDynamic . dynamicConst
2322−#if MIN_VERSION_base(4,10,0)
2323− liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2324−#endif
2325− SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2326− a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2327− (<*) = flip (*>) -- There are no effects, so order doesn't matter
2328−
2329−holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2330−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2331−
2332−holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2333−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2334−
2335−holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2336−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2337−
2338−buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2339−buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2340−
2341−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2342− {-# INLINABLE hold #-}
2343− hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2344− {-# INLINABLE holdDyn #-}
2345− holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2346− {-# INLINABLE holdIncremental #-}
2347− holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2348− {-# INLINABLE buildDynamic #-}
2349− buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2350− {-# INLINABLE headE #-}
2351− headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2352−
2353−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2354− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2355−
2356−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2357− {-# INLINABLE hold #-}
2358− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2359− {-# INLINABLE holdDyn #-}
2360− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2361− {-# INLINABLE holdIncremental #-}
2362− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2363− {-# INLINABLE buildDynamic #-}
2364− buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2365− {-# INLINABLE headE #-}
2366− headE = R.slowHeadE
2367−-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2368−
2369−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2370− {-# INLINABLE sample #-}
2371− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2372−
2373−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2374− {-# INLINABLE sample #-}
2375− sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2376−
2377−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2378− {-# INLINABLE hold #-}
2379− hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2380− {-# INLINABLE holdDyn #-}
2381− holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2382− {-# INLINABLE holdIncremental #-}
2383− holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2384− {-# INLINABLE buildDynamic #-}
2385− buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2386− {-# INLINABLE headE #-}
2387− headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2388−
2389−--------------------------------------------------------------------------------
2390−-- Deprecated items
2391−--------------------------------------------------------------------------------
2392−
2393−-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2394−{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2395−type SpiderEnv = SpiderTimeline
2396−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2397− {-# INLINABLE subscribeEvent #-}
2398− subscribeEvent e = SpiderHostFrame $ do
2399− --TODO: Unsubscribe eventually (manually and/or with weak ref)
2400− val <- liftIO $ newIORef Nothing
2401− subscription <- subscribe (unSpiderEvent e) $ Subscriber
2402− { subscriberPropagate = \a -> do
2403− liftIO $ writeIORef val $ Just a
2404− scheduleClear val
2405− , subscriberInvalidateHeight = \_ -> return ()
2406− , subscriberRecalculateHeight = \_ -> return ()
2407− }
2408− return $ SpiderEventHandle
2409− { spiderEventHandleSubscription = subscription
2410− , spiderEventHandleValue = val
2411− }
2412−
2413−instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2414− type EventTrigger (SpiderTimeline x) = RootTrigger x
2415− type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2416− type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2417−
2418−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2419− {-# NOINLINE readEvent #-}
2420− readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2421− result <- readIORef $ spiderEventHandleValue h
2422− touch h
2423− return result
2424−
2425−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2426− newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2427− newFanEventWithTrigger f = SpiderHost $ do
2428− es <- newFanEventWithTriggerIO f
2429− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2430−
2431−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2432− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2433− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2434− es <- newFanEventWithTriggerIO f
2435− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2436−
2437−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2438− {-# INLINABLE subscribeEvent #-}
2439− subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2440−
2441−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2442− type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2443− fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2444− runHostFrame = runFrame . runSpiderHostFrame
2445−
2446−unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2447−unsafeNewSpiderTimelineEnv = do
2448− lock <- newMVar ()
2449− env <- newEventEnv
2450−#ifdef DEBUG
2451− depthRef <- newIORef 0
2452−#endif
2453− return $ SpiderTimelineEnv
2454− { _spiderTimeline_lock = lock
2455− , _spiderTimeline_eventEnv = env
2456−#ifdef DEBUG
2457− , _spiderTimeline_depth = depthRef
2458−#endif
2459− }
2460−
2461−-- | Create a new SpiderTimelineEnv
2462−newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2463−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2464−
2465−data LocalSpiderTimeline x s
2466−
2467−instance Reifies s (SpiderTimelineEnv x) =>
2468− HasSpiderTimeline (LocalSpiderTimeline x s) where
2469− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2470−
2471−localSpiderTimeline
2472− :: Proxy s
2473− -> SpiderTimelineEnv x
2474− -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2475−localSpiderTimeline _ = unsafeCoerce
2476−
2477−-- | Pass a new timeline to the given function.
2478−withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2479−withSpiderTimeline k = do
2480− env <- unsafeNewSpiderTimelineEnv
2481− reify env $ \s -> k $ localSpiderTimeline s env
2482−
2483−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2484−
2485−type ComputeM = EventM
2486−
2487−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2488−
2489−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2490− {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2491− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2492− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2493− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2494− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2495− type PullM (SpiderTimeline x) = SpiderPullM x
2496− type PushM (SpiderTimeline x) = SpiderPushM x
2497− {-# INLINABLE never #-}
2498− never = SpiderEvent eventNever
2499− {-# INLINABLE constant #-}
2500− constant = SpiderBehavior . behaviorConst
2501− {-# INLINE push #-}
2502− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2503− {-# INLINE pushCheap #-}
2504− pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2505− {-# INLINABLE pull #-}
2506− pull = SpiderBehavior . pull . coerce
2507− {-# INLINABLE merge #-}
2508− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2509− {-# INLINABLE fan #-}
2510− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2511− {-# INLINABLE switch #-}
2512− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2513− {-# INLINABLE coincidence #-}
2514− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2515− {-# INLINABLE current #-}
2516− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2517− {-# INLINABLE updated #-}
2518− updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2519− {-# INLINABLE unsafeBuildDynamic #-}
2520− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2521− {-# INLINABLE unsafeBuildIncremental #-}
2522− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2523− {-# INLINABLE mergeIncremental #-}
2524− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2525− {-# INLINABLE mergeIncrementalWithMove #-}
2526− mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2527− {-# INLINABLE currentIncremental #-}
2528− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2529− {-# INLINABLE updatedIncremental #-}
2530− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2531− {-# INLINABLE incrementalToDynamic #-}
2532− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2533− c <- readBehaviorUntracked $ dynamicCurrent i
2534− return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2535− eventCoercion Coercion = Coercion
2536− behaviorCoercion Coercion = Coercion
2537− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2538− {-# INLINABLE mergeIntIncremental #-}
2539− mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2540− {-# INLINABLE fanInt #-}
2541− fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2542−
2543−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2544−
2545−data SpiderEventHandle x a = SpiderEventHandle
2546− { spiderEventHandleSubscription :: EventSubscription x
2547− , spiderEventHandleValue :: IORef (Maybe a)
2548− }
2549−
2550−instance MonadRef (EventM x) where
2551− type Ref (EventM x) = Ref IO
2552− {-# INLINABLE newRef #-}
2553− {-# INLINABLE readRef #-}
2554− {-# INLINABLE writeRef #-}
2555− newRef = liftIO . newRef
2556− readRef = liftIO . readRef
2557− writeRef r a = liftIO $ writeRef r a
2558−
2559−instance MonadAtomicRef (EventM x) where
2560− {-# INLINABLE atomicModifyRef #-}
2561− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2562−
2563−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2564−newtype SpiderHost x a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2565−
2566−instance Monad (SpiderHost x) where
2567− {-# INLINABLE (>>=) #-}
2568− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2569− {-# INLINABLE (>>) #-}
2570− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2571− {-# INLINABLE return #-}
2572− return x = SpiderHost $ return x
2573− {-# INLINABLE fail #-}
2574− fail s = SpiderHost $ fail s
2575−
2576−-- | Run an action affecting the global Spider timeline; this will be guarded by
2577−-- a mutex for that timeline
2578−runSpiderHost :: SpiderHost Global a -> IO a
2579−runSpiderHost (SpiderHost a) = a
2580−
2581−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2582−-- mutex for that timeline
2583−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2584−runSpiderHostForTimeline (SpiderHost a) _ = a
2585−
2586−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2587− deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2588−
2589−instance Monad (SpiderHostFrame x) where
2590− {-# INLINABLE (>>=) #-}
2591− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2592− {-# INLINABLE (>>) #-}
2593− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2594− {-# INLINABLE return #-}
2595− return x = SpiderHostFrame $ return x
2596− {-# INLINABLE fail #-}
2597− fail s = SpiderHostFrame $ fail s
2598−
2599−instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2600− notReadyUntil _ = pure ()
2601− notReady = pure ()
2602−
2603−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2604−newEventWithTriggerIO f = do
2605− es <- newFanEventWithTriggerIO $ \Refl -> f
2606− return $ select es Refl
2607−
2608−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2609−newFanEventWithTriggerIO f = do
2610− occRef <- newIORef DMap.empty
2611− subscribedRef <- newIORef DMap.empty
2612− let !r = Root
2613− { rootOccurrence = occRef
2614− , rootSubscribed = subscribedRef
2615− , rootInit = f
2616− }
2617− return $ EventSelector $ \k -> eventRoot k r
2618−
2619−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2620−
2621−instance MonadRef (SpiderHost x) where
2622− type Ref (SpiderHost x) = Ref IO
2623− newRef = SpiderHost . newRef
2624− readRef = SpiderHost . readRef
2625− writeRef r = SpiderHost . writeRef r
2626−
2627−instance MonadAtomicRef (SpiderHost x) where
2628− atomicModifyRef r = SpiderHost . atomicModifyRef r
2629−
2630−instance MonadRef (SpiderHostFrame x) where
2631− type Ref (SpiderHostFrame x) = Ref IO
2632− newRef = SpiderHostFrame . newRef
2633− readRef = SpiderHostFrame . readRef
2634− writeRef r = SpiderHostFrame . writeRef r
2635−
2636−instance MonadAtomicRef (SpiderHostFrame x) where
2637− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2638−
2639−instance PrimMonad (SpiderHostFrame x) where
2640− type PrimState (SpiderHostFrame x) = PrimState IO
2641− primitive = SpiderHostFrame . EventM . primitive
src/Reflex/Time.hsdeleted−384
@@ -1,384 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE DeriveTraversable #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RecursiveDo #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeFamilies #-}
11−#ifdef USE_TEMPLATE_HASKELL
12−{-# LANGUAGE TemplateHaskell #-}
13−#endif
14−-- |
15−-- Module:
16−-- Reflex.Time
17−-- Description:
18−-- Clocks, timers, and other time-related functions.
19−module Reflex.Time where
20−
21−import Reflex.Class
22−import Reflex.Dynamic
23−import Reflex.PerformEvent.Class
24−import Reflex.PostBuild.Class
25−import Reflex.TriggerEvent.Class
26−
27−import Control.Concurrent
28−import qualified Control.Concurrent.Thread.Delay as Concurrent
29−import Control.Lens hiding ((|>))
30−import Control.Monad
31−import Control.Monad.Fix
32−import Control.Monad.IO.Class
33−import Data.Align
34−import Data.Data (Data)
35−import Data.Fixed
36−import Data.Semigroup (Semigroup(..))
37−import Data.Sequence (Seq, (|>))
38−import qualified Data.Sequence as Seq
39−import Data.These
40−import Data.Time.Clock
41−import Data.Typeable
42−import GHC.Generics (Generic)
43−import System.Random
44−
45−-- | Metadata associated with a timer "tick"
46−data TickInfo
47− = TickInfo { _tickInfo_lastUTC :: UTCTime
48− -- ^ UTC time immediately after the last tick.
49− , _tickInfo_n :: Integer
50− -- ^ Number of time periods or ticks since the start of the timer
51− , _tickInfo_alreadyElapsed :: NominalDiffTime
52− -- ^ Amount of time that has elapsed in the current tick period.
53− }
54− deriving (Eq, Ord, Show, Typeable)
55−
56−-- | Fires an 'Event' once every time provided interval elapses, approximately.
57−-- The provided 'UTCTime' is used bootstrap the determination of how much time has elapsed with each tick.
58−-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread.
59−tickLossy :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> UTCTime -> m (Event t TickInfo)
60−tickLossy dt t0 = tickLossyFrom dt t0 =<< getPostBuild
61−
62−-- | Fires an 'Event' once every time provided interval elapses, approximately.
63−-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread and the time of the post-build as the tick basis time.
64−tickLossyFromPostBuildTime :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> m (Event t TickInfo)
65−tickLossyFromPostBuildTime dt = do
66− postBuild <- getPostBuild
67− postBuildTime <- performEvent $ liftIO getCurrentTime <$ postBuild
68− tickLossyFrom' $ (dt,) <$> postBuildTime
69−
70−-- | Fires an 'Event' approximately each time the provided interval elapses. If the system starts running behind, occurrences will be dropped rather than buffered.
71−-- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the provided initial time.
72−tickLossyFrom
73− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
74− => NominalDiffTime
75− -- ^ The length of a tick interval
76− -> UTCTime
77− -- ^ The basis time from which intervals count and with which the initial calculation of elapsed time will be made.
78− -> Event t a
79− -- ^ Event that starts a tick generation thread. Usually you want this to
80− -- be something like the result of getPostBuild that only fires once. But
81− -- there could be uses for starting multiple timer threads.
82− -> m (Event t TickInfo)
83−tickLossyFrom dt t0 e = tickLossyFrom' $ (dt, t0) <$ e
84−
85−-- | Generalization of tickLossyFrom that takes the delay and initial time as an 'Event'.
86−tickLossyFrom'
87− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
88− => Event t (NominalDiffTime, UTCTime)
89− -- ^ Event that starts a tick generation thread. Usually you want this to
90− -- be something like the result of 'getPostBuild' that only fires once. But
91− -- there could be uses for starting multiple timer threads.
92− -> m (Event t TickInfo)
93−tickLossyFrom' e = do
94− rec result <- performEventAsync $ callAtNextInterval <$> leftmost [e, snd <$> result]
95− return $ fst <$> result
96− where callAtNextInterval pair cb = void $ liftIO $ forkIO $ do
97− tick <- uncurry getCurrentTick pair
98− Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000
99− cb (tick, pair)
100−
101−-- | Like 'tickLossy', but immediately calculates the first tick and provides a 'Dynamic' that is updated as ticks fire.
102−clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)
103−clockLossy dt t0 = do
104− initial <- liftIO $ getCurrentTick dt t0
105− e <- tickLossy dt t0
106− holdDyn initial e
107−
108−-- | Generates a 'TickInfo', given the specified interval and timestamp. The 'TickInfo' will include the
109−-- current time, the number of ticks that have elapsed since the timestamp, and the amount of time that
110−-- has elapsed since the start time of this tick.
111−getCurrentTick :: NominalDiffTime -> UTCTime -> IO TickInfo
112−getCurrentTick dt t0 = do
113− t <- getCurrentTime
114− let offset = t `diffUTCTime` t0
115− (n, alreadyElapsed) = offset `divMod'` dt
116− return $ TickInfo t n alreadyElapsed
117−
118−-- | Delay an Event's occurrences by a given amount in seconds.
119−delay :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
120−delay dt e = performEventAsync $ ffor e $ \a cb -> liftIO $ void $ forkIO $ do
121− Concurrent.delay $ ceiling $ dt * 1000000
122− cb a
123−
124−-- | Send events with Poisson timing with the given basis and rate
125−-- Each occurrence of the resulting event will contain the index of
126−-- the current interval, with 0 representing the basis time
127−poissonLossyFrom
128− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
129− => g
130− -> Double
131− -- ^ Poisson event rate (Hz)
132− -> UTCTime
133− -- ^ Baseline time for events
134− -> Event t a
135− -- ^ Event that starts a tick generation thread. Usually you want this to
136− -- be something like the result of getPostBuild that only fires once. But
137− -- there could be uses for starting multiple timer threads.
138− -- Start sending events in response to the event parameter.
139− -> m (Event t TickInfo)
140−poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate
141−
142−
143−-- | Send events with Poisson timing with the given basis and rate
144−-- Each occurrence of the resulting event will contain the index of
145−-- the current interval, with 0 representing the basis time.
146−-- Automatically begin sending events when the DOM is built
147−poissonLossy
148− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
149− => g
150− -> Double
151− -- ^ Poisson event rate (Hz)
152− -> UTCTime
153− -- ^ Baseline time for events
154− -> m (Event t TickInfo)
155−poissonLossy rnd rate t0 = poissonLossyFrom rnd rate t0 =<< getPostBuild
156−
157−-- | Send events with inhomogeneous Poisson timing with the given basis
158−-- and variable rate. Provide a maxRate that you expect to support.
159−inhomogeneousPoissonFrom
160− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
161− => g
162− -> Behavior t Double
163− -> Double
164− -> UTCTime
165− -> Event t a
166− -> m (Event t TickInfo)
167−inhomogeneousPoissonFrom rnd rate maxRate t0 e = do
168−
169− -- Create a thread for producing homogeneous poisson events
170− -- along with random Doubles (usage of Double's explained below)
171− ticksWithRateRand <- performEventAsync $
172− fmap callAtNextInterval e
173−
174− -- Filter homogeneous events according to associated
175− -- random values and the current rate parameter
176− return $ attachWithMaybe filterFun rate ticksWithRateRand
177−
178− where
179−
180− -- Inhomogeneous poisson processes are built from faster
181− -- homogeneous ones by randomly dropping events from the
182− -- fast process. For each fast homogeneous event, choose
183− -- a uniform random sample from (0, rMax). If the
184− -- inhomogeneous rate at this moment is greater than the
185− -- random sample, then keep this event, otherwise drop it
186− filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo
187− filterFun r (tInfo, p)
188− | r >= p = Just tInfo
189− | otherwise = Nothing
190−
191− callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0
192−
193− go tTargetLast lastGen cb lastN = do
194− t <- getCurrentTime
195−
196− -- Generate random numbers for this poisson interval (u)
197− -- and sample-retention likelihood (p)
198− let (u, nextGen) = randomR (0,1) lastGen
199− (p :: Double, nextGen') = randomR (0,maxRate) nextGen
200−
201− -- Inter-event interval is drawn from exponential
202− -- distribution accourding to u
203− let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime
204− nEvents = lastN + 1
205− alreadyElapsed = diffUTCTime t tTargetLast
206− tTarget = addUTCTime dt tTargetLast
207− thisDelay = realToFrac $ diffUTCTime tTarget t :: Double
208− Concurrent.delay $ ceiling $ thisDelay * 1000000
209− _ <- cb (TickInfo t nEvents alreadyElapsed, p)
210− go tTarget nextGen' cb nEvents
211−
212−-- | Send events with inhomogeneous Poisson timing with the given basis
213−-- and variable rate. Provide a maxRate that you expect to support
214−inhomogeneousPoisson
215− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
216− => g
217− -> Behavior t Double
218− -> Double
219− -> UTCTime
220− -> m (Event t TickInfo)
221−inhomogeneousPoisson rnd rate maxRate t0 =
222− inhomogeneousPoissonFrom rnd rate maxRate t0 =<< getPostBuild
223−
224−-- | Block occurrences of an Event until the given number of seconds elapses without
225−-- the Event firing, at which point the last occurrence of the Event will fire.
226−debounce :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
227−debounce dt e = do
228− n :: Dynamic t Integer <- count e
229− let tagged = attachPromptlyDynWith (,) n e
230− delayed <- delay dt tagged
231− return $ attachWithMaybe (\n' (t, v) -> if n' == t then Just v else Nothing) (current n) delayed
232−
233−-- | When the given 'Event' occurs, wait the given amount of time and collect
234−-- all occurrences during that time. Then, fire the output 'Event' with the
235−-- collected output.
236−batchOccurrences :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t (Seq a))
237−batchOccurrences t newValues = do
238− let f s x = (Just newState, out)
239− where newState = case x of
240− This a -> s |> a
241− That _ -> mempty
242− These a _ -> Seq.singleton a
243− out = case x of
244− This _ -> if Seq.null s then Just () else Nothing
245− That _ -> Nothing
246− These _ _ -> Just ()
247− rec (buffer, toDelay) <- mapAccumMaybe f mempty $ align newValues delayed
248− delayed <- delay t toDelay
249− return $ tag buffer delayed
250−
251−-- | Throttle an input event, ensuring that at least a given amount of time passes between occurrences of the output event. If the input event occurs too
252−-- frequently, the output event occurs with the most recently seen input value after the given delay passes since the last occurrence of the output.
253−-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
254−throttle :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
255−throttle t e = do
256− let f (immediate, buffer) x = case x of -- (Just newState, out)
257− This a -- If only the input event fires
258− | immediate -> -- and we're in immediate mode
259− -- Immediate mode turns off, and the buffer is empty.
260− -- We fire the output event with the input event value immediately.
261− (Just (False, Nothing), Just a)
262− | otherwise -> -- and we're not in immediate mode
263− -- Immediate mode remains off, and we replace the contents of the buffer (if any) with the input value.
264− -- We don't fire the output event.
265− (Just (False, Just a), Nothing)
266− That _ -> -- If only the delayed output event fires,
267− case buffer of
268− Nothing -> -- and the buffer is empty:
269− -- Immediate mode turns back on, and the buffer remains empty.
270− -- We don't fire.
271− (Just (True, Nothing), Nothing)
272− Just b -> -- and the buffer is full:
273− -- Immediate mode remains off, and the buffer is cleared.
274− -- We fire with the buffered value.
275− (Just (False, Nothing), Just b)
276− These a _ -> -- If both the input and delayed output event fire simultaneously:
277− -- Immediate mode turns off, and the buffer is empty.
278− -- We fire with the input event's value, as it is the most recent we have seen at this moment.
279− (Just (False, Nothing), Just a)
280− rec (_, outE) <- mapAccumMaybeDyn f (True, Nothing) $ align e delayed -- We start in immediate mode with an empty buffer.
281− delayed <- delay t outE
282− return outE
283−
284−data ThrottleState b
285− = ThrottleState_Immediate
286− | ThrottleState_Buffered (ThrottleBuffer b)
287− deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
288−
289−data ThrottleBuffer b
290− = ThrottleBuffer_Empty -- Empty conflicts with lens, and hiding it would require turning
291− -- on PatternSynonyms
292− | ThrottleBuffer_Full b
293− deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
294−
295−instance Semigroup b => Semigroup (ThrottleBuffer b) where
296− x <> y = case x of
297− ThrottleBuffer_Empty -> y
298− ThrottleBuffer_Full b1 -> case y of
299− ThrottleBuffer_Empty -> x
300− ThrottleBuffer_Full b2 -> ThrottleBuffer_Full $ b1 <> b2
301− {-# INLINE (<>) #-}
302−
303−instance Semigroup b => Monoid (ThrottleBuffer b) where
304− mempty = ThrottleBuffer_Empty
305− {-# INLINE mempty #-}
306− mappend = (<>)
307− {-# INLINE mappend #-}
308−
309−-- | Throttle an input event, ensuring that the output event doesn't occur more often than you are ready for it. If the input event occurs too
310−-- frequently, the output event will contain semigroup-based summaries of the input firings that happened since the last output firing.
311−-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
312−-- The first parameter is a function that receives access to the output event, and should construct an event that fires when the receiver is
313−-- ready for more input. For example, using @delay 20@ would give a simple time-based throttle.
314−--
315−-- NB: The provided lag function must *actually* delay the event.
316−throttleBatchWithLag :: (MonadFix m, MonadHold t m, PerformEvent t m, Semigroup a) => (Event t () -> m (Event t ())) -> Event t a -> m (Event t a)
317−-- Invariants:
318−-- * Immediate mode must turn off whenever output is produced.
319−-- * Output must be produced whenever immediate mode turns from on to off.
320−-- * Immediate mode can only go from off to on when the delayed event fires.
321−-- * Every input firing must go into either an immediate output firing or the
322−-- buffer, but not both.
323−-- * An existing full buffer must either stay in the buffer or go to output,
324−-- but not both.
325−throttleBatchWithLag lag e = do
326− let f state x = case x of -- (Just $ newState, out)
327− This a -> -- If only the input event fires
328− case state of
329− ThrottleState_Immediate -> -- and we're in immediate mode
330− -- Immediate mode turns off, and the buffer is empty.
331− -- We fire the output event with the input event value immediately.
332− (Just $ ThrottleState_Buffered $ ThrottleBuffer_Empty, Just a)
333− ThrottleState_Buffered b -> -- and we're not in immediate mode
334− -- Immediate mode remains off, and we accumulate the input value.
335− -- We don't fire the output event.
336− (Just $ ThrottleState_Buffered $ b <> ThrottleBuffer_Full a, Nothing)
337− That _ -> -- If only the delayed output event fires,
338− case state of
339− ThrottleState_Immediate -> -- and we're in immediate mode
340− -- Nothing happens.
341− (Nothing, Nothing)
342− ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
343− -- Immediate mode turns back on, and the buffer remains empty.
344− -- We don't fire.
345− (Just ThrottleState_Immediate, Nothing)
346− ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
347− -- Immediate mode remains off, and the buffer is cleared.
348− -- We fire with the buffered value.
349− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just b)
350− These a _ -> -- If both the input and delayed output event fire simultaneously:
351− case state of
352− ThrottleState_Immediate -> -- and we're in immediate mode
353− -- Immediate mode turns off, and the buffer is empty.
354− -- We fire with the input event's value, as it is the most recent we have seen at this moment.
355− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
356− ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
357− -- Immediate mode stays off, and the buffer remains empty.
358− -- We fire with the input event's value.
359− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
360− ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
361− -- Immediate mode remains off, and the buffer is cleared.
362− -- We fire with everything including the buffered value.
363− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just (b <> a))
364− rec (_stateDyn, outE) <- mapAccumMaybeDyn f
365− ThrottleState_Immediate -- We start in immediate mode with an empty buffer.
366− (align e delayed)
367− delayed <- lag (void outE)
368− return outE
369−
370−#ifdef USE_TEMPLATE_HASKELL
371−makeLensesWith (lensRules & simpleLenses .~ True) ''TickInfo
372−#else
373−tickInfo_lastUTC :: Lens' TickInfo UTCTime
374−tickInfo_lastUTC f (TickInfo x1 x2 x3) = (\y -> TickInfo y x2 x3) <$> f x1
375−{-# INLINE tickInfo_lastUTC #-}
376−
377−tickInfo_n :: Lens' TickInfo Integer
378−tickInfo_n f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 y x3) <$> f x2
379−{-# INLINE tickInfo_n #-}
380−
381−tickInfo_alreadyElapsed :: Lens' TickInfo NominalDiffTime
382−tickInfo_alreadyElapsed f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 x2 y) <$> f x3
383−{-# INLINE tickInfo_alreadyElapsed #-}
384−#endif
src/Reflex/TriggerEvent/Base.hsdeleted−148
@@ -1,148 +0,0 @@
1−-- | This module defines 'TriggerEventT', the standard implementation of
2−-- 'TriggerEvent'.
3−{-# LANGUAGE DeriveFunctor #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE TypeFamilies #-}
8−module Reflex.TriggerEvent.Base
9− ( TriggerEventT (..)
10− , runTriggerEventT
11− , askEvents
12− , TriggerInvocation (..)
13− , EventTriggerRef (..)
14− ) where
15−
16−import Control.Applicative (liftA2)
17−import Control.Concurrent
18−import Control.Monad.Exception
19−import Control.Monad.Primitive
20−import Control.Monad.Reader
21−import Control.Monad.Ref
22−import Data.Coerce
23−import Data.Dependent.Sum
24−import Data.IORef
25−import Data.Monoid ((<>))
26−import qualified Data.Semigroup as S
27−import Reflex.Class
28−import Reflex.Adjustable.Class
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.PostBuild.Class
32−import Reflex.TriggerEvent.Class
33−
34−-- | A value with which to fire an 'Event', as well as a callback to invoke
35−-- after its propagation has completed.
36−data TriggerInvocation a = TriggerInvocation a (IO ())
37−
38−-- | A reference to an 'EventTrigger' suitable for firing with 'TriggerEventT'.
39−newtype EventTriggerRef t a = EventTriggerRef { unEventTriggerRef :: IORef (Maybe (EventTrigger t a)) }
40−
41−-- | A basic implementation of 'TriggerEvent'.
42−newtype TriggerEventT t m a = TriggerEventT { unTriggerEventT :: ReaderT (Chan [DSum (EventTriggerRef t) TriggerInvocation]) m a }
43− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
44−
45−-- | Run a 'TriggerEventT' action. The argument should be a 'Chan' into which
46−-- 'TriggerInvocation's can be passed; it is expected that some other thread
47−-- will be responsible for popping values out of the 'Chan' and firing their
48−-- 'EventTrigger's.
49−runTriggerEventT :: TriggerEventT t m a -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a
50−runTriggerEventT = runReaderT . unTriggerEventT
51−
52−instance MonadTrans (TriggerEventT t) where
53− {-# INLINABLE lift #-}
54− lift = TriggerEventT . lift
55−
56−instance PrimMonad m => PrimMonad (TriggerEventT t m) where
57− type PrimState (TriggerEventT t m) = PrimState m
58− {-# INLINABLE primitive #-}
59− primitive = lift . primitive
60−
61−instance PerformEvent t m => PerformEvent t (TriggerEventT t m) where
62− type Performable (TriggerEventT t m) = Performable m
63− {-# INLINABLE performEvent_ #-}
64− performEvent_ e = lift $ performEvent_ e
65− {-# INLINABLE performEvent #-}
66− performEvent e = lift $ performEvent e
67−
68−instance PostBuild t m => PostBuild t (TriggerEventT t m) where
69− {-# INLINABLE getPostBuild #-}
70− getPostBuild = lift getPostBuild
71−
72−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (TriggerEventT t m) where
73− {-# INLINABLE newEventWithTrigger #-}
74− newEventWithTrigger = lift . newEventWithTrigger
75− {-# INLINABLE newFanEventWithTrigger #-}
76− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
77−
78−instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (TriggerEventT t m) where
79− {-# INLINABLE newTriggerEvent #-}
80− newTriggerEvent = do
81− (e, t) <- newTriggerEventWithOnComplete
82− return (e, \a -> t a $ return ())
83− {-# INLINABLE newTriggerEventWithOnComplete #-}
84− newTriggerEventWithOnComplete = do
85− events <- askEvents
86− (eResult, reResultTrigger) <- lift newEventWithTriggerRef
87− return . (,) eResult $ \a cb ->
88− writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
89− {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
90− newEventWithLazyTriggerWithOnComplete f = do
91− events <- askEvents
92− lift . newEventWithTrigger $ \t ->
93− f $ \a cb -> do
94− reResultTrigger <- newRef $ Just t
95− writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
96−
97−instance MonadRef m => MonadRef (TriggerEventT t m) where
98− type Ref (TriggerEventT t m) = Ref m
99− {-# INLINABLE newRef #-}
100− newRef = lift . newRef
101− {-# INLINABLE readRef #-}
102− readRef = lift . readRef
103− {-# INLINABLE writeRef #-}
104− writeRef r = lift . writeRef r
105−
106−instance MonadAtomicRef m => MonadAtomicRef (TriggerEventT t m) where
107− {-# INLINABLE atomicModifyRef #-}
108− atomicModifyRef r = lift . atomicModifyRef r
109−
110−instance MonadSample t m => MonadSample t (TriggerEventT t m) where
111− {-# INLINABLE sample #-}
112− sample = lift . sample
113−
114−instance MonadHold t m => MonadHold t (TriggerEventT t m) where
115− {-# INLINABLE hold #-}
116− hold v0 v' = lift $ hold v0 v'
117− {-# INLINABLE holdDyn #-}
118− holdDyn v0 v' = lift $ holdDyn v0 v'
119− {-# INLINABLE holdIncremental #-}
120− holdIncremental v0 v' = lift $ holdIncremental v0 v'
121− {-# INLINABLE buildDynamic #-}
122− buildDynamic a0 = lift . buildDynamic a0
123− {-# INLINABLE headE #-}
124− headE = lift . headE
125−
126−instance Adjustable t m => Adjustable t (TriggerEventT t m) where
127− {-# INLINABLE runWithReplace #-}
128− runWithReplace (TriggerEventT a0) a' = TriggerEventT $ runWithReplace a0 (coerceEvent a')
129− {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
130− traverseIntMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseIntMapWithKeyWithAdjust (coerce . f) dm0 dm'
131− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
132− traverseDMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
133− {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}
134− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
135−
136−-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
137−instance (Monoid a, Applicative m) => Monoid (TriggerEventT t m a) where
138− mempty = pure mempty
139− mappend = (<>)
140−
141−instance (S.Semigroup a, Applicative m) => S.Semigroup (TriggerEventT t m a) where
142− (<>) = liftA2 (S.<>)
143−
144−
145−-- | Retrieve the current 'Chan'; event trigger invocations pushed into it will
146−-- be fired.
147−askEvents :: Monad m => TriggerEventT t m (Chan [DSum (EventTriggerRef t) TriggerInvocation])
148−askEvents = TriggerEventT ask
src/Reflex/TriggerEvent/Class.hsdeleted−50
@@ -1,50 +0,0 @@
1−-- | This module defines 'TriggerEvent', which describes actions that may create
2−-- new 'Event's that can be triggered from 'IO'.
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE UndecidableInstances #-}
7−module Reflex.TriggerEvent.Class
8− ( TriggerEvent (..)
9− ) where
10−
11−import Reflex.Class
12−
13−import Control.Monad.Reader
14−import Control.Monad.State
15−import qualified Control.Monad.State.Strict as Strict
16−
17−--TODO: Shouldn't have IO hard-coded
18−-- | 'TriggerEvent' represents actions that can create 'Event's that can be
19−-- triggered by 'IO' actions.
20−class Monad m => TriggerEvent t m | m -> t where
21− -- | Create a triggerable 'Event'. Whenever the resulting function is called,
22− -- the resulting 'Event' will fire at some point in the future. Note that
23− -- this may not be synchronous.
24− newTriggerEvent :: m (Event t a, a -> IO ())
25− -- | Like 'newTriggerEvent', but the callback itself takes another callback,
26− -- to be invoked once the requested 'Event' occurrence has finished firing.
27− -- This allows synchronous operation.
28− newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow
29− -- | Like 'newTriggerEventWithOnComplete', but with setup and teardown. This
30− -- relatively complex type signature allows any external listeners to be
31− -- subscribed lazily and then removed whenever the returned 'Event' is no
32− -- longer being listened to. Note that the setup/teardown may happen multiple
33− -- times, and there is no guarantee that the teardown will be executed
34− -- promptly, or even at all, in the case of program termination.
35− newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)
36−
37−instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
38− newTriggerEvent = lift newTriggerEvent
39− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
40− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
41−
42−instance TriggerEvent t m => TriggerEvent t (StateT s m) where
43− newTriggerEvent = lift newTriggerEvent
44− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
45− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
46−
47−instance TriggerEvent t m => TriggerEvent t (Strict.StateT s m) where
48− newTriggerEvent = lift newTriggerEvent
49− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
50− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
src/Reflex/Widget/Basic.hsdeleted−44
@@ -1,44 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExplicitForAll #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−{-# LANGUAGE RecursiveDo #-}
5−#ifdef USE_REFLEX_OPTIMIZER
6−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
7−#endif
8−
9−module Reflex.Widget.Basic where
10−
11−import Control.Monad.Fix (MonadFix)
12−import Data.Map (Map)
13−
14−import Reflex.Class
15−import Reflex.Adjustable.Class
16−import Reflex.Patch.MapWithMove
17−
18−
19−-- | Build sortable content in such a way that re-sorting it can cause minimal
20−-- disruption to an existing context.
21−--
22−-- Naively re-sorting a list of images would destroy every image and add them back
23−-- in the new order. This framework is able to avoid that by preserving the
24−-- identity of each image and simply moving it to the new location.
25−--
26−-- Example:
27−--
28−-- > let sortByFst = buttonA $> comparing fst
29−-- > sortBySnd = buttonB $> comparing snd
30−-- > sortEvent = leftmost [sortByFst, sortBySnd]
31−-- > sortableList
32−-- > (\k v -> text $ "\n" ++ show k ++ " " ++ v) -- show each element on a new line
33−-- > (Map.fromList $ zip [0..] [(3, "a"), (2, "b"), (1, "c")])
34−-- > sortEvent
35−sortableList :: forall t m k v a. (MonadHold t m, MonadFix m, Adjustable t m, Ord k)
36− => (k -> v -> m a) -- ^ Function to render the content for each key/value pair
37− -> Map k v -- ^ The sortable list with an initial ordering determined by the @Map@ keys in ascending order
38− -> Event t (v -> v -> Ordering) -- ^ An event carrying a sort function for the list
39− -> m (Map k a)
40−sortableList f m0 reSortFunc = do
41− rec let reSortPatch = attachWith (flip patchThatSortsMapWith) (currentIncremental m) reSortFunc
42− m <- holdIncremental m0 reSortPatch
43− (results, _) <- mapMapWithAdjustWithMove f m0 reSortPatch
44− pure results
src/Reflex/Workflow.hsdeleted−50
@@ -1,50 +0,0 @@
1−{-# LANGUAGE RecursiveDo #-}
2−{-# LANGUAGE ScopedTypeVariables #-}
3−-- |
4−-- Module:
5−-- Reflex.Workflow
6−-- Description:
7−-- Provides a convenient way to describe a series of interrelated widgets that
8−-- can send data to, invoke, and replace one another. Useful for modeling user interface
9−-- "workflows."
10−module Reflex.Workflow (
11− Workflow (..)
12− , workflow
13− , workflowView
14− , mapWorkflow
15− , mapWorkflowCheap
16− ) where
17−
18−import Control.Arrow ((***))
19−import Control.Monad.Fix (MonadFix)
20−
21−import Reflex.Class
22−import Reflex.Adjustable.Class
23−import Reflex.Network
24−import Reflex.NotReady.Class
25−import Reflex.PostBuild.Class
26−
27−-- | A widget in a workflow
28−-- When the 'Event' returned by a 'Workflow' fires, the current 'Workflow' is replaced by the one inside the firing 'Event'. A series of 'Workflow's must share the same return type.
29−newtype Workflow t m a = Workflow { unWorkflow :: m (a, Event t (Workflow t m a)) }
30−
31−-- | Runs a 'Workflow' and returns the 'Dynamic' result of the 'Workflow' (i.e., a 'Dynamic' of the value produced by the current 'Workflow' node, and whose update 'Event' fires whenever one 'Workflow' is replaced by another).
32−workflow :: forall t m a. (Reflex t, Adjustable t m, MonadFix m, MonadHold t m) => Workflow t m a -> m (Dynamic t a)
33−workflow w0 = do
34− rec eResult <- networkHold (unWorkflow w0) $ fmap unWorkflow $ switch $ snd <$> current eResult
35− return $ fmap fst eResult
36−
37−-- | Similar to 'workflow', but outputs an 'Event' that fires whenever the current 'Workflow' is replaced by the next 'Workflow'.
38−workflowView :: forall t m a. (Reflex t, NotReady t m, Adjustable t m, MonadFix m, MonadHold t m, PostBuild t m) => Workflow t m a -> m (Event t a)
39−workflowView w0 = do
40− rec eResult <- networkView . fmap unWorkflow =<< holdDyn w0 eReplace
41− eReplace <- fmap switch $ hold never $ fmap snd eResult
42− return $ fmap fst eResult
43−
44−-- | Map a function over a 'Workflow', possibly changing the resturn type.
45−mapWorkflow :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
46−mapWorkflow f (Workflow x) = Workflow (fmap (f *** fmap (mapWorkflow f)) x)
47−
48−-- | Map a "cheap" function over a 'Workflow'. Refer to the documentation for 'pushCheap' for more information and performance considerations.
49−mapWorkflowCheap :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
50−mapWorkflowCheap f (Workflow x) = Workflow (fmap (f *** fmapCheap (mapWorkflowCheap f)) x)
test/EventWriterT.hsdeleted−132
@@ -1,132 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE RecursiveDo #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−module Main where
7−
8−import Control.Lens
9−import Control.Monad
10−import Control.Monad.Fix
11−import qualified Data.Dependent.Map as DMap
12−import Data.Functor.Misc
13−import qualified Data.Map as M
14−import Data.These
15−
16−import Reflex
17−import Reflex.EventWriter.Base
18−import Test.Run
19−
20−main :: IO ()
21−main = do
22− os1@[[Just [10,9,8,7,6,5,4,3,2,1]]] <- runApp' (unwrapApp testOrdering) $
23− [ Just ()
24− ]
25− print os1
26− os2@[[Just [1,3,5,7,9]],[Nothing,Nothing],[Just [2,4,6,8,10]],[Just [2,4,6,8,10],Nothing]]
27− <- runApp' (unwrapApp testSimultaneous) $ map Just $
28− [ This ()
29− , That ()
30− , This ()
31− , These () ()
32− ]
33− print os2
34− os3@[[Nothing, Just [2]]] <- runApp' (unwrapApp testMoribundTellEvent) [Just ()]
35− print os3
36− os4@[[Nothing, Just [2]]] <- runApp' (unwrapApp testMoribundTellEventDMap) [Just ()]
37− print os4
38− os5@[[Nothing, Just [1, 2]]] <- runApp' (unwrapApp testLiveTellEventDMap) [Just ()]
39− print os5
40− os6 <- runApp' (unwrapApp delayedPulse) [Just ()]
41− print os6
42− let ![[Nothing, Nothing]] = os6
43− return ()
44−
45−unwrapApp :: (Reflex t, Monad m) => (a -> EventWriterT t [Int] m ()) -> a -> m (Event t [Int])
46−unwrapApp x appIn = do
47− ((), e) <- runEventWriterT $ x appIn
48− return e
49−
50−testOrdering :: (Reflex t, Monad m) => Event t () -> EventWriterT t [Int] m ()
51−testOrdering pulse = do
52− forM_ [10,9..1] $ \i -> tellEvent ([i] <$ pulse)
53− return ()
54−
55−testSimultaneous :: (Reflex t, Adjustable t m, MonadHold t m) => Event t (These () ()) -> EventWriterT t [Int] m ()
56−testSimultaneous pulse = do
57− let e0 = fmapMaybe (^? here) pulse
58− e1 = fmapMaybe (^? there) pulse
59− forM_ [1,3..9] $ \i -> runWithReplace (tellEvent ([i] <$ e0)) $ ffor e1 $ \_ -> tellEvent ([i+1] <$ e0)
60− return ()
61−
62−-- | Test that a widget telling and event which fires at the same time it has been replaced
63−-- doesn't count along with the new widget.
64−testMoribundTellEvent
65− :: forall t m
66− . ( Reflex t
67− , Adjustable t m
68− , MonadHold t m
69− , MonadFix m
70− )
71− => Event t ()
72− -> EventWriterT t [Int] m ()
73−testMoribundTellEvent pulse = do
74− rec let tellIntOnReplace :: Int -> EventWriterT t [Int] m ()
75− tellIntOnReplace x = tellEvent $ [x] <$ rwrFinished
76− (_, rwrFinished) <- runWithReplace (tellIntOnReplace 1) $ tellIntOnReplace 2 <$ pulse
77− return ()
78−
79−-- | The equivalent of 'testMoribundTellEvent' for 'traverseDMapWithKeyWithAdjust'.
80−testMoribundTellEventDMap
81− :: forall t m
82− . ( Reflex t
83− , Adjustable t m
84− , MonadHold t m
85− , MonadFix m
86− )
87− => Event t ()
88− -> EventWriterT t [Int] m ()
89−testMoribundTellEventDMap pulse = do
90− rec let tellIntOnReplace :: Int -> EventWriterT t [Int] m ()
91− tellIntOnReplace x = tellEvent $ [x] <$ rwrFinished
92− (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-
93− traverseDMapWithKeyWithAdjust
94− (\(Const2 ()) (Identity v) -> Identity . const v <$> tellIntOnReplace v)
95− (mapToDMap $ M.singleton () 1)
96− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)
97− return ()
98−
99−-- | Ensures that elements which are _not_ removed can still fire 'tellEvent's
100−-- during the same frame as other elements are updated.
101−testLiveTellEventDMap
102− :: forall t m
103− . ( Reflex t
104− , Adjustable t m
105− , MonadHold t m
106− , MonadFix m
107− )
108− => Event t ()
109− -> EventWriterT t [Int] m ()
110−testLiveTellEventDMap pulse = do
111− rec let tellIntOnReplace :: Int -> EventWriterT t [Int] m ()
112− tellIntOnReplace x = tellEvent $ [x] <$ rwrFinished
113− (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-
114− traverseDMapWithKeyWithAdjust
115− (\(Const2 k) (Identity ()) -> Identity <$> tellIntOnReplace k)
116− (mapToDMap $ M.singleton 1 ())
117− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)
118− return ()
119−
120−delayedPulse
121− :: forall t m
122− . ( Reflex t
123− , Adjustable t m
124− , MonadHold t m
125− , MonadFix m
126− )
127− => Event t ()
128− -> EventWriterT t [Int] m ()
129−delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do
130− -- This has the effect of delaying pulse' from pulse
131− (_, pulse') <- runWithReplace (pure ()) $ pure [1] <$ pulse
132− tellEvent pulse'
test/GC.hsdeleted−100
@@ -1,100 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE GADTs #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE RankNTypes #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE TypeFamilies #-}
7−module Main where
8−
9−import Control.Monad
10−import Control.Monad.IO.Class
11−import Control.Monad.Ref
12−import Data.Align
13−import Data.Dependent.Map (DMap)
14−import qualified Data.Dependent.Map as DMap
15−import Data.Dependent.Sum
16−import Data.Functor.Identity
17−import Data.GADT.Compare
18−import Data.IORef
19−import Data.Semigroup
20−import Data.These
21−
22−import Data.Functor.Misc
23−import Reflex.Patch
24−
25−import qualified Reflex.Host.Class as Host
26−import qualified Reflex.Spider.Internal as S
27−
28−import System.Exit
29−import System.Mem
30−
31−main :: IO ()
32−main = do
33− ref <- newIORef Nothing
34− hostPerf ref
35− readIORef ref >>= maybe exitFailure (putStrLn . ("Result " <>) . show)
36−
37−hostPerf :: IORef (Maybe Int) -> IO ()
38−hostPerf ref = S.runSpiderHost $ do
39− ---- body
40− liftIO $ putStrLn "#creating triggers"
41− (response', responseTrigger) <- Host.newEventWithTriggerRef
42− (eadd', addTriggerRef) <- Host.newEventWithTriggerRef
43− let response = S.unSpiderEvent response'
44− eadd = S.unSpiderEvent eadd'
45− liftIO $ putStrLn "#creating event graph"
46− eventToPerform <- Host.runHostFrame $ do
47− (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity))
48− <- S.SpiderHostFrame
49− $ fmap ( S.merge
50− . S.dynamicHold)
51− $ S.hold DMap.empty
52− -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained
53− $ (\e -> S.Event $ \sub -> do
54− (s, o) <- S.subscribeAndRead e $ sub
55− { S.subscriberPropagate = S.subscriberPropagate sub
56− }
57− return (s, o))
58− $ runIdentity <$> S.select
59− (S.fan $ S.pushCheap (return . Just . mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e)) response)
60− (WrapArg Request)
61− return $ alignWith (mergeThese (<>))
62− (flip S.pushCheap eadd $ \_ -> return $ Just $ DMap.singleton Request $ do
63− liftIO $ putStrLn "#eadd fired"
64− return $ PatchDMap $ DMap.singleton (Const2 (1 :: Int)) $ ComposeMaybe $ Just
65− $ S.pushCheap (return . Just . DMap.singleton Action . (\_ -> liftIO (writeIORef ref (Just 1)))) $ eadd)
66− (flip S.pushCheap reqMap $ \m -> return $ Just $ mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m)
67− ---- epilogue
68− eventToPerformHandle <- Host.subscribeEvent (S.SpiderEvent eventToPerform)
69− liftIO $ putStrLn "#performing GC" >> performMajorGC
70− liftIO $ putStrLn "#attempting to fire eadd"
71− mAddTrigger <- readRef addTriggerRef
72− forM_ mAddTrigger $ \t -> replicateM_ 2 $ do
73− liftIO $ putStrLn "#firing eadd"
74− mToPerform <- Host.fireEventsAndRead [t :=> Identity ()] $ sequence =<< Host.readEvent eventToPerformHandle
75− case mToPerform of
76− Nothing -> return ()
77− Just toPerform -> do
78− responses <- Host.runHostFrame $ DMap.traverseWithKey (\_ v -> Identity <$> v) toPerform
79− mrt <- readRef responseTrigger
80− let followupEventTriggers = case mrt of
81− Just rt -> [rt :=> Identity responses]
82− Nothing -> []
83− Host.fireEventsAndRead followupEventTriggers $ return ()
84− return ()
85− return ()
86−
87−data Tell a where
88− Action :: Tell ()
89− Request :: Tell (PatchDMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) (S.Event S.Global))
90−
91−instance GEq Tell where
92− geq Action Action = Just Refl
93− geq Request Request = Just Refl
94− geq _ _ = Nothing
95−
96−instance GCompare Tell where
97− gcompare Action Action = GEQ
98− gcompare Request Request = GEQ
99− gcompare Action Request = GLT
100− gcompare Request Action = GGT
test/QueryT.hsdeleted−138
@@ -1,138 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE StandaloneDeriving #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−
11−import Control.Lens
12−import Control.Monad.Fix
13−import Data.Align
14−import qualified Data.AppendMap as AMap
15−import Data.Functor.Misc
16−import Data.Map (Map)
17−import qualified Data.Map as Map
18−import Data.Map.Monoidal (MonoidalMap)
19−import Data.Semigroup
20−import Data.These
21−
22−import Reflex
23−import Reflex.Patch.MapWithMove
24−import Test.Run
25−
26−newtype MyQuery = MyQuery SelectedCount
27− deriving (Show, Read, Eq, Ord, Monoid, Semigroup, Additive, Group)
28−
29−instance Query MyQuery where
30− type QueryResult MyQuery = ()
31− crop _ _ = ()
32−
33−instance (Ord k, Query a, Eq (QueryResult a), Align (MonoidalMap k)) => Query (Selector k a) where
34− type QueryResult (Selector k a) = Selector k (QueryResult a)
35− crop q r = undefined
36−
37−newtype Selector k a = Selector { unSelector :: MonoidalMap k a }
38− deriving (Show, Read, Eq, Ord, Functor)
39−
40−#if !(MIN_VERSION_monoidal_containers(0,4,1))
41−deriving instance Ord k => Align (MonoidalMap k)
42−#endif
43−
44−instance (Ord k, Eq a, Monoid a, Align (MonoidalMap k)) => Semigroup (Selector k a) where
45− (Selector a) <> (Selector b) = Selector $ fmapMaybe id $ f a b
46− where
47− f = alignWith $ \case
48− This x -> Just x
49− That y -> Just y
50− These x y ->
51− let z = x `mappend` y
52− in if z == mempty then Nothing else Just z
53−
54−instance (Ord k, Eq a, Monoid a, Align (MonoidalMap k)) => Monoid (Selector k a) where
55− mempty = Selector AMap.empty
56− mappend = (<>)
57−
58−instance (Eq a, Ord k, Group a, Align (MonoidalMap k)) => Group (Selector k a) where
59− negateG = fmap negateG
60−
61−instance (Eq a, Ord k, Group a, Align (MonoidalMap k)) => Additive (Selector k a)
62−
63−main :: IO ()
64−main = do
65− [0, 1, 1, 0] <- fmap (map fst . concat) $
66− runApp (testQueryT testRunWithReplace) () $ map (Just . That) $
67− [ That (), This (), That () ]
68− [0, 1, 1, 0] <- fmap (map fst . concat) $
69− runApp (testQueryT testSequenceDMapWithAdjust) () $ map (Just . That) $
70− [ That (), This (), That () ]
71− [0, 1, 1, 0] <- fmap (map fst . concat) $
72− runApp (testQueryT testSequenceDMapWithAdjustWithMove) () $ map (Just . That) $
73− [ That (), This (), That () ]
74− return ()
75−
76−testQueryT :: (Reflex t, MonadFix m)
77− => (Event t () -> Event t () -> QueryT t (Selector Int MyQuery) m ())
78− -> AppIn t () (These () ())
79− -> m (AppOut t Int Int)
80−testQueryT w (AppIn _ pulse) = do
81− let replace = fmapMaybe (^? here) pulse
82− increment = fmapMaybe (^? there) pulse
83− (_, q) <- runQueryT (w replace increment) $ pure mempty
84− let qDyn = head . AMap.keys . unSelector <$> incrementalToDynamic q
85− return $ AppOut
86− { _appOut_behavior = current qDyn
87− , _appOut_event = updated qDyn
88− }
89−
90−testRunWithReplace :: ( Reflex t
91− , Adjustable t m
92− , MonadHold t m
93− , MonadFix m
94− , MonadQuery t (Selector Int MyQuery) m)
95− => Event t ()
96− -> Event t ()
97− -> m ()
98−testRunWithReplace replace increment = do
99− let w = do
100− n <- count increment
101− queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
102− _ <- runWithReplace w $ w <$ replace
103− return ()
104−
105−testSequenceDMapWithAdjust :: ( Reflex t
106− , Adjustable t m
107− , MonadHold t m
108− , MonadFix m
109− , MonadQuery t (Selector Int MyQuery) m)
110− => Event t ()
111− -> Event t ()
112− -> m ()
113−testSequenceDMapWithAdjust replace increment = do
114− _ <- listHoldWithKey (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do
115− n <- count increment
116− queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
117− return ()
118−
119−testSequenceDMapWithAdjustWithMove :: ( Reflex t
120− , Adjustable t m
121− , MonadHold t m
122− , MonadFix m
123− , MonadQuery t (Selector Int MyQuery) m)
124− => Event t ()
125− -> Event t ()
126− -> m ()
127−testSequenceDMapWithAdjustWithMove replace increment = do
128− _ <- listHoldWithKeyWithMove (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do
129− n <- count increment
130− queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
131− return ()
132−
133−-- scam it out to test traverseDMapWithAdjustWithMove
134−listHoldWithKeyWithMove :: forall t m k v a. (Ord k, MonadHold t m, Adjustable t m) => Map k v -> Event t (Map k (Maybe v)) -> (k -> v -> m a) -> m (Dynamic t (Map k a))
135−listHoldWithKeyWithMove m0 m' f = do
136− (n0, n') <- mapMapWithAdjustWithMove f m0 $ ffor m' $ PatchMapWithMove . Map.map (\v -> NodeInfo (maybe From_Delete From_Insert v) Nothing)
137− incrementalToDynamic <$> holdIncremental n0 n'
138−-- -}
test/Reflex/Bench/Focused.hsdeleted−369
@@ -1,369 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE RecursiveDo #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeSynonymInstances #-}
11−
12−module Reflex.Bench.Focused where
13−
14−import Reflex
15−import Reflex.TestPlan
16−
17−import Control.Applicative
18−import Control.Monad
19−import Control.Monad.Fix
20−import Control.Monad.Identity
21−import Data.Traversable (for, traverse)
22−
23−import qualified Data.Dependent.Map as DMap
24−import Data.Map (Map)
25−import qualified Data.Map as Map
26−import Data.Maybe
27−
28−import Data.Functor.Misc
29−
30−import Data.List
31−import Data.List.Split
32−import Data.Tuple
33−
34−import Data.Monoid
35−import Data.Word
36−
37−import Control.DeepSeq
38−
39−import Prelude hiding (concat, sum)
40−
41−
42−mergeTree :: Num a => (Monoid (f [a]), Functor f) => Int -> [f a] -> f a
43−mergeTree n es | length es <= n = sum' es
44− | otherwise = mergeTree n subTrees
45− where
46− merges = chunksOf n es
47− subTrees = map sum' merges
48− sum' = fmap sum . mconcat . fmap (fmap (:[]) )
49−
50−mergeListDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
51−mergeListDyn = mconcat . fmap (fmap pure)
52−
53−mergeTreeDyn :: (Num a, Reflex t) => Int -> [Dynamic t a] -> Dynamic t a
54−mergeTreeDyn n dyns | length dyns <= n = sumDyns dyns
55− | otherwise = mergeTreeDyn n $ fmap sumDyns merges
56− where
57− merges = chunksOf n dyns
58− sumDyns = fmap sum . mergeListDyn
59−
60−
61−
62−-- N events all firing for N frames
63−continuous :: TestPlan t m => Word -> Word -> m [Event t Word]
64−continuous n frames = for [1..n] $ \i -> plan $ (, i) <$> [1..frames]
65−
66−-- Fire N events once every P frames for total N frames (interspersed evenly)
67−occasional :: TestPlan t m => Word -> Word -> Word -> m [Event t Word]
68−occasional n period frames = traverse plan $ zipWith occs [1..] phases
69− where
70− phases = take (fromIntegral n) $ concat (repeat [1..period])
71− occs i phase = (, i) <$> [1, phase+1..frames]
72−
73−
74−
75−-- Event which never fires (but isn't 'never')
76−never' :: TestPlan t m => m (Event t Word)
77−never' = plan []
78−
79−
80−-- Event which fires once on first frame
81−event :: TestPlan t m => m (Event t Word)
82−event = plan [(1, 0)]
83−
84−-- Event which fires constantly over N frames
85−events :: TestPlan t m => Word -> m (Event t Word)
86−events n = plan $ (\i -> (i, i)) <$> [1..n]
87−
88−
89−-- N events all originating from one event
90−fmapFan :: Reflex t => Word -> Event t Word -> [Event t Word]
91−fmapFan n e = (\i -> (+i) <$> e) <$> [1..n]
92−
93−
94−-- Make a fan using the value in the event converting it to a singleton Map
95−-- use a fan of size n (key is the value mod n)
96−fanMerge :: Reflex t => Word -> Event t Word -> Event t Word
97−fanMerge n e = leftmost $ s <$> [0..n - 1] where
98− s k = select f (Const2 k)
99− f = fan (toMap <$> e)
100− toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k)
101−
102−-- Dumb version of the above using simple fmapMaybe to filter
103−fmapFanMerge :: Reflex t => Word -> Event t Word -> Event t Word
104−fmapFanMerge n e = leftmost $ s <$> [0..n - 1] where
105− s k = flip fmapMaybe e $ \j -> if k == j `mod` n
106− then Just k
107− else Nothing
108−
109−
110−
111−-- Create an Event with a Map which is dense to size N
112−denseMap :: TestPlan t m => Word -> m (Event t (Map Word Word))
113−denseMap n = plan [(1, m)] where
114− m = Map.fromList $ zip [1..n] [1..n]
115−
116−iter :: (a -> a) -> Word -> a -> a
117−iter _ 0 a = a
118−iter f n a = iter f (n - 1) (f a)
119−
120−iterM :: Monad m => (a -> m a) -> Word -> a -> m a
121−iterM _ 0 a = return a
122−iterM f n a = iterM f (n - 1) =<< f a
123−
124−fmapChain :: (Functor f) => Word -> f Word -> f Word
125−fmapChain = iter (fmap (+1))
126−
127−mapDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
128−mapDynChain = iterM (return . fmap (+1))
129−
130−joinDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
131−joinDynChain = iterM (\d -> return $ join $ fmap (const d) d)
132−
133−combineDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
134−combineDynChain = iterM (\d -> return $ zipDynWith (+) d d)
135−
136−pingPong :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> Event t a -> m (Event t a)
137−pingPong e1 e2 = do
138− rec
139− d <- foldDyn (const swap) (e1, e2) e
140− let e = switch (fst <$> current d)
141− return e
142−
143−switchFactors :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
144−switchFactors 0 e = return e
145−switchFactors i e = do
146− b <- hold ((+1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)
147− switchFactors (i - 1) (switch b)
148−
149−
150−switchChain :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
151−switchChain = iterM (\e -> pingPong e ((+1) <$> e))
152−
153−
154−switchChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
155−switchChain2 = iterM (\e -> pingPong e ((+1) <$> leftmost [e, e]))
156−
157−switchPromptlyChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
158−switchPromptlyChain = iterM $ \e ->
159− switchPromptlyDyn <$> holdDyn e (e <$ e)
160−
161−
162−coinChain :: Reflex t => Word -> Event t Word -> Event t Word
163−coinChain = iter $ \e -> coincidence (e <$ e)
164−
165−fanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
166−fanMergeChain width = iter $ fanMerge width
167−
168−fmapFanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
169−fmapFanMergeChain width = iter $ fmapFanMerge width
170−
171−-- | Data type for a collection (a map) which is updated by providing differences
172−data UpdatedMap t k a = UpdatedMap (Map k a) (Event t (Map k (Maybe a)))
173−
174−-- This will hopefully become a primitive (faster!)
175−switchMergeEvents :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
176−switchMergeEvents mapChanges = switch . fmap mergeMap <$> holdMap mapChanges
177−
178−-- switchMergeMaybe :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
179−-- switchMergeMaybe (UpdatedMap initial changes) = switchMergeMap initial (fmap (fromMaybe never) <$> changes)
180−
181−switchMergeBehaviors :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Behavior t a) -> m (Behavior t (Map k a))
182−switchMergeBehaviors mapChanges = pull . joinMap <$> holdMap mapChanges
183− where joinMap m = traverse sample =<< sample m
184−
185−-- | Turn an UpdatedMap into a Dynamic by applying the differences to the initial value
186−holdMapDyn :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Dynamic t (Map k a))
187−holdMapDyn (UpdatedMap initial changes) = foldDyn (flip (Map.foldrWithKey modify)) initial changes
188−
189− where
190− modify k Nothing items = Map.delete k items
191− modify k (Just item) items = Map.insert k item items
192−
193−
194−-- | Hold an UpdatedMap as a behavior by applying differences to the initial value
195−holdMap :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Behavior t (Map k a))
196−holdMap = (current <$>) . holdMapDyn
197−
198−
199−increasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a)
200−increasingMerge xs = do
201− e <- planList (zipWith Map.singleton [1..] (Just <$> xs) ++ [reset])
202− return (UpdatedMap Map.empty e)
203− where
204− reset = Map.fromList $ zip [1..] (const Nothing <$> xs)
205−
206−decreasingMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
207−decreasingMerge xs = do
208− e <- planList (zipWith Map.singleton [1..] (const Nothing <$> xs) ++ [reset])
209− return (UpdatedMap initial e)
210− where
211− initial = Map.fromList $ zip [1..] xs
212− reset = Just <$> initial
213−
214−modifyMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
215−modifyMerge xs = do
216− e <- planList $ zipWith Map.singleton [1..] (Just <$> xs)
217− return (UpdatedMap initial e)
218− where
219− initial = Map.fromList $ zip [1..] xs
220−
221−
222−countMany :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Behavior t Int]
223−countMany = traverse (fmap current . count)
224−
225−countManyDyn :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Dynamic t Int]
226−countManyDyn = traverse count
227−
228−
229−-- Given a function which creates a sub-network (from a single event)
230−-- Create a plan which uses a switch to substitute it
231−switches :: TestPlan t m => Word -> (forall n. (MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> m (Event t a)
232−switches numFrames f = do
233− es <- events numFrames
234− switch <$> hold never (makeEvents es)
235−
236− where
237− makeEvents es = pushAlways (\n -> f (fmap (+n) es)) es
238−
239−
240−
241−-- Two sets of benchmarks, one which we're interested in testing subscribe time (as well as time to fire frames)
242−-- the other, which we're only interested in time for running frames
243−subscribing :: Word -> Word -> [(String, TestCase)]
244−subscribing n frames =
245− [ testSub "fmapFanMerge" $ return . mergeList . fmapFan n
246− , testSub "fanMerge" $ return . fanMerge n
247− , testSub "fmapFan/mergeTree" $ return . mergeTree 8 . fmapFan n
248− , testSub "fmapChain" $ return . fmapChain n
249− , testSub "switchChain" $ switchChain n
250− , testSub "switchPromptlyChain" $ switchPromptlyChain n
251− , testSub "switchFactors" $ switchFactors n
252− , testSub "coincidenceChain" $ return . coinChain n
253− ]
254−
255− where
256− testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)
257− testSub name test = testE name (switches frames test)
258−
259−-- Set of benchmark to test specifically merging dynamic collections
260−-- a pattern which occurs frequently in reflex-dom collections
261−merging :: Word -> [(String, TestCase)]
262−merging n =
263− [ testE "static events" $ mergeList <$> sparse
264− , testE "increasing events" $ switchMergeEvents =<< increasingMerge =<< sparse
265− , testE "decreasing events" $ switchMergeEvents =<< decreasingMerge =<< sparse
266− , testE "modify events" $ switchMergeEvents =<< modifyMerge =<< sparse
267−
268− , testB "static behaviors" $ pull . traverse sample <$> counters
269− , testB "increasing behaviors" $ switchMergeBehaviors =<< increasingMerge =<< counters
270− , testB "decreasing behaviors" $ switchMergeBehaviors =<< decreasingMerge =<< counters
271− , testB "modify behaviors" $ switchMergeBehaviors =<< modifyMerge =<< counters
272−
273−
274− -- , testE "increasing events/switchMerge" $ switchMergeMaybe =<< increasingMerge =<< sparse
275− -- , testE "decreasing events/switchMerge" $ switchMergeMaybe =<< decreasingMerge =<< sparse
276− -- , testE "modify events/switchMerge" $ switchMergeMaybe =<< modifyMerge =<< sparse
277− ]
278−
279− where
280− sparse :: TestPlan t m => m [Event t Word]
281− sparse = fmap (fmap (+1)) <$> occasional n 8 n
282−
283− counters :: TestPlan t m => m [Behavior t Int]
284− counters = countMany =<< sparse
285−
286−
287−
288−fans :: Word -> [(String, TestCase)]
289−fans n =
290− [ testE "fanMapChain" $ fanMergeChain n 10 <$> e
291− , testE "fmapFanMapChain" $ fmapFanMergeChain n 10 <$> e
292−
293− , testE "fanMerge " $ fanMerge n <$> events n
294−
295− , testE "fmapFanMerge " $ fmapFanMerge n <$> events n
296− , testE "triggerMerge" $ leftmost <$> for [1..n] (\i -> plan [(i, i)])
297−
298− ]
299− where
300−
301− e :: TestPlan t m => m (Event t Word)
302− e = events 100
303−
304−
305−
306−
307−dynamics :: Word -> [(String, TestCase)]
308−dynamics n =
309− [ testE "mapDynChain" $ fmap updated $ mapDynChain n =<< d
310− , testE "joinDynChain" $ fmap updated $ joinDynChain n =<< d
311− , testE "combineDynChain" $ fmap updated $ combineDynChain n =<< d
312− , testE "dense mergeTree" $ fmap (updated . mergeTreeDyn 8) dense
313− , testE "sparse mergeTree" $ fmap (updated . mergeTreeDyn 8) sparse
314− , testE "mergeDyn" $ fmap (updated . fmap sum . mergeListDyn) sparse
315− ] where
316−
317− d :: TestPlan t m => m (Dynamic t Word)
318− d = count =<< events 10
319−
320− sparse, dense :: TestPlan t m => m [Dynamic t Int]
321− sparse = countManyDyn =<< occasional n 8 16
322− dense = countManyDyn =<< continuous n 2
323−
324−
325−firing :: Word -> [(String, TestCase)]
326−firing n =
327− [ testE "fmapChain" $ fmapChain n <$> e
328− , testE "switchChain2" $ switchChain2 n =<< e
329− , testE "switchPromptlyChain" $ switchPromptlyChain n =<< e
330− , testE "switchFactors" $ switchFactors n =<< e
331− , testE "coincidenceChain" $ coinChain n <$> e
332−
333− , testE "dense mergeTree" $ mergeTree 8 <$> dense
334− , testE "sparse mergeTree" $ mergeTree 8 <$> sparse
335−
336− -- Triggers test failure in Spider
337− --, testE "runFrame" $ events n
338−
339− , testB "sum counters" $ do
340− counts <- counters
341− return $ pull $ sum <$> traverse sample counts
342−
343− , testB "pullChain" $ fmapChain n . current <$> (count =<< events 4)
344− , testB "pullChain2" $ do
345− es <- events 4
346− e' <- plan [(0, ())]
347−
348− b <- hold (constant 0) $
349− pushAlways (const $ fmapChain n <$> hold 0 es) e'
350−
351− return (join b)
352− , testB "counters/pullTree" $ mergeTree 8 <$> counters
353−
354− ]
355− where
356− e :: TestPlan t m => m (Event t Word)
357− e = events 10
358−
359− dense, sparse :: TestPlan t m => m [Event t Word]
360− dense = continuous n 2
361− sparse = occasional n 8 16
362−
363− counters :: TestPlan t m => m [Behavior t Int]
364− counters = countMany =<< sparse
365−
366−
367−
368−
369−
test/Reflex/Plan/Pure.hsdeleted−72
@@ -1,72 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−
9−module Reflex.Plan.Pure where
10−
11−import Reflex
12−import Reflex.Pure
13−import Reflex.TestPlan
14−
15−import Control.Applicative
16−import Control.Monad.Fix
17−import Control.Monad.State
18−import Data.IntMap (IntMap)
19−import qualified Data.IntMap as IntMap
20−import Data.IntSet (IntSet)
21−import qualified Data.IntSet as IntSet
22−
23−import Data.Bifunctor
24−import Data.Maybe
25−import Data.Monoid
26−import Prelude
27−
28−
29−mapToPureEvent :: IntMap a -> Event (Pure Int) a
30−mapToPureEvent m = Event $ flip IntMap.lookup m
31−
32−type TimeM = (->) Int
33−newtype PurePlan a = PurePlan { unPlan :: StateT IntSet TimeM a } deriving (Functor, Applicative, Monad, MonadFix)
34−
35−liftPlan :: TimeM a -> PurePlan a
36−liftPlan = PurePlan . lift
37−
38−instance MonadHold (Pure Int) PurePlan where
39− hold initial = liftPlan . hold initial
40− holdDyn initial = liftPlan . holdDyn initial
41− holdIncremental initial = liftPlan . holdIncremental initial
42− buildDynamic getInitial = liftPlan . buildDynamic getInitial
43− headE = liftPlan . headE
44−
45−instance MonadSample (Pure Int) PurePlan where
46− sample = liftPlan . sample
47−
48−
49−instance TestPlan (Pure Int) PurePlan where
50− plan occs = do
51− PurePlan . modify $ IntSet.union (IntMap.keysSet m)
52− return $ mapToPureEvent m
53− where m = IntMap.fromList (first fromIntegral <$> occs)
54−
55−runPure :: PurePlan a -> (a, IntSet)
56−runPure (PurePlan p) = runStateT p mempty $ 0
57−
58−relevantTimes :: IntSet -> IntSet
59−relevantTimes occs = IntSet.fromList [0..l + 1]
60− where l = fromMaybe 0 (fst <$> IntSet.maxView occs)
61−
62−testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a
63−testBehavior (b, occs) = IntMap.fromSet (sample b) (relevantTimes occs)
64−
65−testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a)
66−testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relevantTimes occs)
67−
68−
69−
70−
71−
72−
test/Reflex/Plan/Reflex.hsdeleted−135
@@ -1,135 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE StandaloneDeriving #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−module Reflex.Plan.Reflex
12− ( TestPlan(..)
13− , runPlan
14− , Plan (..)
15− , Schedule
16− , Firing (..)
17− , MonadIORef
18−
19−
20− , readSchedule
21− , readSchedule_
22− , testSchedule
23− , readEvent'
24− , makeDense
25−
26− , runTestE
27− , runTestB
28−
29− ) where
30−
31−import Reflex.Class
32−import Reflex.Host.Class
33−import Reflex.TestPlan
34−
35−import Control.Applicative
36−import Control.Monad
37−import Control.Monad.Identity
38−import Control.Monad.State.Strict
39−
40−import Control.Monad.Ref
41−import Data.Dependent.Sum (DSum (..))
42−import qualified Data.IntMap.Strict as IntMap
43−import Data.Maybe
44−import Data.Monoid
45−import Data.Traversable (sequenceA, traverse)
46−
47−import Control.DeepSeq
48−import Control.Exception
49−import Data.IntMap.Strict (IntMap)
50−import Data.IORef
51−import System.Mem
52−
53−-- Note: this import must come last to silence warnings from AMP
54−import Prelude
55−
56−type MonadIORef m = (MonadIO m, MonadRef m, Ref m ~ Ref IO)
57−
58−data Firing t where
59− Firing :: IORef (Maybe (EventTrigger t a)) -> a -> Firing t
60−
61−
62−type Schedule t = IntMap [Firing t]
63−
64−-- Implementation of a TestPlan in terms of ReflexHost
65−newtype Plan t a = Plan (StateT (Schedule t) (HostFrame t) a)
66−
67−deriving instance ReflexHost t => Functor (Plan t)
68−deriving instance ReflexHost t => Applicative (Plan t)
69−deriving instance ReflexHost t => Monad (Plan t)
70−
71−deriving instance ReflexHost t => MonadSample t (Plan t)
72−deriving instance ReflexHost t => MonadHold t (Plan t)
73−deriving instance ReflexHost t => MonadFix (Plan t)
74−
75−
76−instance (ReflexHost t, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => TestPlan t (Plan t) where
77− plan occurrences = Plan $ do
78− (e, ref) <- newEventWithTriggerRef
79− modify (IntMap.unionWith mappend (firings ref))
80− return e
81−
82− where
83− firings ref = IntMap.fromList (makeFiring ref <$> occurrences)
84− makeFiring ref (t, a) = (fromIntegral t, [Firing ref a])
85−
86−
87−firingTrigger :: (MonadReflexHost t m, MonadIORef m) => Firing t -> m (Maybe (DSum (EventTrigger t) Identity))
88−firingTrigger (Firing ref a) = fmap (:=> Identity a) <$> readRef ref
89−
90−runPlan :: (MonadReflexHost t m) => Plan t a -> m (a, Schedule t)
91−runPlan (Plan p) = runHostFrame $ runStateT p mempty
92−
93−
94−makeDense :: Schedule t -> Schedule t
95−makeDense s = fromMaybe (emptyRange 0) $ do
96− (end, _) <- fst <$> IntMap.maxViewWithKey s
97− return $ IntMap.union s (emptyRange end)
98− where
99− emptyRange end = IntMap.fromList (zip [0..end + 1] (repeat []))
100−
101−
102−-- For the purposes of testing, we add in a zero frame and extend one frame (to observe changes to behaviors
103−-- after the last event)
104−-- performGC is called at each frame to test for GC issues
105−testSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
106−testSchedule schedule readResult = IntMap.traverseWithKey (\t occs -> liftIO performGC *> triggerFrame readResult t occs) (makeDense schedule)
107−
108−readSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
109−readSchedule schedule readResult = IntMap.traverseWithKey (triggerFrame readResult) schedule
110−
111−readSchedule_ :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m ()
112−readSchedule_ schedule readResult = mapM_ (uncurry $ triggerFrame readResult) $ IntMap.toList schedule
113−
114−triggerFrame :: (MonadReflexHost t m, MonadIORef m, NFData a) => ReadPhase m a -> Int -> [Firing t] -> m a
115−triggerFrame readResult _ occs = do
116− triggers <- catMaybes <$> traverse firingTrigger occs
117− liftIO . evaluate . force =<< fireEventsAndRead triggers readResult
118−
119−readEvent' :: MonadReadEvent t m => EventHandle t a -> m (Maybe a)
120−readEvent' = readEvent >=> sequenceA
121−
122−
123−-- Convenience functions for running tests producing Events/Behaviors
124−runTestB :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Behavior t a) -> m (IntMap a)
125−runTestB p = do
126− (b, s) <- runPlan p
127− testSchedule s $ sample b
128−
129−runTestE :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Event t a) -> m (IntMap (Maybe a))
130−runTestE p = do
131− (e, s) <- runPlan p
132− h <- subscribeEvent e
133− testSchedule s (readEvent' h)
134−
135−
test/Reflex/Test.hsdeleted−66
@@ -1,66 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−
8−module Reflex.Test
9− ( testAgreement
10− , compareResult
11− , runTests
12−
13− , module Reflex.TestPlan
14−
15− ) where
16−
17−import Reflex.Spider
18−
19−import Reflex.TestPlan
20−
21−import Reflex.Plan.Pure
22−import Reflex.Plan.Reflex
23−
24−import Control.Monad
25−import Data.Monoid
26−
27−import Data.IntMap (IntMap)
28−
29−--import Data.Foldable
30−import System.Exit
31−
32−import Prelude
33−
34−
35−testAgreement :: TestCase -> IO Bool
36−testAgreement (TestE p) = do
37− spider <- runSpiderHost $ runTestE p
38− let results = [("spider", spider)]
39−
40− compareResult results (testEvent $ runPure p)
41−
42−testAgreement (TestB p) = do
43− spider <- runSpiderHost $ runTestB p
44− let results = [("spider", spider)]
45−
46− compareResult results (testBehavior $ runPure p)
47−
48−
49−compareResult :: (Show a, Eq a) => [(String, IntMap a)] -> IntMap a -> IO Bool
50−compareResult results expected = fmap and $ forM results $ \(name, r) -> do
51−
52− when (r /= expected) $ do
53− putStrLn ("Got: " ++ show (name, r))
54− putStrLn ("Expected: " ++ show expected)
55− return (r == expected)
56−
57−
58−runTests :: [(String, TestCase)] -> IO ()
59−runTests testCases = do
60− results <- forM testCases $ \(name, test) -> do
61− putStrLn $ "Test: " <> name
62− testAgreement test
63− exitWith $ if and results
64− then ExitSuccess
65− else ExitFailure 1
66−
test/Reflex/Test/CrossImpl.hsdeleted−257
@@ -1,257 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoMonomorphismRestriction #-}
9−{-# LANGUAGE RankNTypes #-}
10−{-# LANGUAGE RecursiveDo #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−
16−import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_)
17−
18−import Control.Monad.Ref
19−import Reflex.Class
20−import Reflex.Dynamic
21−import Reflex.Host.Class
22−import qualified Reflex.Pure as P
23−import qualified Reflex.Spider.Internal as S
24−
25−import Control.Arrow (second, (&&&))
26−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
27−import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
28−import Data.Dependent.Map (DSum (..))
29−import Data.Foldable
30−import Data.Map.Strict (Map)
31−import qualified Data.Map.Strict as Map
32−import qualified Data.Set as Set
33−import Data.Monoid
34−import Data.Traversable
35−import System.Exit
36−import System.Mem
37−
38−import System.IO.Unsafe
39−
40−mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a
41−mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of
42− Nothing -> error $ "mapToPureBehavior: no value for time " <> show t
43− Just (_, v) -> v
44−
45−mapToPureEvent :: Map Int a -> Event PureReflexDomain a
46−mapToPureEvent m = P.Event $ flip Map.lookup m
47−
48−relevantTestingTimes :: (Map Int a, Map Int b) -> [Int]
49−relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of
50− (Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event
51− _ -> [] -- Doesn't actually make much sense
52−
53−type PureReflexDomain = P.Pure Int
54−type TimeM = (->) Int
55−
56−testPure :: (t ~ PureReflexDomain, m ~ TimeM) => ((Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
57−testPure builder (b, e) =
58− let (P.Behavior b', P.Event e') = ($ 0) $ builder (mapToPureBehavior b, mapToPureEvent e)
59− relevantTimes = relevantTestingTimes (b, e)
60− e'' = Map.mapMaybe id $ Map.fromList $ map (id &&& e') relevantTimes
61− b'' = Map.fromList $ map (id &&& b') relevantTimes
62− in (b'', e'')
63−
64−class MapMSignals a a' t t' | a -> t, a' -> t', a t' -> a', a' t -> a where
65− mapMSignals :: Monad m => (forall b. Behavior t b -> m (Behavior t' b)) -> (forall b. Event t b -> m (Event t' b)) -> a -> m a'
66−
67−instance MapMSignals (Behavior t a) (Behavior t' a) t t' where
68− mapMSignals fb _ = fb
69−
70−instance MapMSignals (Event t a) (Event t' a) t t' where
71− mapMSignals _ fe = fe
72−
73−instance (MapMSignals a a' t t', MapMSignals b b' t t') => MapMSignals (a, b) (a', b') t t' where
74− mapMSignals fb fe (a, b) = liftM2 (,) (mapMSignals fb fe a) (mapMSignals fb fe b)
75−
76−testSpider :: (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
77−testSpider builder (bMap, eMap) = unsafePerformIO $ S.runSpiderHost $ do
78− (re, reTrigger) <- newEventWithTriggerRef
79− (rb, rbTrigger) <- newEventWithTriggerRef
80− b <- runHostFrame $ hold (error "testSpider: No value for input behavior yet") rb
81− (b', e') <- runHostFrame $ builder (b, re)
82− e'Handle <- subscribeEvent e' --TODO: This should be unnecessary
83− let times = relevantTestingTimes (bMap, eMap)
84− liftIO performGC
85− outputs <- forM times $ \t -> do
86− forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger
87− bOutput <- sample b'
88− eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do
89− mret <- readRef reTrigger
90− let firing = case mret of
91− Just ret -> [ret :=> Identity val]
92− Nothing -> []
93− fireEventsAndRead firing $ sequence =<< readEvent e'Handle
94− liftIO performGC
95− return (t, (bOutput, eOutput))
96− return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)
97−
98−tracePerf :: Show a => a -> b -> b
99−tracePerf = flip const
100−
101−testAgreement :: (Eq c, Eq d, Show c, Show d) => (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> IO Bool
102−testAgreement builder inputs = do
103− let identityResult = testPure builder inputs
104− tracePerf "---------" $ return ()
105− let spiderResult = testSpider builder inputs
106− tracePerf "---------" $ return ()
107− let resultsAgree = identityResult == spiderResult
108− if resultsAgree
109− then do --putStrLn "Success:"
110− --print identityResult
111− return ()
112− else do putStrLn "Failure:"
113− putStrLn $ "Pure result: " <> show identityResult
114− putStrLn $ "Spider result: " <> show spiderResult
115− return resultsAgree
116−
117−type TestCaseConstraint t m = (Reflex t, MonadSample t m, MonadHold t m, MonadFix m, MonadFix (PushM t))
118−
119−data TestCase = forall a b c d. (Eq c, Eq d, Show c, Show d) => TestCase (Map Int a, Map Int b) (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d))
120−
121−testCases :: [(String, TestCase)]
122−testCases =
123− [ (,) "hold" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
124− b' <- hold "123" e
125− return (b', e)
126− , (,) "count" $ TestCase (Map.singleton 0 (), Map.fromList [(1, ()), (2, ()), (3, ())]) $ \(_, e) -> do
127− e' <- updated <$> count e
128− b' <- hold (0 :: Int) e'
129− return (b', e')
130− , (,) "headE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
131− e' <- headE $ leftmost [e, e]
132− return (b, e')
133− , (,) "switch-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
134− let e' = fmap (const e) e
135− b' <- hold never e'
136− let e'' = switch b'
137− return (b, e'')
138− , (,) "switch-2" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
139− let e' = flip pushAlways e $ const $ do
140− let eab = splitRecombineEvent e
141− switch <$> hold eab never
142− e'' = coincidence e'
143− return (b, e'')
144− , (,) "switch-3" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
145− let e' = flip pushAlways e $ const $ do
146− let eab = splitRecombineEvent e
147− switch <$> hold eab (fmap (const e) e)
148− e'' = coincidence e'
149− return (b, e'')
150− , (,) "switch-4" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
151− let e' = leftmost [e, e]
152− e'' <- switch <$> hold e' (fmap (const e) e)
153− return (b, e'')
154− , (,) "switchHoldPromptly-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
155− let e' = fmap (const e) e
156− e'' <- switchHoldPromptly never e'
157− return (b, e'')
158− , (,) "switchHoldPromptly-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
159− let e' = fmap (const e) e
160− e'' <- switchHoldPromptly never $ leftmost [e', e']
161− return (b, e'')
162− , (,) "switchHoldPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
163− let e' = leftmost [e, e]
164− e'' <- switchHoldPromptly never (fmap (const e) e')
165− return (b, e'')
166− , (,) "switchHoldPromptly-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
167− let e' = leftmost [e, e]
168− e'' <- switchHoldPromptly never (fmap (const e') e)
169− return (b, e'')
170− , (,) "switch-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
171− let e' = leftmost [e, e]
172− e'' <- switch <$> hold never (fmap (const e') e)
173− return (b, e'')
174− , (,) "switchHoldPromptly-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
175− let e' = flip push e $ \_ -> do
176− Just <$> headE e
177− e'' <- switchHoldPromptly never e'
178− return (b, e'')
179− , (,) "switchHoldPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
180− let e' = flip pushAlways e $ \_ -> do
181− switchHoldPromptly e never
182− e'' <- switchHoldPromptly never e'
183− return (b, e'')
184− , (,) "coincidence-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
185− let e' = flip pushAlways e $ \_ -> return e
186− e'' = coincidence e'
187− return (b, e'')
188− , (,) "coincidence-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
189− let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]
190− e'' = coincidence e'
191− return (b, e'')
192− , (,) "coincidence-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
193− let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e
194− e'' = coincidence e'
195− return (b, e'')
196− , (,) "coincidence-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
197− let e' = flip pushAlways e $ \_ -> headE e
198− e'' = coincidence e'
199− return (b, e'')
200− , (,) "coincidence-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
201− let eChild = flip pushAlways e $ const $ do
202− let eNewValues = leftmost [e, e]
203− return $ coincidence $ fmap (const eNewValues) eNewValues
204− e' = coincidence eChild
205− return (b, e')
206− , (,) "coincidence-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
207− let eChild = flip pushAlways e $ const $ do
208− let e' = coincidence $ fmap (const e) e
209− return $ leftmost [e', e']
210− e'' = coincidence eChild
211− return (b, e'')
212− , (,) "coincidence-7" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
213− let e' = leftmost [e, e]
214− eCoincidences = coincidence $ fmap (const e') e
215− return (b, eCoincidences)
216− , (,) "holdWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
217− eo <- headE e
218− bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo
219− let b' = pull $ sample =<< sample bb
220− return (b', e)
221− , (,) "joinDyn" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
222− bb <- hold "b" e
223− bd <- hold never . fmap (const e) =<< headE e
224− eOuter <- pushAlways sample . fmap (const bb) <$> headE e
225− let eInner = switch bd
226− e' = leftmost [eOuter, eInner]
227− return (b, e')
228− , (,) "holdUniqDyn-laziness" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList (zip [1 :: Int ..] [1 :: Int, 2, 2, 3, 3, 3, 4, 4, 4, 4])) $ \(_, e :: Event t Int) -> do
229− rec result <- holdUniqDyn d
230− d <- holdDyn (0 :: Int) e
231− return (current result, updated result)
232−
233−
234−
235− {-
236− , (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do
237− x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e
238− let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)
239− return (b, e')
240− -}
241− ]
242−
243−splitRecombineEvent :: Reflex t => Event t a -> Event t String
244−splitRecombineEvent e =
245− let ea = "a" <$ e
246− eb = "b" <$ e
247− in leftmost [ea, eb]
248−
249−
250−main :: IO ()
251−main = do
252− results <- forM testCases $ \(name, TestCase inputs builder) -> do
253− putStrLn $ "Test: " <> name
254− testAgreement builder inputs
255− exitWith $ if and results
256− then ExitSuccess
257− else ExitFailure 1
test/Reflex/Test/Micro.hsdeleted−346
@@ -1,346 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RecursiveDo #-}
10−
11−module Reflex.Test.Micro (testCases) where
12−
13−import Reflex
14−import Reflex.TestPlan
15−
16−import Control.Applicative
17−import Control.Monad
18−import Control.Monad.Fix
19−import Data.Char
20−import Data.Foldable
21−import Data.Functor.Misc
22−import qualified Data.Map as Map
23−import Data.Monoid
24−
25−import Prelude
26−
27−pushDyn :: (Reflex t, MonadHold t m) => (a -> PushM t b) -> Dynamic t a -> m (Dynamic t b)
28−pushDyn f d = buildDynamic (sample (current d) >>= f) (pushAlways f (updated d))
29−
30−foldedDyn :: (Reflex t, MonadHold t m) => (a -> a -> a) -> Dynamic t a -> m (Dynamic t a)
31−foldedDyn f d = fmap join $ flip buildDynamic never $ do
32− a <- sample (current d)
33− foldDyn f a (updated d)
34−
35−scannedDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> m (Dynamic t [a])
36−scannedDyn = fmap (fmap reverse) . foldedDyn (<>) . fmap pure
37−
38−scanInnerDyns :: (Reflex t, MonadHold t m) => Dynamic t (Dynamic t a) -> m (Dynamic t [a])
39−scanInnerDyns d = do
40− scans <- scannedDyn d
41− return (join (fmap distributeListOverDynPure scans))
42−
43−
44−
45−{-# ANN testCases "HLint: ignore Functor law" #-}
46−testCases :: [(String, TestCase)]
47−testCases =
48− [ testB "hold" $ hold "0" =<< events1
49−
50− , testB "count" $ do
51− b <- current <$> (count =<< events2)
52− return $ (+ (0::Int)) <$> b
53−
54− , testB "pull-1" $ do
55− b <- hold "0" =<< events1
56− return (pull $ sample $ pull $ sample b)
57−
58− , testB "pull-2" $ do
59− b1 <- behavior1
60− return (pull $ liftA2 (<>) (sample b1) (sample b1))
61−
62− , testB "pull-3" $ do
63− b1 <- behavior1
64− b2 <- behavior2
65− return (pull $ liftA2 (<>) (sample b1) (sample b2))
66−
67− , testB "pull-4" $ do
68− es <- planList ["a", "b", "c"]
69− e <- plan [(0, ())]
70− b <- hold (constant "") $
71− pushAlways (const $ hold "z" es) e
72− return (join b)
73−
74− , testE "id" $ do
75− events2
76−
77− , testE "fmap-id" $ do
78− e <- events2
79− return $ fmap id e
80−
81− , testE "tag-1" $ do
82− b1 <- behavior1
83− e <- events2
84− return (tag b1 e)
85−
86− , testE "tag-2" $ do
87− b1 <- behavior1
88− e <- events2
89− return (tag (map toUpper <$> b1) e)
90−
91− , testE "attach-1" $ do
92− b1 <- behavior1
93− e <- events2
94− return (attachWith (++) (map toUpper <$> b1) e)
95−
96− , testE "leftmost" $ liftA2 leftmost2 events1 events2
97−
98− , testE "appendEvents-1" $ liftA2 mappend events1 events2
99−
100− , testE "appendEvents-2" $ liftA2 mappend events3 events2
101−
102− , testE "merge-1" $ do
103− e <- events1
104− return $ leftmost ["x" <$ e, "y" <$ e]
105−
106− , testE "merge-2" $ do
107− e <- events1
108− let m = mergeMap $ Map.fromList [(1::Int, "y" <$ e), (2, "z" <$ e)]
109− let ee = flip pushAlways e $ const $ return m
110− return $ coincidence ee
111−
112− , testE "headE-1" $ do
113− e <- events1
114− headE $ leftmost [e, e]
115−
116− , testE "headE-2" $ do
117− e <- events1
118− b <- hold never (e <$ e)
119− headE $ switch b
120−
121− , testE "switch-1" $ do
122− e <- events1
123− b <- hold never (e <$ e)
124− return $ switch b
125−
126− , testE "switch-2" $ do
127− e <- events1
128− return $ coincidence $ flip pushAlways e $ const $ do
129− switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) (e <$ e)
130−
131− , testE "switch-3" $ do
132− e <- events1
133− return $ coincidence $ flip pushAlways e $ const $ do
134− switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) never
135−
136− , testE "switch-4" $ do
137− e <- events1
138− switch <$> hold (deep e) (e <$ e)
139−
140− , testE "switch-5" $ do
141− e <- events1
142− return $ coincidence $ flip pushAlways e $ const $
143− return $ leftmost ["x" <$ e, "y" <$ e, "z" <$ e]
144−
145− , testE "switch-6" $ do
146− e <- events1
147− return $ coincidence $ flip pushAlways e $ const $ do
148− switch <$> hold ("x" <$ e) (e <$ e)
149−
150− , testE "switchHoldPromptly-1" $ do
151− e <- events1
152− let e' = e <$ e
153− switchHoldPromptly never $ e <$ e'
154−
155− , testE "switchHoldPromptly-2" $ do
156− e <- events1
157− switchHoldPromptly never $ deep (e <$ e)
158−
159− , testE "switchHoldPromptly-3" $ do
160− e <- events1
161− switchHoldPromptly never $ (e <$ deep e)
162−
163− , testE "switchHoldPromptly-4" $ do
164− e <- events1
165− switchHoldPromptly never $ (deep e <$ e)
166−
167− , testE "switch-5" $ do
168− e <- events1
169− switch <$> hold never (deep e <$ e)
170−
171− , testE "switchHoldPromptly-5" $ do
172− e <- events1
173− switchHoldPromptly never $ flip push e $
174− const (Just <$> headE e)
175−
176− , testE "switchHoldPromptly-6" $ do
177− e <- events1
178− switchHoldPromptly never $ flip pushAlways e $
179− const (switchHoldPromptly e never)
180−
181− , testE "coincidence-1" $ do
182− e <- events1
183− return $ coincidence $ flip pushAlways e $
184− const $ return e
185−
186− , testE "coincidence-2" $ do
187− e <- events1
188− return $ coincidence $ flip pushAlways e $
189− const $ return (deep e)
190−
191− , testE "coincidence-3" $ do
192− e <- events1
193− return $ coincidence $ flip pushAlways e $
194− const $ return (coincidence (e <$ e))
195−
196− , testE "coincidence-4" $ do
197− e <- events1
198− return $ coincidence $ flip pushAlways e $
199− const (headE e)
200−
201− , testE "coincidence-5" $ do
202− e <- events1
203− return $ coincidence $ flip pushAlways e $ const $ do
204− let e' = deep e
205− return (coincidence (e' <$ e'))
206−
207− , testE "coincidence-6" $ do
208− e <- events1
209− return $ coincidence $ flip pushAlways e $ const $ do
210− let e' = coincidence (e <$ e)
211− return $ deep e'
212−
213− , testE "coincidence-7" $ do
214− e <- events1
215− return $ coincidence (deep e <$ e)
216−
217− , testB "holdWhileFiring" $ do
218− e <- events1
219− eo <- headE e
220− bb <- hold (constant "x") $ pushAlways (const $ hold "a" eo) eo
221− return $ pull $ sample =<< sample bb
222−
223−
224− , testB "foldDynWhileFiring" $ do
225− e <- events1
226− d <- foldDyn (:) [] $
227− pushAlways (\a -> foldDyn (:) [a] e) e
228−
229− return $ current (join (fmap distributeListOverDynPure d))
230−
231− , testE "joinDyn" $ do
232− e <- events1
233− bb <- hold "b" e
234− bd <- hold never . fmap (const e) =<< headE e
235−
236− eOuter <- pushAlways sample . fmap (const bb) <$> headE e
237− let eInner = switch bd
238− return $ leftmost [eOuter, eInner]
239−
240− , testB "foldDyn" $ do
241− d <- foldDyn (++) "0" =<< events1
242− return (current d)
243−
244− , testB "mapDyn" $ do
245− d <- foldDyn (++) "0" =<< events1
246− return $ current $ fmap (map toUpper) d
247−
248− , testB "combineDyn" $ do
249− d1 <- foldDyn (++) "0" =<< events1
250− d2 <- fmap (fmap (map toUpper)) $ foldDyn (++) "0" =<< events2
251−
252− return $ current $ zipDynWith (<>) d1 d2
253−
254− , testB "buildDynamicStrictness" $ do
255− rec
256− d'' <- pushDyn return d'
257− d' <- pushDyn return d
258− d <- holdDyn "0" =<< events1
259−
260− _ <- sample (current d'')
261− return (current d'')
262−
263− , testB "factorDyn" $ do
264− d <- holdDyn (Left "a") =<< eithers
265−
266− eithers' <- eitherDyn d
267− let unFactor = either id id
268− return $ current (join (fmap unFactor eithers'))
269−
270− , testB "pushDynDeep" $ do
271− _ <- events1
272− _ <- events2
273−
274− d1 <- holdDyn "d1" =<< events1
275− d2 <- holdDyn "d2" =<< events2
276−
277− d <- flip pushDyn d1 $ \a ->
278− flip pushDyn d2 $ \b ->
279− flip pushDyn d1 $ \c ->
280− return (a <> b <> c)
281−
282− d' <- pushDyn scanInnerDyns d >>= scanInnerDyns
283− return $ current d'
284−
285− , testE "fan-1" $ do
286− e <- fmap toMap <$> events1
287− let es = select (fanMap e) . Const2 <$> values
288−
289− return (mergeList es)
290−
291− , testE "fan-2" $ do
292− e <- fmap toMap <$> events3
293− let es = select (fanMap e) . Const2 <$> values
294−
295− return (mergeList es)
296−
297− , testE "fan-3" $ do
298− f <- fanMap . fmap toMap <$> events3
299− return $ select f (Const2 'c')
300−
301− , testE "fan-4" $ do
302− e <- fmap toMap <$> events1
303− return $ toUpper <$> select (fanMap e) (Const2 'a')
304−
305− , testE "fan-5" $ do
306− e <- fmap toMap <$> events2
307− return $ toUpper <$> select (fanMap e) (Const2 'c')
308−
309− , testE "fan-6" $ do
310− f <- fanMap . fmap toMap <$> events1
311− return $ toList <$> mergeList [ select f (Const2 'b'), select f (Const2 'b'), select f (Const2 'e'), select f (Const2 'e') ]
312−
313− , testE "difference" $ do
314− e1 <- events1
315− e2 <- events2
316− return $ e1 `difference ` e2
317−
318− , testE "lazy-hold" $ do
319− let lazyHold :: forall t m. (Reflex t, MonadHold t m, MonadFix m) => m (Event t ())
320− lazyHold = do
321− rec !b <- hold never e
322− let e = never <$ switch b
323− return $ void e
324− lazyHold
325−
326−
327− ] where
328−
329− events1, events2, events3 :: TestPlan t m => m (Event t String)
330− events1 = plan [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")]
331− events2 = plan [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")]
332− events3 = liftA2 mappend events1 events2
333−
334− eithers :: TestPlan t m => m (Event t (Either String String))
335− eithers = plan [(1, Left "e"), (3, Left "d"), (4, Right "c"), (6, Right "b"), (7, Left "a")]
336−
337−
338− values = "abcde"
339− toMap str = Map.fromList $ map (\c -> (c, c)) str
340−
341− behavior1, behavior2 :: forall t m. TestPlan t m => m (Behavior t String)
342− behavior1 = hold "1" =<< events1
343− behavior2 = hold "2" =<< events2
344−
345− deep e = leftmost [e, e]
346− leftmost2 e1 e2 = leftmost [e1, e2]
test/Reflex/TestPlan.hsdeleted−52
@@ -1,52 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE UndecidableInstances #-}
9−module Reflex.TestPlan
10− ( TestPlan(..)
11−
12− , TestCase (..)
13− , testE, testB
14− , TestE, TestB
15−
16− , planList
17−
18− ) where
19−
20−import Control.DeepSeq
21−import Control.Monad.Fix
22−import Data.Word
23−import Reflex.Class
24−
25−
26−import Prelude
27−
28−class (Reflex t, MonadHold t m, MonadFix m) => TestPlan t m where
29− -- | Specify a plan of an input Event firing
30− -- Occurrences must be in the future (i.e. Time > 0)
31− -- Initial specification is
32−
33− plan :: [(Word, a)] -> m (Event t a)
34−
35−
36−planList :: TestPlan t m => [a] -> m (Event t a)
37−planList xs = plan $ zip [1..] xs
38−
39−type TestE a = forall t m. TestPlan t m => m (Event t a)
40−type TestB a = forall t m. TestPlan t m => m (Behavior t a)
41−
42−data TestCase where
43− TestE :: (Show a, Eq a, NFData a) => TestE a -> TestCase
44− TestB :: (Show a, Eq a, NFData a) => TestB a -> TestCase
45−
46−-- Helpers to declare test cases
47−testE :: (Eq a, Show a, NFData a) => String -> TestE a -> (String, TestCase)
48−testE name test = (name, TestE test)
49−
50−testB :: (Eq a, Show a, NFData a) => String -> TestB a -> (String, TestCase)
51−testB name test = (name, TestB test)
52−
test/RequesterT.hsdeleted−169
@@ -1,169 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE RankNTypes #-}
5−{-# LANGUAGE RecursiveDo #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−module Main where
8−
9−import Control.Lens
10−import Control.Monad
11−import Control.Monad.Fix
12−import qualified Data.Dependent.Map as DMap
13−import Data.Dependent.Sum
14−import Data.Functor.Misc
15−import qualified Data.Map as M
16−import Data.These
17−
18−import Reflex
19−import Reflex.Requester.Base
20−import Reflex.Requester.Class
21−import Test.Run
22−
23−data RequestInt a where
24− RequestInt :: Int -> RequestInt Int
25−
26−main :: IO ()
27−main = do
28− os1 <- runApp' (unwrapApp testOrdering) $
29− [ Just ()
30− ]
31− print os1
32− os2 <- runApp' (unwrapApp testSimultaneous) $ map Just $
33− [ This ()
34− , That ()
35− , This ()
36− , These () ()
37− ]
38− print os2
39− os3 <- runApp' (unwrapApp testMoribundRequest) [Just ()]
40− print os3
41− os4 <- runApp' (unwrapApp testMoribundRequestDMap) [Just ()]
42− print os4
43− os5 <- runApp' (unwrapApp testLiveRequestDMap) [Just ()]
44− print os5
45− os6 <- runApp' (unwrapApp delayedPulse) [Just ()]
46− print os6
47− let ![[Just [1,2,3,4,5,6,7,8,9,10]]] = os1 -- The order is reversed here: see the documentation for 'runRequesterT'
48− let ![[Just [9,7,5,3,1]],[Nothing,Nothing],[Just [10,8,6,4,2]],[Just [10,8,6,4,2],Nothing]] = os2
49− let ![[Nothing, Just [2]]] = os3
50− let ![[Nothing, Just [2]]] = os4
51− let ![[Nothing, Just [1, 2]]] = os5
52− -- let ![[Nothing, Nothing]] = os6 -- TODO re-enable this test after issue #233 has been resolved
53− return ()
54−
55−unwrapRequest :: DSum tag RequestInt -> Int
56−unwrapRequest (_ :=> RequestInt i) = i
57−
58−unwrapApp :: ( Reflex t, Monad m )
59− => (a -> RequesterT t RequestInt Identity m ())
60− -> a
61− -> m (Event t [Int])
62−unwrapApp x appIn = do
63− ((), e) <- runRequesterT (x appIn) never
64− return $ fmap (map unwrapRequest . requesterDataToList) e
65−
66−testOrdering :: ( Response m ~ Identity
67− , Request m ~ RequestInt
68− , Requester t m
69− , Adjustable t m)
70− => Event t ()
71− -> m ()
72−testOrdering pulse = forM_ [10,9..1] $ \i ->
73− requestingIdentity (RequestInt i <$ pulse)
74−
75−testSimultaneous :: ( Response m ~ Identity
76− , Request m ~ RequestInt
77− , Requester t m
78− , Adjustable t m)
79− => Event t (These () ())
80− -> m ()
81−testSimultaneous pulse = do
82− let tellE = fmapMaybe (^? here) pulse
83− switchE = fmapMaybe (^? there) pulse
84− forM_ [1,3..9] $ \i -> runWithReplace (requestingIdentity (RequestInt i <$ tellE)) $ ffor switchE $ \_ ->
85− requestingIdentity (RequestInt (i+1) <$ tellE)
86−
87−-- | Test that a widget requesting and event which fires at the same time it has been replaced
88−-- doesn't count along with the new widget.
89−testMoribundRequest
90− :: forall t m
91− . ( Reflex t
92− , Adjustable t m
93− , MonadHold t m
94− , MonadFix m
95− , Response m ~ Identity
96− , Request m ~ RequestInt
97− , Requester t m
98− )
99− => Event t ()
100− -> m ()
101−testMoribundRequest pulse = do
102− rec let requestIntOnReplace x = requestingIdentity $ RequestInt x <$ rwrFinished
103− (_, rwrFinished) <- runWithReplace (requestIntOnReplace 1) $ requestIntOnReplace 2 <$ pulse
104− return ()
105−
106−-- | The equivalent of 'testMoribundRequest' for 'traverseDMapWithKeyWithAdjust'.
107−testMoribundRequestDMap
108− :: forall t m
109− . ( Reflex t
110− , Adjustable t m
111− , MonadHold t m
112− , MonadFix m
113− , Response m ~ Identity
114− , Request m ~ RequestInt
115− , Requester t m
116− )
117− => Event t ()
118− -> m ()
119−testMoribundRequestDMap pulse = do
120− rec let requestIntOnReplace :: Int -> m ()
121− requestIntOnReplace x = void $ requestingIdentity $ RequestInt x <$ rwrFinished
122− (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-
123− traverseDMapWithKeyWithAdjust
124− (\(Const2 ()) (Identity v) -> Identity . const v <$> requestIntOnReplace v)
125− (mapToDMap $ M.singleton () 1)
126− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)
127− return ()
128−
129−-- | Ensures that elements which are _not_ removed can still fire requests
130−-- during the same frame as other elements are updated.
131−testLiveRequestDMap
132− :: forall t m
133− . ( Reflex t
134− , Adjustable t m
135− , MonadHold t m
136− , MonadFix m
137− , Response m ~ Identity
138− , Request m ~ RequestInt
139− , Requester t m
140− )
141− => Event t ()
142− -> m ()
143−testLiveRequestDMap pulse = do
144− rec let requestIntOnReplace :: Int -> m ()
145− requestIntOnReplace x = void $ requestingIdentity $ RequestInt x <$ rwrFinished
146− (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-
147− traverseDMapWithKeyWithAdjust
148− (\(Const2 k) (Identity ()) -> Identity <$> requestIntOnReplace k)
149− (mapToDMap $ M.singleton 1 ())
150− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)
151− return ()
152−
153−delayedPulse
154− :: forall t m
155− . ( Reflex t
156− , Adjustable t m
157− , MonadHold t m
158− , MonadFix m
159− , Response m ~ Identity
160− , Request m ~ RequestInt
161− , PerformEvent t m
162− , Requester t m
163− )
164− => Event t ()
165− -> m ()
166−delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do
167− -- This has the effect of delaying pulse' from pulse
168− (_, pulse') <- runWithReplace (pure ()) $ pure (RequestInt 1) <$ pulse
169− requestingIdentity pulse'
test/Test/Run.hsdeleted−74
@@ -1,74 +0,0 @@
1−{-# LANGUAGE GADTs #-}
2−{-# LANGUAGE LambdaCase #-}
3−module Test.Run where
4−
5−import Control.Monad
6−import Control.Monad.Ref
7−import Data.Dependent.Sum
8−import Data.Functor.Identity
9−import Data.These
10−
11−import Reflex
12−import Reflex.Host.Class
13−
14−data AppIn t b e = AppIn
15− { _appIn_behavior :: Behavior t b
16− , _appIn_event :: Event t e
17− }
18−
19−data AppOut t b e = AppOut
20− { _appOut_behavior :: Behavior t b
21− , _appOut_event :: Event t e
22− }
23−
24−runApp :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
25− => (AppIn t bIn eIn -> PerformEventT t m (AppOut t bOut eOut))
26− -> bIn
27− -> [Maybe (These bIn eIn)]
28− -> IO [[(bOut, Maybe eOut)]]
29−runApp app b0 input = runSpiderHost $ do
30− (appInHoldE, pulseHoldTriggerRef) <- newEventWithTriggerRef
31− (appInE, pulseEventTriggerRef) <- newEventWithTriggerRef
32− appInB <- hold b0 appInHoldE
33− (out, FireCommand fire) <- hostPerformEventT $ app $ AppIn
34− { _appIn_event = appInE
35− , _appIn_behavior = appInB
36− }
37− hnd <- subscribeEvent (_appOut_event out)
38− mpulseB <- readRef pulseHoldTriggerRef
39− mpulseE <- readRef pulseEventTriggerRef
40− let readPhase = do
41− b <- sample (_appOut_behavior out)
42− frames <- sequence =<< readEvent hnd
43− return (b, frames)
44− forM input $ \case
45− Nothing ->
46− fire [] $ readPhase
47− Just i -> case i of
48− This b' -> case mpulseB of
49− Nothing -> error "tried to fire in-behavior but ref was empty"
50− Just pulseB -> fire [ pulseB :=> Identity b' ] $ readPhase
51− That e' -> case mpulseE of
52− Nothing -> error "tried to fire in-event but ref was empty"
53− Just pulseE -> fire [ pulseE :=> Identity e' ] $ readPhase
54− These b' e' -> case mpulseB of
55− Nothing -> error "tried to fire in-behavior but ref was empty"
56− Just pulseB -> case mpulseE of
57− Nothing -> error "tried to fire in-event but ref was empty"
58− Just pulseE -> fire [ pulseB :=> Identity b', pulseE :=> Identity e' ] $ readPhase
59−
60−runApp' :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
61− => (Event t eIn -> PerformEventT t m (Event t eOut))
62− -> [Maybe eIn]
63− -> IO [[Maybe eOut]]
64−runApp' app input = do
65− let app' = fmap (AppOut (pure ())) . app
66− map (map snd) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
67−
68−runAppB :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
69− => (Event t eIn -> PerformEventT t m (Behavior t bOut))
70− -> [Maybe eIn]
71− -> IO [[bOut]]
72−runAppB app input = do
73− let app' = fmap (flip AppOut never) . app
74− map (map fst) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
test/hlint.hs+3−8
@@ -1,7 +1,7 @@
11module Main where
22
33import Control.Monad
4−import Language.Haskell.HLint3 (hlint)
4+import Language.Haskell.HLint (hlint)
55import System.Directory
66import System.Exit (exitFailure, exitSuccess)
77import System.FilePath
@@ -22,6 +22,8 @@ main = do
2222 , "--ignore=Use unless"
2323 , "--ignore=Reduce duplication"
2424 , "--cpp-define=USE_TEMPLATE_HASKELL"
25+ , "--ignore=Use tuple-section"
26+ , "--ignore=Unused LANGUAGE pragma" -- hlint3 falsely believes that TypeOperators is not needed
2527 ]
2628 recurseInto = and <$> sequence
2729 [ fileType ==? Directory
@@ -29,16 +31,9 @@ main = do
2931 ]
3032 matchFile = and <$> sequence
3133 [ extension ==? ".hs"
32− , let notElem' = liftOp notElem
33− in filePath `notElem'` filePathExceptions pwd
3434 ]
3535 files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
3636 ideas <- fmap concat $ forM files $ \f -> do
3737 putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
3838 runHlint f
3939 if null ideas then exitSuccess else exitFailure
40−
41−filePathExceptions :: FilePath -> [FilePath]
42−filePathExceptions pwd = map (pwd </>) $
43− [ "src/Data/AppendMap.hs" -- parse error when hlint runs
44− ]
test/rootCleanup.hsdeleted−25
@@ -1,25 +0,0 @@
1−import Control.Concurrent
2−import Control.Monad
3−import Data.IORef
4−import Reflex
5−import Reflex.Host.Class
6−import System.Exit
7−import System.Mem
8−
9−main :: IO ()
10−main = do
11− numSubscriptions <- newIORef 0
12− replicateM_ 1000 $ do
13− runSpiderHost $ do
14− e <- newEventWithTrigger $ \_ -> do
15− modifyIORef' numSubscriptions succ
16− return $ modifyIORef' numSubscriptions pred
17− _ <- hold () e
18− return ()
19− replicateM_ 100 $ do
20− performMajorGC
21− threadDelay 1
22− n <- readIORef numSubscriptions
23− if n == 0
24− then putStrLn "Succeeded"
25− else putStrLn "Failed" >> exitFailure
test/semantics.hsdeleted−47
@@ -1,47 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−
8−module Main (main) where
9−
10−import Reflex.Test
11−
12−import Data.Bifunctor
13−import Data.Functor
14−import Data.List
15−import qualified Reflex.Bench.Focused as Focused
16−import qualified Reflex.Test.Micro as Micro
17−
18−import System.Environment
19−import System.Exit
20−
21−import Prelude
22−
23−matchPrefixes :: [String] -> (String -> Bool)
24−matchPrefixes [] = const True
25−matchPrefixes args = \name -> any (`isPrefixOf` name) args
26−
27−
28−main :: IO ()
29−main = do
30− args <- getArgs
31−
32− case args of
33− ["--list"] -> mapM_ putStrLn (fst <$> allTests) >> exitWith (ExitFailure 1)
34− _ -> case filter (matchPrefixes args . fst) allTests of
35− [] -> putStrLn "filter did not match any tests" >> exitWith (ExitFailure 1)
36− tests -> runTests tests
37−
38− where
39− allTests = concat
40− [ makeGroup "micro" Micro.testCases
41− , makeGroup "subscribing (100,40)" (Focused.subscribing 100 40)
42− , makeGroup "firing 1000" (Focused.firing 1000)
43− , makeGroup "merge 100" (Focused.merging 100)
44− , makeGroup "fan 50" (Focused.fans 50)
45− ]
46−
47− makeGroup name tests = first (\test -> intercalate "/" [name, test]) <$> tests
test/tests.hsnew file+43
@@ -0,0 +1,43 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+module Main where
3+
4+import Test.HUnit (runTestTT, (~:), assertEqual, errors, failures, test)
5+import Data.Patch ( Patch(apply) )
6+import Data.Patch.MapWithMove ( patchThatChangesMap )
7+import Data.Map as Map ( Map, fromList, singleton )
8+import Hedgehog (checkParallel, discover, Property, property, forAll, PropertyT, (===))
9+import Hedgehog.Gen as Gen ( int )
10+import Hedgehog.Range as Range ( linear )
11+import Control.Monad (replicateM)
12+import System.Exit (exitFailure, exitSuccess)
13+import Data.Sequence as Seq ( foldMapWithIndex, replicateM )
14+
15+main :: IO ()
16+main = do
17+ counts <- runTestTT $ test [
18+ "Simple Move" ~: (do
19+ let mapBefore = Map.fromList [(0,1)]
20+ mapAfter = Map.fromList [(0,0),(1,1)]
21+ patch = patchThatChangesMap mapBefore mapAfter
22+ afterPatch = apply patch mapBefore
23+ assertEqual "Patch creates the same Map" (Just mapAfter) afterPatch),
24+ "Property Checks" ~: propertyChecks
25+ ]
26+ if errors counts + failures counts == 0 then exitSuccess else exitFailure
27+
28+propertyChecks :: IO Bool
29+propertyChecks = checkParallel $$(discover)
30+
31+prop_patchThatChangesMap :: Property
32+prop_patchThatChangesMap = property $ do
33+ mapBefore <- makeRandomIntMap
34+ mapAfter <- makeRandomIntMap
35+ let patch = patchThatChangesMap mapBefore mapAfter
36+ Just mapAfter === apply patch mapBefore
37+
38+makeRandomIntMap :: Monad m => PropertyT m (Map Int Int)
39+makeRandomIntMap = do
40+ let genNum = Gen.int (Range.linear 0 100)
41+ length <- forAll genNum
42+ listOfNumbers <- forAll $ Seq.replicateM length genNum
43+ pure $ Seq.foldMapWithIndex Map.singleton listOfNumbers