on e5d5946 help sign in
.github/workflows/haskell.ymldeleted−47
since splitsnapshots
unifiedsplit
@@ -1,47 +0,0 @@
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+2−11
@@ -5,7 +5,6 @@ Contributions and issue reports are encouraged and appreciated!
5- [Opening Issues](#opening-issues)
5- [Opening Issues](#opening-issues)
6- [Submitting Changes](#submitting-changes)
6- [Submitting Changes](#submitting-changes)
7 - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
7 - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
8− - [Guidelines for Pull Requests](#guidelines-for-pull-requests)
9 - [Code Quality](#code-quality)
8 - [Code Quality](#code-quality)
10 - [Documentation](#documentation)
9 - [Documentation](#documentation)
11
10
@@ -15,8 +14,8 @@ Before opening an issue, please check whether your issue has already been report
15
14
16* Describe the issue you're encountering or the suggestion you're making
15* Describe the issue you're encountering or the suggestion you're making
17* 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.
16* 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.
18−* Let us know what version of patch you were using. If you're using a github checkout, provide the git hash.
17+* Let us know what version of reflex 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.
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.
20
19
21## Submitting Changes
20## Submitting Changes
22
21
@@ -31,10 +30,6 @@ One way to think about it is that your commit message should be able to complete
31#### Body
30#### Body
32For 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.
31For 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.
33
32
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−
38### Code Quality
33### Code Quality
39
34
40#### Warnings
35#### Warnings
@@ -45,10 +40,6 @@ Your pull request should add no new warnings to the project. It should also gene
45
40
46Make 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!
41Make 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!
47
42
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−
52### Documentation
43### Documentation
53
44
54#### In the code
45#### In the code
ChangeLog.md+23−52
@@ -1,61 +1,32 @@
1−# Revision history for patch
1+# Revision history for reflex
2
2
3## Unreleased
3## Unreleased
4
4
5−* New dep of `data-orphans` for old GHC to get instances honestly instead of
5+* Generalize merging functions:
6− via `monoidal-containers`.
6+ `merge` to `mergeG`,
7+ `mergeIncremental` to `mergeIncrementalG`,
8+ `distributeDMapOverDynPure` to `distributeDMapOverDynPureG`,
9+ `mergeIncrementalWithMove` to `mergeIncrementalWithMoveG`.
7
10
8−## 0.0.5.0 - 2021-12-17
11+## 0.6.2.0
9
12
10−* `Additive` now lives in `Data.Semigroup.Additive`, but is still reexported
13+* Fix `holdDyn` so that it is lazy in its event argument
11− from `Data.Patch` for compatability.
14+ These produce `DMap`s whose values needn't be `Identity`.
15+* Stop using the now-deprecated `*Tag` classes (e.g., `ShowTag`).
16+* Fix `holdDyn` so that it is lazy in its event argument.
12
17
13−* Rewrite `PatchMapWithMove` in terms of `PatchMapWithPatchingMove`.
18+## 0.6.1.0
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.
18
19
19−## 0.0.4.0 - 2021-04-20
20+* Re-export all of `Data.Map.Monoidal`
21+* Fix `QueryT` and `RequesterT` tests
20
22
21−* Enable PolyKinds
23+## 0.6.0.0 -- 2019-03-20
22
24
23−## 0.0.3.2 - 2020-11-06
25+* Deprecate `FunctorMaybe` in favor of `Data.Witherable.Filterable`. We still export `fmapMaybe`, `ffilter`, etc., but they all rely on `Filterable` now.
24−
26+* Rename `MonadDynamicWriter` to `DynamicWriter` and add a deprecation for the old name.
25−* Update version bounds
27+* Remove many deprecated functions.
26−
28+* Add a `Num` instance for `Dynamic`.
27−## 0.0.3.1 - 2020-02-05
29+* Add `matchRequestsWithResponses` to make it easier to use `Requester` with protocols that don't do this matching for you.
28−
30+* Add `withRequesterT` to map functions over the request and response of a `RequesterT`.
29−* Replace `fromJust` with something easier to debug.
31+* Suppress nil patches in `QueryT` as an optimization. The `Query` type must now have an `Eq` instance.
30−
32+* Add `throttleBatchWithLag` to `Reflex.Time`. See that module for details.
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.mdnew file+311
@@ -0,0 +1,311 @@
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+14−41
@@ -1,52 +1,25 @@
1−# patch
1+## [Reflex](https://reflex-frp.org/)
2
2
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)
3+[![Hackage](https://img.shields.io/hackage/v/reflex.svg)](http://hackage.haskell.org/package/reflex)
4
4
5−Data structures for describing changes to other data structures.
5+### Practical Functional Reactive Programming
6
6
7−A `Patch` type represents a kind of change made to a data structure.
7+Reflex is a fully-deterministic, higher-order Functional Reactive Programming (FRP) interface and an engine that efficiently implements that interface.
8
8
9−```haskell
9+[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.
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−```
16
10
17−## Patching Maps
11+A summary of Reflex functions is available in the [quick reference](Quickref.md).
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).
19
12
20−`PatchMap` is defined as:
13+**Visit https://reflex-frp.org/ for more information, tutorials, documentation and [examples](https://examples.reflex-frp.org/).**
21
14
22−```haskell
15+### Resources
23−newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
16+[Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
24−```
25
17
26−The `Maybe` around the value is used to represent insertion/updates or deletion of the element at a given key.
18+[/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
27
19
28−Its `Patch` instance begins with:
20+[irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
29
21
30−```haskell
22+### Hacking
31−instance Ord k => Patch (PatchMap k v) where
32− type PatchTarget (PatchMap k v) = Map k v
33− ...
34−```
35
23
36−When a `PatchMap` is applied to its `PatchTarget`, the following changes can occur:
24+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.
37−
25+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.
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.hsnew file+110
@@ -0,0 +1,110 @@
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.hsnew file+157
@@ -0,0 +1,157 @@
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.projectdeleted−1
@@ -1 +0,0 @@
1−packages: .
default.nixnew file+39
@@ -0,0 +1,39 @@
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
10+, useTemplateHaskell ? true
11+}:
12+mkDerivation {
13+ pname = "reflex";
14+ version = "0.6.2.0";
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+ ] ++ (if ghc.isGhcjs or false then [
26+ ghcjs-base
27+ ] else []) ++ (if !useTemplateHaskell then [] else [
28+ haskell-src-exts haskell-src-meta
29+ ]);
30+ testHaskellDepends = if ghc.isGhcjs or false then [] else [
31+ hlint filepath directory filemanip
32+ ];
33+ configureFlags = if useTemplateHaskell then [] else [
34+ "-f-use-template-haskell"
35+ ];
36+ homepage = "https://github.com/reflex-frp/reflex";
37+ description = "Higher-order Functional Reactive Programming";
38+ license = stdenv.lib.licenses.bsd3;
39+}
dep/reflex-platform/default.nixdeleted−8
@@ -1,8 +0,0 @@
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.jsondeleted−8
@@ -1,8 +0,0 @@
1−{
2− "owner": "reflex-frp",
3− "repo": "reflex-platform",
4− "branch": "master",
5− "private": false,
6− "rev": "c9d11db1b98855fe8ab24a3ff6a5dbe0ad902ad9",
7− "sha256": "0sfzkqdvyah5mwvmli0wq1nl0b8cvk2cmfgfy4rz57wv42x3099y"
8−}
hydra.jsonnew file+29
@@ -0,0 +1,29 @@
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.nixnew file+70
@@ -0,0 +1,70 @@
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.cabaldeleted−100
@@ -1,100 +0,0 @@
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.nixnew file+8
@@ -0,0 +1,8 @@
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.cabalnew file+370
@@ -0,0 +1,370 @@
1+Name: reflex
2+Version: 0.6.2.0
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 >= 0.2,
48+ containers >= 0.5 && < 0.7,
49+ data-default >= 0.5 && < 0.8,
50+ dependent-map >= 0.3 && < 0.4,
51+ exception-transformers == 0.4.*,
52+ profunctors,
53+ lens >= 4.7 && < 5,
54+ monad-control >= 1.0.1 && < 1.1,
55+ monoidal-containers == 0.4.*,
56+ mtl >= 2.1 && < 2.3,
57+ prim-uniq >= 0.1.0.1 && < 0.2,
58+ primitive >= 0.5 && < 0.7,
59+ random == 1.1.*,
60+ ref-tf == 0.4.*,
61+ reflection == 2.1.*,
62+ semigroupoids >= 4.0 && < 6,
63+ semigroups >= 0.16 && < 0.19,
64+ stm >= 2.4 && < 2.6,
65+ syb >= 0.5 && < 0.8,
66+ these >= 0.4 && < 0.9,
67+ time >= 1.4 && < 1.9,
68+ transformers >= 0.2,
69+ transformers-compat >= 0.3,
70+ unbounded-delays >= 0.1.0.0 && < 0.2,
71+ witherable >= 0.2 && < 0.4
72+
73+ exposed-modules:
74+ Data.AppendMap,
75+ Data.FastMutableIntMap,
76+ Data.FastWeakBag,
77+ Data.Functor.Misc,
78+ Data.Map.Misc,
79+ Data.WeakBag,
80+ Reflex,
81+ Reflex.Class,
82+ Reflex.Adjustable.Class,
83+ Reflex.BehaviorWriter.Base,
84+ Reflex.BehaviorWriter.Class,
85+ Reflex.Collection,
86+ Reflex.Dynamic,
87+ Reflex.Dynamic.Uniq,
88+ Reflex.DynamicWriter,
89+ Reflex.DynamicWriter.Base,
90+ Reflex.DynamicWriter.Class,
91+ Reflex.EventWriter,
92+ Reflex.EventWriter.Base,
93+ Reflex.EventWriter.Class,
94+ Reflex.FastWeak,
95+ Reflex.FunctorMaybe,
96+ Reflex.Host.Class,
97+ Reflex.Network,
98+ Reflex.NotReady.Class,
99+ Reflex.Patch,
100+ Reflex.Patch.Class,
101+ Reflex.Patch.DMap,
102+ Reflex.Patch.DMapWithMove,
103+ Reflex.Patch.IntMap,
104+ Reflex.Patch.Map,
105+ Reflex.Patch.MapWithMove,
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.6 && < 0.7,
139+ haskell-src-exts >= 1.16 && < 1.22,
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.6.*
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+7−47
@@ -1,49 +1,9 @@
1−{ reflex-platform-fun ? import ./dep/reflex-platform
1+{ rp ? import ./reflex-platform.nix {}
2}:
2}:
3−
4let
3let
5− native-reflex-platform = reflex-platform-fun {};
6− inherit (native-reflex-platform.nixpkgs) lib;
4+ inherit (rp.nixpkgs) lib;
7− systems = ["x86_64-linux" "x86_64-darwin"];
5+ compilers = ["ghc8_4" "ghc8_0" "ghcjs8_4" "ghcjs8_0"];
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
6+in lib.genAttrs compilers (ghc: {
21− reflex-platform = reflex-platform-fun {
7+ reflex-useTemplateHaskell = rp.${ghc}.callPackage ./. { useTemplateHaskell = true; };
22− inherit system;
8+ reflex = rp.${ghc}.callPackage ./. { useTemplateHaskell = false; };
23− haskellOverlays = [
9+})
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.hsnew file+80
@@ -0,0 +1,80 @@
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.hsnew file+93
@@ -0,0 +1,93 @@
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.hsnew file+156
@@ -0,0 +1,156 @@
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+8−4
@@ -4,12 +4,17 @@
4{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE FlexibleInstances #-}
6{-# LANGUAGE GADTs #-}
6{-# LANGUAGE GADTs #-}
7+{-# LANGUAGE KindSignatures #-}
7{-# LANGUAGE LambdaCase #-}
8{-# LANGUAGE LambdaCase #-}
8{-# LANGUAGE MultiParamTypeClasses #-}
9{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE PatternSynonyms #-}
9{-# LANGUAGE PolyKinds #-}
11{-# LANGUAGE PolyKinds #-}
10{-# LANGUAGE RankNTypes #-}
12{-# LANGUAGE RankNTypes #-}
11{-# LANGUAGE ScopedTypeVariables #-}
13{-# LANGUAGE ScopedTypeVariables #-}
12{-# LANGUAGE StandaloneDeriving #-}
14{-# LANGUAGE StandaloneDeriving #-}
15+#ifdef USE_REFLEX_OPTIMIZER
16+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
17+#endif
13-- | This module provides types and functions with no particular theme, but
18-- | This module provides types and functions with no particular theme, but
14-- which are relevant to the use of 'Functor'-based datastructures like
19-- which are relevant to the use of 'Functor'-based datastructures like
15-- 'Data.Dependent.Map.DMap'.
20-- 'Data.Dependent.Map.DMap'.
@@ -37,19 +42,18 @@ module Data.Functor.Misc
37 ) where
42 ) where
38
43
39import Control.Applicative ((<$>))
44import Control.Applicative ((<$>))
45+import Control.Monad.Identity
40import Data.Dependent.Map (DMap)
46import Data.Dependent.Map (DMap)
41import qualified Data.Dependent.Map as DMap
47import qualified Data.Dependent.Map as DMap
42import Data.Dependent.Sum
48import Data.Dependent.Sum
43−import Data.Functor.Identity
44import Data.GADT.Compare
49import Data.GADT.Compare
45import Data.GADT.Show
50import Data.GADT.Show
46import Data.IntMap (IntMap)
51import Data.IntMap (IntMap)
47import qualified Data.IntMap as IntMap
52import qualified Data.IntMap as IntMap
48import Data.Map (Map)
53import Data.Map (Map)
49import qualified Data.Map as Map
54import qualified Data.Map as Map
50−import Data.Some (Some, mkSome)
55+import Data.Some (Some(Some))
51import Data.These
56import Data.These
52−import Data.Type.Equality ((:~:)(Refl))
53import Data.Typeable hiding (Refl)
57import Data.Typeable hiding (Refl)
54
58
55--------------------------------------------------------------------------------
59--------------------------------------------------------------------------------
@@ -116,7 +120,7 @@ intMapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=
116-- | Convert a 'DMap' to a regular 'Map' by forgetting the types associated with
120-- | Convert a 'DMap' to a regular 'Map' by forgetting the types associated with
117-- the keys, using a function to remove the wrapping 'Functor'
121-- the keys, using a function to remove the wrapping 'Functor'
118weakenDMapWith :: (forall a. v a -> v') -> DMap k v -> Map (Some k) v'
122weakenDMapWith :: (forall a. v a -> v') -> DMap k v -> Map (Some k) v'
119−weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (mkSome k, f v)) . DMap.toAscList
123+weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (Some k, f v)) . DMap.toAscList
120
124
121--------------------------------------------------------------------------------
125--------------------------------------------------------------------------------
122-- WrapArg
126-- WrapArg
src/Data/Map/Misc.hsnew file+71
@@ -0,0 +1,71 @@
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.hsdeleted−115
@@ -1,115 +0,0 @@
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.hsdeleted−95
@@ -1,95 +0,0 @@
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/Data/Patch/MapWithMove.hsdeleted−312
@@ -1,312 +0,0 @@
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.hsdeleted−432
@@ -1,432 +0,0 @@
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.hsdeleted−54
@@ -1,54 +0,0 @@
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.hsnew file+121
@@ -0,0 +1,121 @@
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.hsnew file+35
@@ -0,0 +1,35 @@
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.hsnew file+140
@@ -0,0 +1,140 @@
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.hsnew file+202
@@ -0,0 +1,202 @@
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.hsnew file+26
@@ -0,0 +1,26 @@
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.hsnew file+1628
@@ -0,0 +1,1628 @@
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+{-# LANGUAGE Trustworthy #-}
21+#ifdef USE_REFLEX_OPTIMIZER
22+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
23+#endif
24+
25+-- |
26+-- Module:
27+-- Reflex.Class
28+-- Description:
29+-- This module contains the Reflex interface, as well as a variety of
30+-- convenience functions for working with 'Event's, 'Behavior's, and other
31+-- signals.
32+module Reflex.Class
33+ ( module Reflex.Patch
34+ -- * Primitives
35+ , Reflex (..)
36+ , mergeInt
37+ , coerceBehavior
38+ , coerceEvent
39+ , coerceDynamic
40+ , MonadSample (..)
41+ , MonadHold (..)
42+ -- ** 'fan' related types
43+ , EventSelector (..)
44+ , EventSelectorInt (..)
45+ -- * Convenience functions
46+ , constDyn
47+ , pushAlways
48+ -- ** Combining 'Event's
49+ , leftmost
50+ , merge
51+ , mergeIncremental
52+ , mergeIncrementalWithMove
53+ , mergeMap
54+ , mergeIntMap
55+ , mergeMapIncremental
56+ , mergeMapIncrementalWithMove
57+ , mergeIntMapIncremental
58+ , coincidencePatchMap
59+ , coincidencePatchMapWithMove
60+ , coincidencePatchIntMap
61+ , mergeList
62+ , mergeWith
63+ , difference
64+ , alignEventWithMaybe
65+ -- ** Breaking up 'Event's
66+ , splitE
67+ , fanEither
68+ , fanThese
69+ , fanMap
70+ , dmapToThese
71+ , EitherTag (..)
72+ , eitherToDSum
73+ , dsumToEither
74+ , factorEvent
75+ , filterEventKey
76+ -- ** Collapsing 'Event . Event'
77+ , switchHold
78+ , switchHoldPromptly
79+ , switchHoldPromptOnly
80+ , switchHoldPromptOnlyIncremental
81+ -- ** Using 'Event's to sample 'Behavior's
82+ , tag
83+ , tagMaybe
84+ , attach
85+ , attachWith
86+ , attachWithMaybe
87+ -- ** Blocking an 'Event' based on a 'Behavior'
88+ , gate
89+ -- ** Combining 'Dynamic's
90+ , distributeDMapOverDynPure
91+ , distributeDMapOverDynPureG
92+ , distributeListOverDyn
93+ , distributeListOverDynWith
94+ , zipDyn
95+ , zipDynWith
96+ -- ** Accumulating state
97+ , Accumulator (..)
98+ , accumDyn
99+ , accumMDyn
100+ , accumMaybeDyn
101+ , accumMaybeMDyn
102+ , mapAccumDyn
103+ , mapAccumMDyn
104+ , mapAccumMaybeDyn
105+ , mapAccumMaybeMDyn
106+ , accumB
107+ , accumMB
108+ , accumMaybeB
109+ , accumMaybeMB
110+ , mapAccumB
111+ , mapAccumMB
112+ , mapAccumMaybeB
113+ , mapAccumMaybeMB
114+ , mapAccum_
115+ , mapAccumM_
116+ , mapAccumMaybe_
117+ , mapAccumMaybeM_
118+ , accumIncremental
119+ , accumMIncremental
120+ , accumMaybeIncremental
121+ , accumMaybeMIncremental
122+ , mapAccumIncremental
123+ , mapAccumMIncremental
124+ , mapAccumMaybeIncremental
125+ , mapAccumMaybeMIncremental
126+ , zipListWithEvent
127+ , numberOccurrences
128+ , numberOccurrencesFrom
129+ , numberOccurrencesFrom_
130+ , (<@>)
131+ , (<@)
132+ , tailE
133+ , headTailE
134+ , takeWhileE
135+ , takeWhileJustE
136+ , dropWhileE
137+ , takeDropWhileJustE
138+ , switcher
139+ -- * Debugging functions
140+ , traceEvent
141+ , traceEventWith
142+ -- * Unsafe functions
143+ , unsafeDynamic
144+ , unsafeMapIncremental
145+ -- * 'Filterable' convenience functions
146+ , FunctorMaybe -- fmapMaybe is purposely not exported from deprecated 'FunctorMaybe' and the new alias is exported instead
147+ , mapMaybe -- Re-exported for convenience
148+ , fmapMaybe
149+ , fforMaybe
150+ , ffilter
151+ , filterLeft
152+ , filterRight
153+ -- * Miscellaneous convenience functions
154+ , ffor
155+ , ffor2
156+ , ffor3
157+ -- * Deprecated functions
158+ , switchPromptly
159+ , switchPromptOnly
160+ -- * "Cheap" functions
161+ , fmapMaybeCheap
162+ , mapMaybeCheap
163+ , fmapCheap
164+ , fforCheap
165+ , fforMaybeCheap
166+ , pushAlwaysCheap
167+ , tagCheap
168+ , mergeWithCheap
169+ , mergeWithCheap'
170+ -- * Slow, but general, implementations
171+ , slowHeadE
172+ ) where
173+
174+import Control.Applicative
175+import Control.Monad.Identity
176+import Control.Monad.Reader
177+import Control.Monad.State.Strict
178+import Control.Monad.Trans.Cont (ContT)
179+import Control.Monad.Trans.Except (ExceptT)
180+import Control.Monad.Trans.RWS (RWST)
181+import Control.Monad.Trans.Writer (WriterT)
182+import Data.Align
183+import Data.Bifunctor
184+import Data.Coerce
185+import Data.Default
186+import Data.Dependent.Map (DMap, DSum (..))
187+import qualified Data.Dependent.Map as DMap
188+import Data.Functor.Compose
189+import Data.Functor.Product
190+import Data.GADT.Compare (GEq (..), GCompare (..), (:~:) (..))
191+import Data.FastMutableIntMap (PatchIntMap)
192+import Data.Foldable
193+import Data.Functor.Bind
194+import Data.Functor.Misc
195+import Data.Functor.Plus
196+import Data.IntMap.Strict (IntMap)
197+import qualified Data.IntMap.Strict as IntMap
198+import Data.List.NonEmpty (NonEmpty (..))
199+import Data.Map (Map)
200+import Data.Semigroup (Semigroup, sconcat, stimes, (<>))
201+import Data.Some (Some(Some))
202+import Data.String
203+import Data.These
204+import Data.Type.Coercion
205+import Data.Witherable (Filterable(..))
206+import qualified Data.Witherable as W
207+import Reflex.FunctorMaybe (FunctorMaybe)
208+import qualified Reflex.FunctorMaybe
209+import Reflex.Patch
210+import qualified Reflex.Patch.MapWithMove as PatchMapWithMove
211+
212+import Debug.Trace (trace)
213+
214+-- | The 'Reflex' class contains all the primitive functionality needed for
215+-- Functional Reactive Programming (FRP). The @/t/@ type parameter indicates
216+-- which "timeline" is in use. Timelines are fully-independent FRP contexts,
217+-- and the type of the timeline determines the FRP engine to be used. For most
218+-- purposes, the 'Reflex.Spider' implementation is recommended.
219+class ( MonadHold t (PushM t)
220+ , MonadSample t (PullM t)
221+ , MonadFix (PushM t)
222+ , Functor (Dynamic t)
223+ , Applicative (Dynamic t) -- Necessary for GHC <= 7.8
224+ , Monad (Dynamic t)
225+ ) => Reflex t where
226+ -- | A container for a value that can change over time. 'Behavior's can be
227+ -- sampled at will, but it is not possible to be notified when they change
228+ data Behavior t :: * -> *
229+ -- | A stream of occurrences. During any given frame, an 'Event' is either
230+ -- occurring or not occurring; if it is occurring, it will contain a value of
231+ -- the given type (its "occurrence type")
232+ data Event t :: * -> *
233+ -- | A container for a value that can change over time and allows
234+ -- notifications on changes. Basically a combination of a 'Behavior' and an
235+ -- 'Event', with a rule that the 'Behavior' will change if and only if the
236+ -- 'Event' fires.
237+ data Dynamic t :: * -> *
238+ -- | An 'Incremental' is a more general form of a 'Dynamic'.
239+ -- Instead of always fully replacing the value, only parts of it can be patched.
240+ -- This is only needed for performance critical code via `mergeIncremental` to make small
241+ -- changes to large values.
242+ data Incremental t :: * -> *
243+ -- | A monad for doing complex push-based calculations efficiently
244+ type PushM t :: * -> *
245+ -- | A monad for doing complex pull-based calculations efficiently
246+ type PullM t :: * -> *
247+ -- | An 'Event' with no occurrences
248+ never :: Event t a
249+ -- | Create a 'Behavior' that always has the given value
250+ 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
251+ -- | Create an 'Event' from another 'Event'; the provided function can sample
252+ -- 'Behavior's and hold 'Event's, and use the results to produce a occurring
253+ -- (Just) or non-occurring (Nothing) result
254+ push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
255+ -- | 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.
256+ pushCheap :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
257+ -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be
258+ -- recomputed whenever any of the read 'Behavior's changes
259+ pull :: PullM t a -> Behavior t a
260+ -- | Merge a collection of events; the resulting 'Event' will only occur if at
261+ -- least one input event is occurring, and will contain all of the input keys
262+ -- that are occurring simultaneously
263+ mergeG :: GCompare k => (forall a. q a -> Event t (v a))
264+ -> DMap k q -> Event t (DMap k v)
265+ --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
266+ -- | Efficiently fan-out an event to many destinations. You should save the
267+ -- result in a @let@-binding, and then repeatedly 'select' on the result to
268+ -- create child events
269+ fan :: GCompare k => Event t (DMap k Identity) -> EventSelector t k
270+ -- | Create an 'Event' that will occur whenever the currently-selected input
271+ -- 'Event' occurs
272+ switch :: Behavior t (Event t a) -> Event t a
273+ -- | Create an 'Event' that will occur whenever the input event is occurring -- and its occurrence value, another 'Event', is also occurring
274+ coincidence :: Event t (Event t a) -> Event t a
275+ -- | Extract the 'Behavior' of a 'Dynamic'.
276+ current :: Dynamic t a -> Behavior t a
277+ -- | Extract the 'Event' of the 'Dynamic'.
278+ updated :: Dynamic t a -> Event t a
279+ -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
280+ -- recent firing of the given 'Event', if any.
281+ unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
282+ -- | Create a new 'Incremental'. The given "PullM"'s value must always change
283+ -- in the same way that the accumulated application of patches would change
284+ -- that value.
285+ unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
286+ -- | Create a merge whose parents can change over time
287+ mergeIncrementalG :: GCompare k
288+ => (forall a. q a -> Event t (v a))
289+ -> Incremental t (PatchDMap k q)
290+ -> Event t (DMap k v)
291+ -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
292+ mergeIncrementalWithMoveG :: GCompare k
293+ => (forall a. q a -> Event t (v a))
294+ -> Incremental t (PatchDMapWithMove k q) -> Event t (DMap k v)
295+ -- | Extract the 'Behavior' component of an 'Incremental'
296+ currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
297+ -- | Extract the 'Event' component of an 'Incremental'
298+ updatedIncremental :: Patch p => Incremental t p -> Event t p
299+ -- | Convert an 'Incremental' to a 'Dynamic'
300+ incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
301+ -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
302+ -- occurrence type
303+ behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
304+ -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
305+ -- occurrence type
306+ eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
307+ -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
308+ -- occurrence type
309+ dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
310+ mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
311+ fanInt :: Event t (IntMap a) -> EventSelectorInt t a
312+
313+--TODO: Specialize this so that we can take advantage of knowing that there's no changing going on
314+-- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple
315+-- keys simultaneously.
316+mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
317+mergeInt m = mergeIntIncremental $ unsafeBuildIncremental (return m) never
318+
319+-- | Coerce a 'Behavior' between representationally-equivalent value types
320+coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
321+coerceBehavior = coerceWith $ behaviorCoercion Coercion
322+
323+-- | Coerce an 'Event' between representationally-equivalent occurrence types
324+coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
325+coerceEvent = coerceWith $ eventCoercion Coercion
326+
327+-- | Coerce a 'Dynamic' between representationally-equivalent value types
328+coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
329+coerceDynamic = coerceWith $ dynamicCoercion Coercion
330+
331+-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
332+-- __must__ change when and only when the 'Event' fires, such that the
333+-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
334+-- if this is not the case, the resulting 'Dynamic' will behave
335+-- nondeterministically.
336+unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
337+unsafeDynamic = unsafeBuildDynamic . sample
338+
339+-- | Construct a 'Dynamic' value that never changes
340+constDyn :: Reflex t => a -> Dynamic t a
341+constDyn = pure
342+
343+instance (Reflex t, Default a) => Default (Dynamic t a) where
344+ def = pure def
345+
346+-- | 'MonadSample' designates monads that can read the current value of a
347+-- 'Behavior'. This includes both 'PullM' and 'PushM'.
348+class (Applicative m, Monad m) => MonadSample t m | m -> t where
349+ -- | Get the current value in the 'Behavior'
350+ sample :: Behavior t a -> m a
351+
352+-- | 'MonadHold' designates monads that can create new 'Behavior's based on
353+-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
354+-- is required to create any stateful computations with Reflex.
355+class MonadSample t m => MonadHold t m where
356+ -- | Create a new 'Behavior' whose value will initially be equal to the given
357+ -- value and will be updated whenever the given 'Event' occurs. The update
358+ -- takes effect immediately after the 'Event' occurs; if the occurrence that
359+ -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
360+ -- the 'Behavior', it will see the __old__ value of the 'Behavior', not the new
361+ -- one.
362+ hold :: a -> Event t a -> m (Behavior t a)
363+ default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)
364+ hold v0 = lift . hold v0
365+ -- | Create a 'Dynamic' value using the given initial value that changes every
366+ -- time the 'Event' occurs.
367+ holdDyn :: a -> Event t a -> m (Dynamic t a)
368+ default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)
369+ holdDyn v0 = lift . holdDyn v0
370+ -- | Create an 'Incremental' value using the given initial value that changes
371+ -- every time the 'Event' occurs.
372+ holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
373+ default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)
374+ holdIncremental v0 = lift . holdIncremental v0
375+ buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)
376+ {-
377+ default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)
378+ buildDynamic getV0 = lift . buildDynamic getV0
379+ -}
380+ -- | Create a new 'Event' that only occurs only once, on the first occurrence of
381+ -- the supplied 'Event'.
382+ headE :: Event t a -> m (Event t a)
383+
384+-- | Accumulate an 'Incremental' with the supplied initial value and the firings of the provided 'Event',
385+-- using the combining function to produce a patch.
386+accumIncremental
387+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
388+ => (PatchTarget p -> b -> p)
389+ -> PatchTarget p
390+ -> Event t b
391+ -> m (Incremental t p)
392+accumIncremental f = accumMaybeIncremental $ \v o -> Just $ f v o
393+
394+-- | Similar to 'accumIncremental' but the combining function runs in 'PushM'
395+accumMIncremental
396+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
397+ => (PatchTarget p -> b -> PushM t p)
398+ -> PatchTarget p
399+ -> Event t b
400+ -> m (Incremental t p)
401+accumMIncremental f = accumMaybeMIncremental $ \v o -> Just <$> f v o
402+
403+-- | Similar to 'accumIncremental' but allows filtering of updates (by dropping updates when the
404+-- combining function produces @Nothing@)
405+accumMaybeIncremental
406+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
407+ => (PatchTarget p -> b -> Maybe p)
408+ -> PatchTarget p
409+ -> Event t b
410+ -> m (Incremental t p)
411+accumMaybeIncremental f = accumMaybeMIncremental $ \v o -> return $ f v o
412+
413+-- | Similar to 'accumMaybeMIncremental' but the combining function runs in 'PushM'
414+accumMaybeMIncremental
415+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
416+ => (PatchTarget p -> b -> PushM t (Maybe p))
417+ -> PatchTarget p
418+ -> Event t b
419+ -> m (Incremental t p)
420+accumMaybeMIncremental f z e = do
421+ rec let e' = flip push e $ \o -> do
422+ v <- sample $ currentIncremental d'
423+ f v o
424+ d' <- holdIncremental z e'
425+ return d'
426+
427+-- | Accumulate an 'Incremental' by folding occurrences of an 'Event'
428+-- with a function that both accumulates and produces a value to fire
429+-- as an 'Event'. Returns both the accumulated value and the constructed
430+-- 'Event'.
431+mapAccumIncremental
432+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
433+ => (PatchTarget p -> b -> (p, c))
434+ -> PatchTarget p
435+ -> Event t b
436+ -> m (Incremental t p, Event t c)
437+mapAccumIncremental f = mapAccumMaybeIncremental $ \v o -> bimap Just Just $ f v o
438+
439+-- | Like 'mapAccumIncremental' but the combining function runs in 'PushM'
440+mapAccumMIncremental
441+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
442+ => (PatchTarget p -> b -> PushM t (p, c))
443+ -> PatchTarget p
444+ -> Event t b
445+ -> m (Incremental t p, Event t c)
446+mapAccumMIncremental f = mapAccumMaybeMIncremental $ \v o -> bimap Just Just <$> f v o
447+
448+-- | Accumulate an 'Incremental' by folding occurrences of an 'Event' with
449+-- a function that both optionally accumulates and optionally produces
450+-- a value to fire as a separate output 'Event'.
451+-- Note that because 'Nothing's are discarded in both cases, the output
452+-- 'Event' may fire even though the output 'Incremental' has not changed, and
453+-- the output 'Incremental' may update even when the output 'Event' is not firing.
454+mapAccumMaybeIncremental
455+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
456+ => (PatchTarget p -> b -> (Maybe p, Maybe c))
457+ -> PatchTarget p
458+ -> Event t b
459+ -> m (Incremental t p, Event t c)
460+mapAccumMaybeIncremental f = mapAccumMaybeMIncremental $ \v o -> return $ f v o
461+
462+-- | Like 'mapAccumMaybeIncremental' but the combining function is a 'PushM' action
463+mapAccumMaybeMIncremental
464+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
465+ => (PatchTarget p -> b -> PushM t (Maybe p, Maybe c))
466+ -> PatchTarget p
467+ -> Event t b
468+ -> m (Incremental t p, Event t c)
469+mapAccumMaybeMIncremental f z e = do
470+ rec let e' = flip push e $ \o -> do
471+ v <- sample $ currentIncremental d'
472+ result <- f v o
473+ return $ case result of
474+ (Nothing, Nothing) -> Nothing
475+ _ -> Just result
476+ d' <- holdIncremental z $ mapMaybe fst e'
477+ return (d', mapMaybe snd e')
478+
479+-- | A somewhat slow implementation of 'headE'
480+slowHeadE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
481+slowHeadE e = do
482+ rec be <- hold e $ fmapCheap (const never) e'
483+ let e' = switch be
484+ return e'
485+
486+-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
487+-- key. This is much more efficient than filtering for each key with
488+-- 'mapMaybe'.
489+newtype EventSelector t k = EventSelector
490+ { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
491+ -- determined by the type of the key, so this can be used to fan-out
492+ -- 'Event's whose sub-'Event's have different types.
493+ --
494+ -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
495+ -- (but equivalent to) using 'mapMaybe' to select only the relevant
496+ -- occurrences of an 'Event'.
497+ select :: forall a. k a -> Event t a
498+ }
499+
500+-- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually
501+-- filtering by key.
502+newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }
503+
504+--------------------------------------------------------------------------------
505+-- Instances
506+--------------------------------------------------------------------------------
507+
508+instance MonadSample t m => MonadSample t (ReaderT r m) where
509+ sample = lift . sample
510+
511+instance MonadHold t m => MonadHold t (ReaderT r m) where
512+ hold a0 = lift . hold a0
513+ holdDyn a0 = lift . holdDyn a0
514+ holdIncremental a0 = lift . holdIncremental a0
515+ buildDynamic a0 = lift . buildDynamic a0
516+ headE = lift . headE
517+
518+instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
519+ sample = lift . sample
520+
521+instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
522+ hold a0 = lift . hold a0
523+ holdDyn a0 = lift . holdDyn a0
524+ holdIncremental a0 = lift . holdIncremental a0
525+ buildDynamic a0 = lift . buildDynamic a0
526+ headE = lift . headE
527+
528+instance MonadSample t m => MonadSample t (StateT s m) where
529+ sample = lift . sample
530+
531+instance MonadHold t m => MonadHold t (StateT s m) where
532+ hold a0 = lift . hold a0
533+ holdDyn a0 = lift . holdDyn a0
534+ holdIncremental a0 = lift . holdIncremental a0
535+ buildDynamic a0 = lift . buildDynamic a0
536+ headE = lift . headE
537+
538+instance MonadSample t m => MonadSample t (ExceptT e m) where
539+ sample = lift . sample
540+
541+instance MonadHold t m => MonadHold t (ExceptT e m) where
542+ hold a0 = lift . hold a0
543+ holdDyn a0 = lift . holdDyn a0
544+ holdIncremental a0 = lift . holdIncremental a0
545+ buildDynamic a0 = lift . buildDynamic a0
546+ headE = lift . headE
547+
548+instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
549+ sample = lift . sample
550+
551+instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
552+ hold a0 = lift . hold a0
553+ holdDyn a0 = lift . holdDyn a0
554+ holdIncremental a0 = lift . holdIncremental a0
555+ buildDynamic a0 = lift . buildDynamic a0
556+ headE = lift . headE
557+
558+instance MonadSample t m => MonadSample t (ContT r m) where
559+ sample = lift . sample
560+
561+instance MonadHold t m => MonadHold t (ContT r m) where
562+ hold a0 = lift . hold a0
563+ holdDyn a0 = lift . holdDyn a0
564+ holdIncremental a0 = lift . holdIncremental a0
565+ buildDynamic a0 = lift . buildDynamic a0
566+ headE = lift . headE
567+
568+--------------------------------------------------------------------------------
569+-- Convenience functions
570+--------------------------------------------------------------------------------
571+
572+-- | Create an 'Event' from another 'Event'. The provided function can sample
573+-- 'Behavior's and hold 'Event's.
574+pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
575+pushAlways f = push (fmap Just . f)
576+
577+-- | Flipped version of 'fmap'.
578+ffor :: Functor f => f a -> (a -> b) -> f b
579+ffor = flip fmap
580+
581+-- | Rotated version of 'liftA2'.
582+ffor2 :: Applicative f => f a -> f b -> (a -> b -> c) -> f c
583+ffor2 a b f = liftA2 f a b
584+
585+-- | Rotated version of 'liftA3'.
586+ffor3 :: Applicative f => f a -> f b -> f c -> (a -> b -> c -> d) -> f d
587+ffor3 a b c f = liftA3 f a b c
588+
589+instance Reflex t => Applicative (Behavior t) where
590+ pure = constant
591+ f <*> x = pull $ sample f `ap` sample x
592+ _ *> b = b
593+ a <* _ = a
594+
595+instance Reflex t => Apply (Behavior t) where
596+ (<.>) = (<*>)
597+
598+instance Reflex t => Bind (Behavior t) where
599+ (>>-) = (>>=)
600+
601+instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
602+ (/) = liftA2 (/)
603+ fromRational = pure . fromRational
604+ recip = fmap recip
605+
606+instance Reflex t => Functor (Behavior t) where
607+ fmap f = pull . fmap f . sample
608+
609+instance (Reflex t, IsString a) => IsString (Behavior t a) where
610+ fromString = pure . fromString
611+
612+instance Reflex t => Monad (Behavior t) where
613+ a >>= f = pull $ sample a >>= sample . f
614+ -- 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.
615+ return = constant
616+ fail = error "Monad (Behavior t) does not support fail"
617+
618+instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
619+ mempty = constant mempty
620+ mappend a b = pull $ liftM2 mappend (sample a) (sample b)
621+ mconcat = pull . fmap mconcat . mapM sample
622+
623+instance (Reflex t, Num a) => Num (Behavior t a) where
624+ (+) = liftA2 (+)
625+ (-) = liftA2 (-)
626+ (*) = liftA2 (*)
627+ abs = fmap abs
628+ fromInteger = pure . fromInteger
629+ negate = fmap negate
630+ signum = fmap signum
631+
632+instance (Num a, Reflex t) => Num (Dynamic t a) where
633+ (+) = liftA2 (+)
634+ (*) = liftA2 (*)
635+ abs = fmap abs
636+ signum = fmap signum
637+ fromInteger = pure . fromInteger
638+ negate = fmap negate
639+ (-) = liftA2 (-)
640+
641+instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
642+ a <> b = pull $ liftM2 (<>) (sample a) (sample b)
643+ sconcat = pull . fmap sconcat . mapM sample
644+#if MIN_VERSION_semigroups(0,17,0)
645+ stimes n = fmap $ stimes n
646+#else
647+ times1p n = fmap $ times1p n
648+#endif
649+
650+-- | Alias for 'mapMaybe'
651+fmapMaybe :: Filterable f => (a -> Maybe b) -> f a -> f b
652+fmapMaybe = mapMaybe
653+
654+-- | Flipped version of 'mapMaybe'.
655+fforMaybe :: Filterable f => f a -> (a -> Maybe b) -> f b
656+fforMaybe = flip mapMaybe
657+
658+-- | Filter 'f a' using the provided predicate.
659+ffilter :: Filterable f => (a -> Bool) -> f a -> f a
660+ffilter = W.filter
661+
662+-- | Filter 'Left's from 'f (Either a b)' into 'a'.
663+filterLeft :: Filterable f => f (Either a b) -> f a
664+filterLeft = mapMaybe (either Just (const Nothing))
665+
666+-- | Filter 'Right's from 'f (Either a b)' into 'b'.
667+filterRight :: Filterable f => f (Either a b) -> f b
668+filterRight = mapMaybe (either (const Nothing) Just)
669+
670+-- | Left-biased event union (prefers left event on simultaneous
671+-- occurrence).
672+instance Reflex t => Alt (Event t) where
673+ ev1 <!> ev2 = leftmost [ev1, ev2]
674+
675+-- | 'Event' intersection (convenient interface to 'coincidence').
676+instance Reflex t => Apply (Event t) where
677+ evf <.> evx = coincidence (fmap (<$> evx) evf)
678+
679+-- | 'Event' intersection (convenient interface to 'coincidence').
680+instance Reflex t => Bind (Event t) where
681+ evx >>- f = coincidence (f <$> evx)
682+ join = coincidence
683+
684+instance Reflex t => Functor (Event t) where
685+ {-# INLINE fmap #-}
686+ fmap f = mapMaybe $ Just . f
687+ {-# INLINE (<$) #-}
688+ x <$ e = fmapCheap (const x) e
689+
690+-- TODO Remove this instance
691+instance Reflex t => FunctorMaybe (Event t) where
692+ {-# INLINE fmapMaybe #-}
693+ fmapMaybe = mapMaybe
694+
695+instance Reflex t => Filterable (Event t) where
696+ {-# INLINE mapMaybe #-}
697+ mapMaybe f = push $ return . f
698+
699+-- | Never: @'zero' = 'never'@.
700+instance Reflex t => Plus (Event t) where
701+ zero = never
702+
703+-- | Replace each occurrence value of the 'Event' with the value of the
704+-- 'Behavior' at the time of that occurrence.
705+tag :: Reflex t => Behavior t b -> Event t a -> Event t b
706+tag b = pushAlways $ \_ -> sample b
707+
708+-- | Replace each occurrence value of the 'Event' with the value of the
709+-- 'Behavior' at that time; if it is 'Just', fire with the contained value; if
710+-- it is 'Nothing', drop the occurrence.
711+tagMaybe :: Reflex t => Behavior t (Maybe b) -> Event t a -> Event t b
712+tagMaybe b = push $ \_ -> sample b
713+
714+-- | Create a new 'Event' that combines occurrences of supplied 'Event' with the
715+-- current value of the 'Behavior'.
716+attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
717+attach = attachWith (,)
718+
719+-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
720+-- combining it with the current value of the 'Behavior'.
721+attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
722+attachWith f = attachWithMaybe $ \a b -> Just $ f a b
723+
724+-- | Create a new 'Event' by combining each occurrence with the current value of
725+-- the 'Behavior'. The occurrence is discarded if the combining function returns
726+-- Nothing
727+attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
728+attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
729+
730+-- | Create a new 'Event' that occurs on all but the first occurrence of the
731+-- supplied 'Event'.
732+tailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a)
733+tailE e = snd <$> headTailE e
734+
735+-- | Create a tuple of two 'Event's with the first one occurring only the first
736+-- time the supplied 'Event' occurs and the second occurring on all but the first
737+-- occurrence.
738+headTailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a, Event t a)
739+headTailE e = do
740+ eHead <- headE e
741+ be <- hold never $ fmap (const e) eHead
742+ return (eHead, switch be)
743+
744+-- | Take the streak of occurrences starting at the current time for which the
745+-- event returns 'True'.
746+--
747+-- Starting at the current time, fire all the occurrences of the 'Event' for
748+-- which the given predicate returns 'True'. When first 'False' is returned,
749+-- do not fire, and permanently stop firing, even if 'True' values would have
750+-- been encountered later.
751+takeWhileE
752+ :: forall t m a
753+ . (Reflex t, MonadFix m, MonadHold t m)
754+ => (a -> Bool)
755+ -> Event t a
756+ -> m (Event t a)
757+takeWhileE f = takeWhileJustE $ \v -> guard (f v) $> v
758+
759+-- | Take the streak of occurrences starting at the current time for which the
760+-- event returns 'Just b'.
761+--
762+-- Starting at the current time, fire all the occurrences of the 'Event' for
763+-- which the given predicate returns 'Just b'. When first 'Nothing' is returned,
764+-- do not fire, and permanently stop firing, even if 'Just b' values would have
765+-- been encountered later.
766+takeWhileJustE
767+ :: forall t m a b
768+ . (Reflex t, MonadFix m, MonadHold t m)
769+ => (a -> Maybe b)
770+ -> Event t a
771+ -> m (Event t b)
772+takeWhileJustE f e = do
773+ rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of
774+ Nothing -> Left never
775+ Just b -> Right b
776+ eFirstBad <- headE eBad
777+ e' <- switchHold e eFirstBad
778+ return eTrue
779+
780+-- | Drop the streak of occurrences starting at the current time for which the
781+-- event returns 'True'.
782+--
783+-- Starting at the current time, do not fire all the occurrences of the 'Event'
784+-- for which the given predicate returns 'True'. When 'False' is first
785+-- returned, do fire, and permanently continue firing, even if 'True' values
786+-- would have been encountered later.
787+dropWhileE
788+ :: forall t m a
789+ . (Reflex t, MonadFix m, MonadHold t m)
790+ => (a -> Bool)
791+ -> Event t a
792+ -> m (Event t a)
793+dropWhileE f e = snd <$> takeDropWhileJustE (\v -> guard (f v) $> v) e
794+
795+-- | Both take and drop the streak of occurrences starting at the current time
796+-- for which the event returns 'Just b'.
797+--
798+-- For the left event, starting at the current time, fire all the occurrences
799+-- of the 'Event' for which the given function returns 'Just b'. When
800+-- 'Nothing' is returned, do not fire, and permanently stop firing, even if
801+-- 'Just b' values would have been encountered later.
802+--
803+-- For the right event, do not fire until the first occurrence where the given
804+-- function returns 'Nothing', and fire that one and all subsequent
805+-- occurrences. Even if the function would have again returned 'Just b', keep
806+-- on firing.
807+takeDropWhileJustE
808+ :: forall t m a b
809+ . (Reflex t, MonadFix m, MonadHold t m)
810+ => (a -> Maybe b)
811+ -> Event t a
812+ -> m (Event t b, Event t a)
813+takeDropWhileJustE f e = do
814+ rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of
815+ Nothing -> Left ()
816+ Just b -> Right b
817+ eFirstBad <- headE eBad
818+ e' <- switchHold e (never <$ eFirstBad)
819+ eRest <- switchHoldPromptOnly never (e <$ eFirstBad)
820+ return (eGood, eRest)
821+
822+-- | Split the supplied 'Event' into two individual 'Event's occurring at the
823+-- same time with the respective values from the tuple.
824+splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
825+splitE e = (fmap fst e, fmap snd e)
826+
827+-- | Print the supplied 'String' and the value of the 'Event' on each
828+-- occurrence. This should /only/ be used for debugging.
829+--
830+-- Note: As with Debug.Trace.trace, the message will only be printed if the
831+-- 'Event' is actually used.
832+traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
833+traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
834+
835+-- | Print the output of the supplied function on each occurrence of the
836+-- 'Event'. This should /only/ be used for debugging.
837+--
838+-- Note: As with Debug.Trace.trace, the message will only be printed if the
839+-- 'Event' is actually used.
840+traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
841+traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
842+
843+instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
844+ (<>) = alignWith (mergeThese (<>))
845+ sconcat = fmap sconcat . mergeList . toList
846+#if MIN_VERSION_semigroups(0,17,0)
847+ stimes n = fmap $ stimes n
848+#else
849+ times1p n = fmap $ times1p n
850+#endif
851+
852+instance (Semigroup a, Reflex t) => Monoid (Event t a) where
853+ mempty = never
854+ mappend = (<>)
855+ mconcat = fmap sconcat . mergeList
856+
857+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
858+-- list occurs. If multiple occur at the same time they are folded from the left
859+-- with the given function.
860+{-# INLINE mergeWith #-}
861+mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
862+mergeWith = mergeWith' id
863+
864+{-# INLINE mergeWith' #-}
865+mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
866+mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)
867+ . mergeInt
868+ . IntMap.fromDistinctAscList
869+ $ zip [0 :: Int ..] es
870+
871+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
872+-- list occurs. If multiple occur at the same time the value is the value of the
873+-- leftmost event.
874+{-# INLINE leftmost #-}
875+leftmost :: Reflex t => [Event t a] -> Event t a
876+leftmost = mergeWith const
877+
878+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
879+-- list occurs and has a list of the values of all 'Event's occurring at that
880+-- time.
881+mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
882+mergeList [] = never
883+mergeList es = mergeWithFoldCheap' id es
884+
885+unsafeMapIncremental
886+ :: (Reflex t, Patch p, Patch p')
887+ => (PatchTarget p -> PatchTarget p')
888+ -> (p -> p')
889+ -> Incremental t p
890+ -> Incremental t p'
891+unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
892+
893+-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
894+-- occurs if at least one of them occurs and has a map of values of all 'Event's
895+-- occurring at that time.
896+mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
897+mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
898+
899+-- | Like 'mergeMap' but for 'IntMap'.
900+mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
901+mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap
902+
903+-- | Create a merge whose parents can change over time
904+mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a)
905+mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id)
906+
907+-- | Create a merge whose parents can change over time
908+mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
909+mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)
910+
911+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
912+mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a)
913+mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id)
914+
915+-- | Split the event into separate events for 'Left' and 'Right' values.
916+fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
917+fanEither e =
918+ let justLeft = either Just (const Nothing)
919+ justRight = either (const Nothing) Just
920+ in (mapMaybe justLeft e, mapMaybe justRight e)
921+
922+-- | Split the event into separate events for 'This' and 'That' values,
923+-- allowing them to fire simultaneously when the input value is 'These'.
924+fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
925+fanThese e =
926+ let this (This x) = Just x
927+ this (These x _) = Just x
928+ this _ = Nothing
929+ that (That y) = Just y
930+ that (These _ y) = Just y
931+ that _ = Nothing
932+ in (mapMaybe this e, mapMaybe that e)
933+
934+-- | Split the event into an 'EventSelector' that allows efficient selection of
935+-- the individual 'Event's.
936+fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
937+fanMap = fan . fmap mapToDMap
938+
939+-- | Switches to the new event whenever it receives one. Only the old event is
940+-- considered the moment a new one is switched in; the output event will fire at
941+-- that moment only if the old event does.
942+--
943+-- Because the simultaneous firing case is irrelevant, this function imposes
944+-- laxer "timing requirements" on the overall circuit, avoiding many potential
945+-- cyclic dependency / metastability failures. It's also more performant. Use
946+-- this rather than 'switchHoldPromptly' and 'switchHoldPromptOnly' unless you
947+-- are absolutely sure you need to act on the new event in the coincidental
948+-- case.
949+switchHold :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
950+switchHold ea0 eea = switch <$> hold ea0 eea
951+
952+-- | Switches to the new event whenever it receives one. Whenever a new event is
953+-- provided, if it is firing, its value will be the resulting event's value; if
954+-- it is not firing, but the old one is, the old one's value will be used.
955+--
956+-- 'switchHold', by always forwarding the old event the moment it is switched
957+-- out, avoids many potential cyclic dependency problems / metastability
958+-- problems. It's also more performant. Use it instead unless you are sure you
959+-- cannot.
960+switchHoldPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
961+switchHoldPromptly ea0 eea = do
962+ bea <- hold ea0 eea
963+ let eLag = switch bea
964+ eCoincidences = coincidence eea
965+ return $ leftmost [eCoincidences, eLag]
966+
967+-- | switches to a new event whenever it receives one. At the moment of
968+-- switching, the old event will be ignored if it fires, and the new one will be
969+-- used if it fires; this is the opposite of 'switch', which will use only the
970+-- old value.
971+--
972+-- 'switchHold', by always forwarding the old event the moment it is switched
973+-- out, avoids many potential cyclic dependency problems / metastability
974+-- problems. It's also more performant. Use it instead unless you are sure you
975+-- cannot.
976+switchHoldPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
977+switchHoldPromptOnly e0 e' = do
978+ eLag <- switch <$> hold e0 e'
979+ return $ coincidence $ leftmost [e', eLag <$ eLag]
980+
981+-- | When the given outer event fires, condense the inner events into the contained patch. Non-firing inner events will be replaced with deletions.
982+coincidencePatchMap :: (Reflex t, Ord k) => Event t (PatchMap k (Event t v)) -> Event t (PatchMap k v)
983+coincidencePatchMap e = fmapCheap PatchMap $ coincidence $ ffor e $ \(PatchMap m) -> mergeMap $ ffor m $ \case
984+ Nothing -> fmapCheap (const Nothing) e
985+ Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
986+
987+-- | See 'coincidencePatchMap'
988+coincidencePatchIntMap :: Reflex t => Event t (PatchIntMap (Event t v)) -> Event t (PatchIntMap v)
989+coincidencePatchIntMap e = fmapCheap PatchIntMap $ coincidence $ ffor e $ \(PatchIntMap m) -> mergeIntMap $ ffor m $ \case
990+ Nothing -> fmapCheap (const Nothing) e
991+ Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
992+
993+-- | See 'coincidencePatchMap'
994+coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v)
995+coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of
996+ PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->
997+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
998+ PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->
999+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }
1000+ PatchMapWithMove.From_Insert ev -> leftmost
1001+ [ fforCheap ev $ \v ->
1002+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }
1003+ , fforCheap e $ \_ ->
1004+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1005+ ]
1006+
1007+-- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es
1008+-- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that
1009+-- fires with the patched value.
1010+switchHoldPromptOnlyIncremental
1011+ :: forall t m p pt w
1012+ . ( Reflex t
1013+ , MonadHold t m
1014+ , Patch (p (Event t w))
1015+ , PatchTarget (p (Event t w)) ~ pt (Event t w)
1016+ , Patch (p w)
1017+ , PatchTarget (p w) ~ pt w
1018+ , Monoid (pt w)
1019+ )
1020+ => (Incremental t (p (Event t w)) -> Event t (pt w))
1021+ -> (Event t (p (Event t w)) -> Event t (p w))
1022+ -> pt (Event t w)
1023+ -> Event t (p (Event t w))
1024+ -> m (Event t (pt w))
1025+switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch e0 e' = do
1026+ lag <- mergePatchIncremental <$> holdIncremental e0 e'
1027+ pure $ ffor (align lag (coincidencePatch e')) $ \case
1028+ This old -> old
1029+ That new -> new `applyAlways` mempty
1030+ These old new -> new `applyAlways` old
1031+
1032+instance Reflex t => Align (Event t) where
1033+ nil = never
1034+#if MIN_VERSION_these(0, 8, 0)
1035+instance Reflex t => Semialign (Event t) where
1036+#endif
1037+ align = alignEventWithMaybe Just
1038+
1039+
1040+-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
1041+-- the 'Behavior' is true at the time of occurrence.
1042+gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
1043+gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
1044+
1045+-- | Create a new behavior given a starting behavior and switch to the behavior
1046+-- carried by the event when it fires.
1047+switcher :: (Reflex t, MonadHold t m)
1048+ => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
1049+switcher b eb = pull . (sample <=< sample) <$> hold b eb
1050+
1051+instance (Reflex t, IsString a) => IsString (Dynamic t a) where
1052+ fromString = pure . fromString
1053+
1054+-- | Combine two 'Dynamic's. The result will change whenever either (or both)
1055+-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
1056+zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
1057+zipDyn = zipDynWith (,)
1058+
1059+-- | Combine two 'Dynamic's with a combining function. The result will change
1060+-- whenever either (or both) input 'Dynamic' changes.
1061+-- More efficient than 'liftA2'.
1062+zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
1063+zipDynWith f da db =
1064+ let eab = align (updated da) (updated db)
1065+ ec = flip push eab $ \o -> do
1066+ (a, b) <- case o of
1067+ This a -> do
1068+ b <- sample $ current db
1069+ return (a, b)
1070+ That b -> do
1071+ a <- sample $ current da
1072+ return (a, b)
1073+ These a b -> return (a, b)
1074+ return $ Just $ f a b
1075+ in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
1076+
1077+instance (Reflex t, Semigroup a) => Semigroup (Dynamic t a) where
1078+ (<>) = zipDynWith (<>)
1079+#if MIN_VERSION_semigroups(0,17,0)
1080+ stimes n = fmap $ stimes n
1081+#else
1082+ times1p n = fmap $ times1p n
1083+#endif
1084+
1085+instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
1086+ mconcat = distributeListOverDynWith mconcat
1087+ mempty = constDyn mempty
1088+ mappend = zipDynWith mappend
1089+
1090+-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1091+-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1092+-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1093+distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
1094+distributeDMapOverDynPure = distributeDMapOverDynPureG coerceDynamic
1095+
1096+-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1097+-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1098+-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1099+distributeDMapOverDynPureG
1100+ :: forall t k q v. (Reflex t, GCompare k)
1101+ => (forall a. q a -> Dynamic t (v a))
1102+ -> DMap k q -> Dynamic t (DMap k v)
1103+distributeDMapOverDynPureG nt dm = case DMap.toList dm of
1104+ [] -> constDyn DMap.empty
1105+ [k :=> v] -> DMap.singleton k <$> nt v
1106+ _ ->
1107+ let getInitial = DMap.traverseWithKey (\_ -> sample . current . nt) dm
1108+ edmPre = mergeG getCompose $ DMap.map (Compose . updated . nt) dm
1109+ result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
1110+ olds <- sample $ current result
1111+ return $ DMap.unionWithKey (\_ _ new -> new) olds news
1112+ in result
1113+
1114+-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
1115+distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
1116+distributeListOverDyn = distributeListOverDynWith id
1117+
1118+-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
1119+distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
1120+distributeListOverDynWith f =
1121+ fmap (f . map fromDSum . DMap.toAscList) .
1122+ distributeDMapOverDynPure .
1123+ DMap.fromDistinctAscList .
1124+ zipWith toDSum [0..]
1125+ where
1126+ toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
1127+ toDSum k v = Const2 k :=> v
1128+ fromDSum :: DSum (Const2 Int a) Identity -> a
1129+ fromDSum (Const2 _ :=> Identity v) = v
1130+
1131+-- | Create a new 'Event' that occurs when the first supplied 'Event' occurs
1132+-- unless the second supplied 'Event' occurs simultaneously.
1133+difference :: Reflex t => Event t a -> Event t b -> Event t a
1134+difference = alignEventWithMaybe $ \case
1135+ This a -> Just a
1136+ _ -> Nothing
1137+
1138+-- | Zips two values by taking the union of their shapes and combining with the provided function.
1139+-- 'Nothing' values are dropped.
1140+alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c
1141+alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $
1142+ merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1143+
1144+-- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that
1145+-- matches the provided key.
1146+filterEventKey
1147+ :: forall t m k v a.
1148+ ( Reflex t
1149+ , MonadFix m
1150+ , MonadHold t m
1151+ , GEq k
1152+ )
1153+ => k a
1154+ -> Event t (DSum k v)
1155+ -> m (Event t (v a))
1156+filterEventKey k kv' = do
1157+ let f :: DSum k v -> Maybe (v a)
1158+ f (newK :=> newV) = case newK `geq` k of
1159+ Just Refl -> Just newV
1160+ Nothing -> Nothing
1161+ takeWhileJustE f kv'
1162+
1163+-- | "Factor" the input 'DSum' 'Event' to produce an 'Event' which
1164+-- fires when the 'DSum' key changes and contains both the value of the
1165+-- 'DSum' at switchover and an 'Event' of values produced by subsequent
1166+-- firings of the input 'Event' that do not change the 'DSum' key.
1167+factorEvent
1168+ :: forall t m k v a.
1169+ ( Reflex t
1170+ , MonadFix m
1171+ , MonadHold t m
1172+ , GEq k
1173+ )
1174+ => k a
1175+ -> Event t (DSum k v)
1176+ -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v))))
1177+factorEvent k0 kv' = do
1178+ key :: Behavior t (Some k) <- hold (Some k0) $ fmapCheap (\(k :=> _) -> Some k) kv'
1179+ let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case
1180+ Some oldKey -> case newKey `geq` oldKey of
1181+ Just Refl -> return Nothing
1182+ Nothing -> do
1183+ newInner <- filterEventKey newKey kv'
1184+ return $ Just $ newKey :=> Pair newVal (Compose newInner)
1185+ eInitial <- filterEventKey k0 kv'
1186+ return (eInitial, update)
1187+
1188+--------------------------------------------------------------------------------
1189+-- Accumulator
1190+--------------------------------------------------------------------------------
1191+
1192+-- | An 'Accumulator' type can be built by accumulating occurrences of an
1193+-- 'Event'.
1194+#if __GLASGOW_HASKELL__ < 802
1195+{-# WARNING accum "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1196+{-# WARNING accumM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1197+{-# WARNING accumMaybe "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1198+{-# WARNING accumMaybeM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1199+#endif
1200+class Reflex t => Accumulator t f | f -> t where
1201+ accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
1202+ accum f = accumMaybe $ \v o -> Just $ f v o
1203+ accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
1204+ accumM f = accumMaybeM $ \v o -> Just <$> f v o
1205+ accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
1206+ accumMaybe f = accumMaybeM $ \v o -> return $ f v o
1207+ accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
1208+ mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
1209+ mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
1210+ mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
1211+ mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
1212+ mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1213+ mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
1214+ mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1215+
1216+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1217+-- with the provided function. See 'foldDyn'.
1218+accumDyn
1219+ :: (Reflex t, MonadHold t m, MonadFix m)
1220+ => (a -> b -> a)
1221+ -> a
1222+ -> Event t b
1223+ -> m (Dynamic t a)
1224+accumDyn f = accumMaybeDyn $ \v o -> Just $ f v o
1225+
1226+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1227+-- with the provided 'PushM' action.
1228+accumMDyn
1229+ :: (Reflex t, MonadHold t m, MonadFix m)
1230+ => (a -> b -> PushM t a)
1231+ -> a
1232+ -> Event t b
1233+ -> m (Dynamic t a)
1234+accumMDyn f = accumMaybeMDyn $ \v o -> Just <$> f v o
1235+
1236+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1237+-- with the provided function, discarding 'Nothing' results.
1238+accumMaybeDyn
1239+ :: (Reflex t, MonadHold t m, MonadFix m)
1240+ => (a -> b -> Maybe a)
1241+ -> a
1242+ -> Event t b
1243+ -> m (Dynamic t a)
1244+accumMaybeDyn f = accumMaybeMDyn $ \v o -> return $ f v o
1245+
1246+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1247+-- with the provided 'PushM' action, discarding 'Nothing' results.
1248+accumMaybeMDyn
1249+ :: (Reflex t, MonadHold t m, MonadFix m)
1250+ => (a -> b -> PushM t (Maybe a))
1251+ -> a
1252+ -> Event t b
1253+ -> m (Dynamic t a)
1254+accumMaybeMDyn f z e = do
1255+ rec let e' = flip push e $ \o -> do
1256+ v <- sample $ current d'
1257+ f v o
1258+ d' <- holdDyn z e'
1259+ return d'
1260+
1261+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1262+-- with a function that both accumulates and produces a value to fire
1263+-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1264+mapAccumDyn
1265+ :: (Reflex t, MonadHold t m, MonadFix m)
1266+ => (a -> b -> (a, c))
1267+ -> a
1268+ -> Event t b
1269+ -> m (Dynamic t a, Event t c)
1270+mapAccumDyn f = mapAccumMaybeDyn $ \v o -> bimap Just Just $ f v o
1271+
1272+-- | Similar to 'mapAccumDyn' except that the combining function is a
1273+-- 'PushM' action.
1274+mapAccumMDyn
1275+ :: (Reflex t, MonadHold t m, MonadFix m)
1276+ => (a -> b -> PushM t (a, c))
1277+ -> a
1278+ -> Event t b
1279+ -> m (Dynamic t a, Event t c)
1280+mapAccumMDyn f = mapAccumMaybeMDyn $ \v o -> bimap Just Just <$> f v o
1281+
1282+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event' with
1283+-- a function that both optionally accumulates and optionally produces
1284+-- a value to fire as a separate output 'Event'.
1285+-- Note that because 'Nothing's are discarded in both cases, the output
1286+-- 'Event' may fire even though the output 'Dynamic' has not changed, and
1287+-- the output 'Dynamic' may update even when the output 'Event' is not firing.
1288+mapAccumMaybeDyn
1289+ :: (Reflex t, MonadHold t m, MonadFix m)
1290+ => (a -> b -> (Maybe a, Maybe c))
1291+ -> a
1292+ -> Event t b
1293+ -> m (Dynamic t a, Event t c)
1294+mapAccumMaybeDyn f = mapAccumMaybeMDyn $ \v o -> return $ f v o
1295+
1296+-- | Like 'mapAccumMaybeDyn' except that the combining function is a
1297+-- 'PushM' action.
1298+mapAccumMaybeMDyn
1299+ :: (Reflex t, MonadHold t m, MonadFix m)
1300+ => (a -> b -> PushM t (Maybe a, Maybe c))
1301+ -> a
1302+ -> Event t b
1303+ -> m (Dynamic t a, Event t c)
1304+mapAccumMaybeMDyn f z e = do
1305+ rec let e' = flip push e $ \o -> do
1306+ v <- sample $ current d'
1307+ result <- f v o
1308+ return $ case result of
1309+ (Nothing, Nothing) -> Nothing
1310+ _ -> Just result
1311+ d' <- holdDyn z $ mapMaybe fst e'
1312+ return (d', mapMaybe snd e')
1313+
1314+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1315+-- with the provided function.
1316+{-# INLINE accumB #-}
1317+accumB
1318+ :: (Reflex t, MonadHold t m, MonadFix m)
1319+ => (a -> b -> a)
1320+ -> a
1321+ -> Event t b
1322+ -> m (Behavior t a)
1323+accumB f = accumMaybeB $ \v o -> Just $ f v o
1324+
1325+-- | Like 'accumB' except that the combining function is a 'PushM' action.
1326+{-# INLINE accumMB #-}
1327+accumMB
1328+ :: (Reflex t, MonadHold t m, MonadFix m)
1329+ => (a -> b -> PushM t a)
1330+ -> a
1331+ -> Event t b
1332+ -> m (Behavior t a)
1333+accumMB f = accumMaybeMB $ \v o -> Just <$> f v o
1334+
1335+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1336+-- with the provided function, discarding 'Nothing' results.
1337+{-# INLINE accumMaybeB #-}
1338+accumMaybeB
1339+ :: (Reflex t, MonadHold t m, MonadFix m)
1340+ => (a -> b -> Maybe a)
1341+ -> a
1342+ -> Event t b
1343+ -> m (Behavior t a)
1344+accumMaybeB f = accumMaybeMB $ \v o -> return $ f v o
1345+
1346+-- | Like 'accumMaybeB' except that the combining function is a 'PushM' action.
1347+{-# INLINE accumMaybeMB #-}
1348+accumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (Behavior t a)
1349+accumMaybeMB f z e = do
1350+ rec let e' = flip push e $ \o -> do
1351+ v <- sample d'
1352+ f v o
1353+ d' <- hold z e'
1354+ return d'
1355+
1356+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1357+-- with a function that both accumulates and produces a value to fire
1358+-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1359+{-# INLINE mapAccumB #-}
1360+mapAccumB
1361+ :: (Reflex t, MonadHold t m, MonadFix m)
1362+ => (a -> b -> (a, c))
1363+ -> a
1364+ -> Event t b
1365+ -> m (Behavior t a, Event t c)
1366+mapAccumB f = mapAccumMaybeB $ \v o -> bimap Just Just $ f v o
1367+
1368+-- | Like 'mapAccumB' except that the combining function is a 'PushM' action.
1369+{-# INLINE mapAccumMB #-}
1370+mapAccumMB
1371+ :: (Reflex t, MonadHold t m, MonadFix m)
1372+ => (a -> b -> PushM t (a, c))
1373+ -> a
1374+ -> Event t b
1375+ -> m (Behavior t a, Event t c)
1376+mapAccumMB f = mapAccumMaybeMB $ \v o -> bimap Just Just <$> f v o
1377+
1378+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event' with
1379+-- a function that both optionally accumulates and optionally produces
1380+-- a value to fire as a separate output 'Event'. 'Nothing's are discarded.
1381+{-# INLINE mapAccumMaybeB #-}
1382+mapAccumMaybeB
1383+ :: (Reflex t, MonadHold t m, MonadFix m)
1384+ => (a -> b -> (Maybe a, Maybe c))
1385+ -> a
1386+ -> Event t b
1387+ -> m (Behavior t a, Event t c)
1388+mapAccumMaybeB f = mapAccumMaybeMB $ \v o -> return $ f v o
1389+
1390+-- | Like 'mapAccumMaybeB' except that the combining function is a 'PushM' action.
1391+{-# INLINE mapAccumMaybeMB #-}
1392+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)
1393+mapAccumMaybeMB f z e = do
1394+ rec let e' = flip push e $ \o -> do
1395+ v <- sample d'
1396+ result <- f v o
1397+ return $ case result of
1398+ (Nothing, Nothing) -> Nothing
1399+ _ -> Just result
1400+ d' <- hold z $ mapMaybe fst e'
1401+ return (d', mapMaybe snd e')
1402+
1403+-- | Accumulate occurrences of an 'Event', producing an output occurrence each
1404+-- time. Discard the underlying 'Accumulator'.
1405+{-# INLINE mapAccum_ #-}
1406+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)
1407+mapAccum_ f z e = do
1408+ (_, result) <- mapAccumB f z e
1409+ return result
1410+
1411+-- | Accumulate occurrences of an 'Event', possibly producing an output
1412+-- occurrence each time. Discard the underlying 'Accumulator'.
1413+{-# INLINE mapAccumMaybe_ #-}
1414+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)
1415+mapAccumMaybe_ f z e = do
1416+ (_, result) <- mapAccumMaybeB f z e
1417+ return result
1418+
1419+-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
1420+-- an output occurrence each time. Discard the underlying 'Accumulator'.
1421+{-# INLINE mapAccumM_ #-}
1422+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)
1423+mapAccumM_ f z e = do
1424+ (_, result) <- mapAccumMB f z e
1425+ return result
1426+
1427+-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
1428+-- producing an output occurrence each time. Discard the underlying
1429+-- 'Accumulator'.
1430+{-# INLINE mapAccumMaybeM_ #-}
1431+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)
1432+mapAccumMaybeM_ f z e = do
1433+ (_, result) <- mapAccumMaybeMB f z e
1434+ return result
1435+
1436+instance Reflex t => Accumulator t (Dynamic t) where
1437+ accumMaybeM = accumMaybeMDyn
1438+ mapAccumMaybeM = mapAccumMaybeMDyn
1439+
1440+instance Reflex t => Accumulator t (Behavior t) where
1441+ accumMaybeM = accumMaybeMB
1442+ mapAccumMaybeM = mapAccumMaybeMB
1443+
1444+instance Reflex t => Accumulator t (Event t) where
1445+ accumMaybeM f z e = updated <$> accumMaybeM f z e
1446+ mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
1447+
1448+-- | Create a new 'Event' by combining each occurrence with the next value of the
1449+-- list using the supplied function. If the list runs out of items, all
1450+-- subsequent 'Event' occurrences will be ignored.
1451+zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
1452+zipListWithEvent f l e = do
1453+ let f' a b = case a of
1454+ h:t -> (Just t, Just $ f h b)
1455+ _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
1456+ mapAccumMaybe_ f' l e
1457+
1458+-- | Assign a number to each occurrence of the given 'Event', starting from 0
1459+{-# INLINE numberOccurrences #-}
1460+numberOccurrences :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Event t (b, a))
1461+numberOccurrences = numberOccurrencesFrom 0
1462+
1463+-- | Assign a number to each occurrence of the given 'Event'
1464+{-# INLINE numberOccurrencesFrom #-}
1465+numberOccurrencesFrom :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t (b, a))
1466+numberOccurrencesFrom = mapAccum_ (\n a -> let !next = n + 1 in (next, (n, a)))
1467+
1468+-- | Assign a number to each occurrence of the given 'Event'; discard the occurrences' values
1469+{-# INLINE numberOccurrencesFrom_ #-}
1470+numberOccurrencesFrom_ :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t b)
1471+numberOccurrencesFrom_ = mapAccum_ (\n _ -> let !next = n + 1 in (next, n))
1472+
1473+-- | This is used to sample the value of a 'Behavior' using an 'Event'.
1474+--
1475+-- The '<@>' operator is intended to be used in conjunction with
1476+-- the 'Applicative' instance for 'Behavior'.
1477+--
1478+-- This is useful when we want to combine the values of one 'Event' and
1479+-- the value of several 'Behavior's at the time the 'Event' is firing.
1480+--
1481+-- If we have:
1482+--
1483+-- > f :: a -> b -> c -> d
1484+-- > b1 :: Behavior t a
1485+-- > b2 :: Behavior t b
1486+-- > e :: Event t c
1487+--
1488+-- then we can do:
1489+--
1490+-- > f <$> b1 <*> b2 <@> e :: Event t d
1491+--
1492+-- in order to apply the function 'f' to the relevant values.
1493+--
1494+-- The alternative would be something like:
1495+--
1496+-- > attachWith (\(x1, x2) y -> f x1 x2 y) ((,) <$> b1 <*> b2) e :: Event t d
1497+--
1498+-- or a variation involing a custom data type to hold the combination of
1499+-- 'Behavior's even when that combination might only ever be used by 'f'.
1500+--
1501+-- A more suggestive example might be:
1502+--
1503+-- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)
1504+--
1505+(<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b
1506+(<@>) b = push $ \x -> do
1507+ f <- sample b
1508+ return . Just . f $ x
1509+infixl 4 <@>
1510+
1511+-- | An version of '<@>' that does not use the value of the 'Event'.
1512+--
1513+-- Alternatively, it is 'tag' in operator form.
1514+--
1515+-- This is useful when we want to combine the values of several
1516+-- 'Behavior's at particular points in time using an 'Applicative'
1517+-- style syntax.
1518+--
1519+-- If we have:
1520+--
1521+-- > g :: a -> b -> d
1522+-- > b1 :: Behavior t a
1523+-- > b2 :: Behavior t b
1524+-- > e :: Event t c
1525+--
1526+-- where 'e' is firing at the points in time of interest.
1527+--
1528+-- Then we can use '<@':
1529+--
1530+-- > g <$> b1 <*> b2 <@ e :: Event t d
1531+--
1532+-- to combine the values of 'b1' and 'b2' at each of those points of time,
1533+-- with the function 'g' being used to combine the values.
1534+--
1535+-- This is the same as '<@>' except that the 'Event' is being used only
1536+-- to act as a trigger.
1537+(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b
1538+(<@) = tag
1539+infixl 4 <@
1540+
1541+------------------
1542+-- Cheap Functions
1543+------------------
1544+
1545+-- | A "cheap" version of 'pushAlways'. See the performance note on 'pushCheap'.
1546+{-# INLINE pushAlwaysCheap #-}
1547+pushAlwaysCheap :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
1548+pushAlwaysCheap f = pushCheap (fmap Just . f)
1549+
1550+-- | A "cheap" version of 'mapMaybe'. See the performance note on 'pushCheap'.
1551+{-# INLINE mapMaybeCheap #-}
1552+mapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1553+mapMaybeCheap f = pushCheap $ return . f
1554+
1555+-- | An alias for 'mapMaybeCheap'
1556+{-# INLINE fmapMaybeCheap #-}
1557+fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1558+fmapMaybeCheap = mapMaybeCheap
1559+
1560+
1561+-- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'.
1562+{-# INLINE fforMaybeCheap #-}
1563+fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b
1564+fforMaybeCheap = flip mapMaybeCheap
1565+
1566+-- | A "cheap" version of 'ffor'. See the performance note on 'pushCheap'.
1567+{-# INLINE fforCheap #-}
1568+fforCheap :: Reflex t => Event t a -> (a -> b) -> Event t b
1569+fforCheap = flip fmapCheap
1570+
1571+-- | A "cheap" version of 'fmap'. See the performance note on 'pushCheap'.
1572+{-# INLINE fmapCheap #-}
1573+fmapCheap :: Reflex t => (a -> b) -> Event t a -> Event t b
1574+fmapCheap f = pushCheap $ return . Just . f
1575+
1576+-- | A "cheap" version of 'tag'. See the performance note on 'pushCheap'.
1577+{-# INLINE tagCheap #-}
1578+tagCheap :: Reflex t => Behavior t b -> Event t a -> Event t b
1579+tagCheap b = pushAlwaysCheap $ \_ -> sample b
1580+
1581+-- | Merge a collection of events; the resulting 'Event' will only occur if at
1582+-- least one input event is occurring, and will contain all of the input keys
1583+-- that are occurring simultaneously
1584+merge :: (Reflex t, GCompare k) => DMap k (Event t) -> Event t (DMap k Identity)
1585+merge = mergeG coerceEvent
1586+{-# INLINE merge #-}
1587+
1588+-- | Create a merge whose parents can change over time
1589+mergeIncremental :: (Reflex t, GCompare k)
1590+ => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
1591+mergeIncremental = mergeIncrementalG coerceEvent
1592+
1593+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
1594+mergeIncrementalWithMove :: (Reflex t, GCompare k)
1595+ => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity)
1596+mergeIncrementalWithMove = mergeIncrementalWithMoveG coerceEvent
1597+
1598+-- | A "cheap" version of 'mergeWithCheap'. See the performance note on 'pushCheap'.
1599+{-# INLINE mergeWithCheap #-}
1600+mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
1601+mergeWithCheap = mergeWithCheap' id
1602+
1603+-- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'.
1604+{-# INLINE mergeWithCheap' #-}
1605+mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
1606+mergeWithCheap' f g = mergeWithFoldCheap' $ foldl1 g . fmap f
1607+
1608+-- | A "cheap" version of 'mergeWithFoldCheap''. See the performance note on 'pushCheap'.
1609+{-# INLINE mergeWithFoldCheap' #-}
1610+mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b
1611+mergeWithFoldCheap' f es =
1612+ fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)
1613+ . mergeInt
1614+ . IntMap.fromDistinctAscList
1615+ $ zip [0 :: Int ..] es
1616+
1617+--------------------------------------------------------------------------------
1618+-- Deprecated functions
1619+--------------------------------------------------------------------------------
1620+
1621+{-# 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'. " #-}
1622+-- | See 'switchHoldPromptly'
1623+switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1624+switchPromptly = switchHoldPromptly
1625+{-# 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'. " #-}
1626+-- | See 'switchHoldPromptOnly'
1627+switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1628+switchPromptOnly = switchHoldPromptOnly
src/Reflex/Collection.hsnew file+218
@@ -0,0 +1,218 @@
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.hsnew file+530
@@ -0,0 +1,530 @@
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.hsnew file+106
@@ -0,0 +1,106 @@
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.hsnew file+105
@@ -0,0 +1,105 @@
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.hsnew file+7
@@ -0,0 +1,7 @@
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.hsnew file+237
@@ -0,0 +1,237 @@
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.hsnew file+30
@@ -0,0 +1,30 @@
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.hsnew file+7
@@ -0,0 +1,7 @@
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.hsnew file+306
@@ -0,0 +1,306 @@
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.hsnew file+27
@@ -0,0 +1,27 @@
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.hsnew file+200
@@ -0,0 +1,200 @@
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.hsnew file+47
@@ -0,0 +1,47 @@
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.hsnew file+280
@@ -0,0 +1,280 @@
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.hsnew file+45
@@ -0,0 +1,45 @@
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.hsnew file+78
@@ -0,0 +1,78 @@
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.hsnew file+65
@@ -0,0 +1,65 @@
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.hsnew file+46
@@ -0,0 +1,46 @@
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 Data.Map.Monoidal (MonoidalMap)
25+import Data.Semigroup (Semigroup (..), (<>))
26+
27+-- | A 'Group' is a 'Monoid' where every element has an inverse.
28+class (Semigroup q, Monoid q) => Group q where
29+ negateG :: q -> q
30+ (~~) :: q -> q -> q
31+ r ~~ s = r <> negateG s
32+
33+-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
34+class Semigroup q => Additive q where
35+
36+-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
37+newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
38+
39+instance Additive p => Patch (AdditivePatch p) where
40+ type PatchTarget (AdditivePatch p) = p
41+ apply (AdditivePatch p) q = Just $ p <> q
42+
43+instance (Ord k, Group q) => Group (MonoidalMap k q) where
44+ negateG = fmap negateG
45+
46+instance (Ord k, Additive q) => Additive (MonoidalMap k q)
src/Data/Patch/Class.hs → src/Reflex/Patch/Class.hsrenamed+3−14
@@ -1,23 +1,17 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE TypeFamilies #-}
1{-# LANGUAGE TypeFamilies #-}
4-- | The interface for types which represent changes made to other types
2-- | The interface for types which represent changes made to other types
5−module Data.Patch.Class where
3+module Reflex.Patch.Class where
6
4
7−import Data.Functor.Identity
5+import Control.Monad.Identity
8−import Data.Kind (Type)
9import Data.Maybe
6import Data.Maybe
10−#if !MIN_VERSION_base(4,11,0)
11import Data.Semigroup (Semigroup(..))
7import Data.Semigroup (Semigroup(..))
12−#endif
13−import Data.Proxy
14
8
15-- | A 'Patch' type represents a kind of change made to a datastructure.
9-- | A 'Patch' type represents a kind of change made to a datastructure.
16--
10--
17-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
11-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
18-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
12-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
19class Patch p where
13class Patch p where
20− type PatchTarget p :: Type
14+ type PatchTarget p :: *
21 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
15 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
22 -- 'Nothing'.
16 -- 'Nothing'.
23 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
17 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
@@ -31,11 +25,6 @@ instance Patch (Identity a) where
31 type PatchTarget (Identity a) = a
25 type PatchTarget (Identity a) = a
32 apply (Identity a) _ = Just a
26 apply (Identity a) _ = Just a
33
27
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−
39-- | Like '(.)', but composes functions that return patches rather than
28-- | Like '(.)', but composes functions that return patches rather than
40-- functions that return new values. The Semigroup instance for patches must
29-- functions that return new values. The Semigroup instance for patches must
41-- apply patches right-to-left, like '(.)'.
30-- apply patches right-to-left, like '(.)'.
src/Data/Patch/DMap.hs → src/Reflex/Patch/DMap.hsrenamed+5−16
@@ -1,4 +1,3 @@
1−{-# LANGUAGE CPP #-}
2{-# LANGUAGE GeneralizedNewtypeDeriving #-}
1{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE LambdaCase #-}
2{-# LANGUAGE LambdaCase #-}
4{-# LANGUAGE PolyKinds #-}
3{-# LANGUAGE PolyKinds #-}
@@ -6,26 +5,20 @@
6{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE ScopedTypeVariables #-}
7{-# LANGUAGE StandaloneDeriving #-}
6{-# LANGUAGE StandaloneDeriving #-}
8{-# LANGUAGE TypeFamilies #-}
7{-# LANGUAGE TypeFamilies #-}
9−
10-- | 'Patch'es on 'DMap' that consist only of insertions (or overwrites) and deletions.
8-- | 'Patch'es on 'DMap' that consist only of insertions (or overwrites) and deletions.
11−module Data.Patch.DMap where
9+module Reflex.Patch.DMap where
12
10
13−import Data.Patch.Class
11+import Reflex.Patch.Class
14−import Data.Patch.IntMap
12+import Reflex.Patch.IntMap
15−import Data.Patch.Map
13+import Reflex.Patch.Map
16
14
17−import Data.Dependent.Map (DMap)
15+import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
18−import Data.Dependent.Sum (DSum (..))
19−import Data.GADT.Compare (GCompare (..))
20import qualified Data.Dependent.Map as DMap
16import qualified Data.Dependent.Map as DMap
21import Data.Functor.Constant
17import Data.Functor.Constant
22import Data.Functor.Misc
18import Data.Functor.Misc
23import qualified Data.IntMap as IntMap
19import qualified Data.IntMap as IntMap
24import qualified Data.Map as Map
20import qualified Data.Map as Map
25−import Data.Monoid.DecidablyEmpty
26−#if !MIN_VERSION_base(4,11,0)
27import Data.Semigroup (Semigroup (..))
21import Data.Semigroup (Semigroup (..))
28−#endif
29import Data.Some (Some)
22import Data.Some (Some)
30
23
31-- | A set of changes to a 'DMap'. Any element may be inserted/updated or deleted.
24-- | A set of changes to a 'DMap'. Any element may be inserted/updated or deleted.
@@ -37,10 +30,6 @@ deriving instance GCompare k => Semigroup (PatchDMap k v)
37
30
38deriving instance GCompare k => Monoid (PatchDMap k v)
31deriving instance GCompare k => Monoid (PatchDMap k v)
39
32
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−
44-- | Apply the insertions or deletions to a given 'DMap'.
33-- | Apply the insertions or deletions to a given 'DMap'.
45instance GCompare k => Patch (PatchDMap k v) where
34instance GCompare k => Patch (PatchDMap k v) where
46 type PatchTarget (PatchDMap k v) = DMap k v
35 type PatchTarget (PatchDMap k v) = DMap k v
src/Data/Patch/DMapWithMove.hs → src/Reflex/Patch/DMapWithMove.hsrenamed+12−20
@@ -13,28 +13,24 @@
13
13
14-- |Module containing @'PatchDMapWithMove' k v@ and associated functions, which represents a 'Patch' to a @'DMap' k v@ which can insert, update, delete, and
14-- |Module containing @'PatchDMapWithMove' k v@ and associated functions, which represents a 'Patch' to a @'DMap' k v@ which can insert, update, delete, and
15-- move values between keys.
15-- move values between keys.
16−module Data.Patch.DMapWithMove where
16+module Reflex.Patch.DMapWithMove where
17
17
18−import Data.Patch.Class
18+import Reflex.Patch.Class
19−import Data.Patch.MapWithMove (PatchMapWithMove (..))
19+import Reflex.Patch.MapWithMove (PatchMapWithMove (..))
20−import qualified Data.Patch.MapWithMove as MapWithMove
20+import qualified Reflex.Patch.MapWithMove as MapWithMove
21
21
22import Data.Constraint.Extras
22import Data.Constraint.Extras
23−import Data.Dependent.Map (DMap)
23+import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
24−import Data.Dependent.Sum (DSum (..))
25import qualified Data.Dependent.Map as DMap
24import qualified Data.Dependent.Map as DMap
26import Data.Functor.Constant
25import Data.Functor.Constant
27import Data.Functor.Misc
26import Data.Functor.Misc
28import Data.Functor.Product
27import Data.Functor.Product
29−import Data.GADT.Compare (GEq (..), GCompare (..))
28+import Data.GADT.Compare (GEq (..))
30import Data.GADT.Show (GShow, gshow)
29import Data.GADT.Show (GShow, gshow)
31import qualified Data.Map as Map
30import qualified Data.Map as Map
32import Data.Maybe
31import Data.Maybe
33−import Data.Monoid.DecidablyEmpty
34−#if !MIN_VERSION_base(4,11,0)
35−import Data.Semigroup (Semigroup (..))
32+import Data.Semigroup (Semigroup (..), (<>))
36−#endif
37−import Data.Some (Some, mkSome)
33+import Data.Some (Some(Some))
38import Data.These
34import Data.These
39
35
40-- | 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
36-- | 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
@@ -46,10 +42,6 @@ import Data.These
46-- * A move should always be represented with both the destination key (as a 'From_Move') and the source key (as a @'ComposeMaybe' ('Just' destination)@)
42-- * A move should always be represented with both the destination key (as a 'From_Move') and the source key (as a @'ComposeMaybe' ('Just' destination)@)
47newtype PatchDMapWithMove k v = PatchDMapWithMove (DMap k (NodeInfo k v))
43newtype PatchDMapWithMove k v = PatchDMapWithMove (DMap k (NodeInfo k v))
48
44
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−
53-- |Structure which represents what changes apply to a particular key. @_nodeInfo_from@ specifies what happens to this key, and in particular what other key
45-- |Structure which represents what changes apply to a particular key. @_nodeInfo_from@ specifies what happens to this key, and in particular what other key
54-- the current key is moving from, while @_nodeInfo_to@ specifies what key the current key is moving to if involved in a move.
46-- the current key is moving from, while @_nodeInfo_to@ specifies what key the current key is moving to if involved in a move.
55data NodeInfo k v a = NodeInfo
47data NodeInfo k v a = NodeInfo
@@ -220,8 +212,8 @@ moveDMapKey src dst = case src `geq` dst of
220-- @
212-- @
221-- let aMay = DMap.lookup a dmap
213-- let aMay = DMap.lookup a dmap
222-- bMay = DMap.lookup b dmap
214-- bMay = DMap.lookup b dmap
223−-- in maybe id (DMap.insert a) (bMay <> aMay)
215+-- in maybe id (DMap.insert a) (bMay `mplus` aMay)
224−-- . maybe id (DMap.insert b) (aMay <> bMay)
216+-- . maybe id (DMap.insert b) (aMay `mplus` bMay)
225-- . DMap.delete a . DMap.delete b $ dmap
217-- . DMap.delete a . DMap.delete b $ dmap
226-- @
218-- @
227swapDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
219swapDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
@@ -318,8 +310,8 @@ weakenPatchDMapWithMoveWith f (PatchDMapWithMove p) = PatchMapWithMove $ weakenD
318 { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
310 { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
319 From_Insert v -> MapWithMove.From_Insert $ f v
311 From_Insert v -> MapWithMove.From_Insert $ f v
320 From_Delete -> MapWithMove.From_Delete
312 From_Delete -> MapWithMove.From_Delete
321− From_Move k -> MapWithMove.From_Move $ mkSome k
313+ From_Move k -> MapWithMove.From_Move $ Some k
322− , MapWithMove._nodeInfo_to = mkSome <$> getComposeMaybe (_nodeInfo_to ni)
314+ , MapWithMove._nodeInfo_to = Some <$> getComposeMaybe (_nodeInfo_to ni)
323 }
315 }
324
316
325-- |"Weaken" a @'PatchDMapWithMove' (Const2 k a) v@ to a @'PatchMapWithMove' k v'@. Weaken is in scare quotes because the 'Const2' has already disabled any
317-- |"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/Data/Patch/IntMap.hs → src/Reflex/Patch/IntMap.hsrenamed+21−30
@@ -1,41 +1,23 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveFoldable #-}
3+{-# LANGUAGE DeriveFunctor #-}
2{-# LANGUAGE DeriveTraversable #-}
4{-# LANGUAGE DeriveTraversable #-}
3−{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE StandaloneDeriving #-}
7−{-# LANGUAGE TemplateHaskell #-}
8{-# LANGUAGE TypeFamilies #-}
6{-# LANGUAGE TypeFamilies #-}
9−
10-- | Module containing 'PatchIntMap', a 'Patch' for 'IntMap' which allows for
7-- | Module containing 'PatchIntMap', a 'Patch' for 'IntMap' which allows for
11-- insert/update or delete of associations.
8-- insert/update or delete of associations.
12−module Data.Patch.IntMap where
9+module Reflex.Patch.IntMap where
13
10
14−import Control.Lens
15import Data.IntMap.Strict (IntMap)
11import Data.IntMap.Strict (IntMap)
16import qualified Data.IntMap.Strict as IntMap
12import qualified Data.IntMap.Strict as IntMap
17import Data.Maybe
13import Data.Maybe
18−import Data.Monoid.DecidablyEmpty
14+import Data.Semigroup
19−#if !MIN_VERSION_base(4,11,0)
20−import Data.Semigroup (Semigroup (..))
21−#endif
22−import Data.Patch.Class
15+import Reflex.Patch.Class
23
16
24-- | 'Patch' for 'IntMap' which represents insertion or deletion of keys in the mapping.
17-- | 'Patch' for 'IntMap' which represents insertion or deletion of keys in the mapping.
25-- Internally represented by 'IntMap (Maybe a)', where @Just@ means insert/update
18-- Internally represented by 'IntMap (Maybe a)', where @Just@ means insert/update
26-- and @Nothing@ means delete.
19-- and @Nothing@ means delete.
27−newtype PatchIntMap a = PatchIntMap { unPatchIntMap :: IntMap (Maybe a) }
20+newtype PatchIntMap a = PatchIntMap (IntMap (Maybe a)) deriving (Functor, Foldable, Traversable, Monoid)
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
39
21
40-- | Apply the insertions or deletions to a given 'IntMap'.
22-- | Apply the insertions or deletions to a given 'IntMap'.
41instance Patch (PatchIntMap a) where
23instance Patch (PatchIntMap a) where
@@ -45,11 +27,20 @@ instance Patch (PatchIntMap a) where
45 adds = IntMap.mapMaybe id p
27 adds = IntMap.mapMaybe id p
46 in IntMap.union adds $ v `IntMap.difference` removes
28 in IntMap.union adds $ v `IntMap.difference` removes
47
29
48−instance FunctorWithIndex Int PatchIntMap
30+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
49−instance FoldableWithIndex Int PatchIntMap
31+-- If the same key is modified by both patches, the one on the left will take
32+-- precedence.
50−instance TraversableWithIndex Int PatchIntMap where
33+instance Semigroup (PatchIntMap v) where
51− itraverse = itraversed . Indexed
34+ PatchIntMap a <> PatchIntMap b = PatchIntMap $ a `mappend` b --TODO: Add a semigroup instance for Map
52− itraversed = _Wrapped .> itraversed <. traversed
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
53
44
54-- | Map a function @Int -> a -> b@ over all @a@s in the given @'PatchIntMap' a@
45-- | Map a function @Int -> a -> b@ over all @a@s in the given @'PatchIntMap' a@
55-- (that is, all inserts/updates), producing a @PatchIntMap b@.
46-- (that is, all inserts/updates), producing a @PatchIntMap b@.
@@ -59,7 +50,7 @@ mapIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap $ IntMap.mapWithKey (\ k m
59-- | Map an effectful function @Int -> a -> f b@ over all @a@s in the given @'PatchIntMap' a@
50-- | Map an effectful function @Int -> a -> f b@ over all @a@s in the given @'PatchIntMap' a@
60-- (that is, all inserts/updates), producing a @f (PatchIntMap b)@.
51-- (that is, all inserts/updates), producing a @f (PatchIntMap b)@.
61traverseIntMapPatchWithKey :: Applicative f => (Int -> a -> f b) -> PatchIntMap a -> f (PatchIntMap b)
52traverseIntMapPatchWithKey :: Applicative f => (Int -> a -> f b) -> PatchIntMap a -> f (PatchIntMap b)
62−traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (traverse . f) m
53+traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (\k mv -> traverse (f k) mv) m
63
54
64-- | Extract all @a@s inserted/updated by the given @'PatchIntMap' a@.
55-- | Extract all @a@s inserted/updated by the given @'PatchIntMap' a@.
65patchIntMapNewElements :: PatchIntMap a -> [a]
56patchIntMapNewElements :: PatchIntMap a -> [a]
src/Data/Patch/Map.hs → src/Reflex/Patch/Map.hsrenamed+28−37
@@ -1,48 +1,22 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveTraversable #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5{-# LANGUAGE LambdaCase #-}
2{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE StandaloneDeriving #-}
8−{-# LANGUAGE TemplateHaskell #-}
9{-# LANGUAGE TypeFamilies #-}
3{-# LANGUAGE TypeFamilies #-}
10−
11-- | 'Patch'es on 'Map' that consist only of insertions (including overwrites)
4-- | 'Patch'es on 'Map' that consist only of insertions (including overwrites)
12-- and deletions
5-- and deletions
13−module Data.Patch.Map where
6+module Reflex.Patch.Map where
14
7
15−import Data.Patch.Class
8+import Reflex.Patch.Class
16
9
17−import Control.Lens
18import Data.Map (Map)
10import Data.Map (Map)
19import qualified Data.Map as Map
11import qualified Data.Map as Map
20import Data.Maybe
12import Data.Maybe
21−import Data.Monoid.DecidablyEmpty
13+import Data.Semigroup
22−import Data.Semigroup (Semigroup (..), stimesIdempotentMonoid)
23
14
24-- | A set of changes to a 'Map'. Any element may be inserted/updated or
15-- | A set of changes to a 'Map'. Any element may be inserted/updated or
25-- deleted. Insertions are represented as values wrapped in 'Just', while
16-- deleted. Insertions are represented as values wrapped in 'Just', while
26-- deletions are represented as 'Nothing's
17-- deletions are represented as 'Nothing's
27newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
18newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
28− deriving ( Show, Read, Eq, Ord
19+ 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
46
20
47-- | Apply the insertions or deletions to a given 'Map'.
21-- | Apply the insertions or deletions to a given 'Map'.
48instance Ord k => Patch (PatchMap k v) where
22instance Ord k => Patch (PatchMap k v) where
@@ -55,11 +29,30 @@ instance Ord k => Patch (PatchMap k v) where
55 Nothing -> Just ()
29 Nothing -> Just ()
56 Just _ -> Nothing
30 Just _ -> Nothing
57
31
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.
58−instance FunctorWithIndex k (PatchMap k)
35+instance Ord k => Semigroup (PatchMap k v) where
59−instance FoldableWithIndex k (PatchMap k)
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
60−instance TraversableWithIndex k (PatchMap k) where
48+instance Ord k => Monoid (PatchMap k v) where
61− itraverse = itraversed . Indexed
49+ mempty = PatchMap mempty
62− itraversed = _Wrapped .> itraversed <. traversed
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
63
56
64-- | Returns all the new elements that will be added to the 'Map'
57-- | Returns all the new elements that will be added to the 'Map'
65patchMapNewElements :: PatchMap k v -> [v]
58patchMapNewElements :: PatchMap k v -> [v]
@@ -68,5 +61,3 @@ patchMapNewElements (PatchMap p) = catMaybes $ Map.elems p
68-- | Returns all the new elements that will be added to the 'Map'
61-- | Returns all the new elements that will be added to the 'Map'
69patchMapNewElementsMap :: PatchMap k v -> Map k v
62patchMapNewElementsMap :: PatchMap k v -> Map k v
70patchMapNewElementsMap (PatchMap p) = Map.mapMaybe id p
63patchMapNewElementsMap (PatchMap p) = Map.mapMaybe id p
71−
72−makeWrapped ''PatchMap
src/Reflex/Patch/MapWithMove.hsnew file+270
@@ -0,0 +1,270 @@
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/PerformEvent/Base.hsnew file+179
@@ -0,0 +1,179 @@
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.hsnew file+64
@@ -0,0 +1,64 @@
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.hsnew file+197
@@ -0,0 +1,197 @@
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.hsnew file+42
@@ -0,0 +1,42 @@
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.hsnew file+223
@@ -0,0 +1,223 @@
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+{-# LANGUAGE PolyKinds #-}
12+{-# LANGUAGE RankNTypes #-}
13+-- |
14+-- Module:
15+-- Reflex.Profiled
16+-- Description:
17+-- This module contains an instance of the 'Reflex' class that provides
18+-- profiling/cost-center information.
19+module Reflex.Profiled where
20+
21+import Control.Monad
22+import Control.Monad.Exception
23+import Control.Monad.Fix
24+import Control.Monad.Primitive
25+import Control.Monad.Reader
26+import Control.Monad.Ref
27+import Control.Monad.State.Strict (StateT, execStateT, modify)
28+import Data.Coerce
29+import Data.Dependent.Map (DMap, GCompare)
30+import Data.FastMutableIntMap
31+import Data.IORef
32+import Data.List
33+import Data.Map (Map)
34+import qualified Data.Map.Strict as Map
35+import Data.Monoid ((<>))
36+import Data.Ord
37+import Data.Profunctor.Unsafe ((#.))
38+import qualified Data.Semigroup as S
39+import Data.Type.Coercion
40+import Foreign.Ptr
41+import GHC.Foreign
42+import GHC.IO.Encoding
43+import GHC.Stack
44+import Reflex.Class
45+import Reflex.Host.Class
46+import Reflex.PerformEvent.Class
47+
48+import System.IO.Unsafe
49+import Unsafe.Coerce
50+
51+data ProfiledTimeline t
52+
53+{-# NOINLINE profilingData #-}
54+profilingData :: IORef (Map (Ptr CostCentreStack) Int)
55+profilingData = unsafePerformIO $ newIORef Map.empty
56+
57+data CostCentreTree = CostCentreTree
58+ { _costCentreTree_ownEntries :: !Int
59+ , _costCentreTree_cumulativeEntries :: !Int
60+ , _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
61+ }
62+ deriving (Show, Eq, Ord)
63+
64+instance S.Semigroup CostCentreTree where
65+ (CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
66+ CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
67+
68+instance Monoid CostCentreTree where
69+ mempty = CostCentreTree 0 0 mempty
70+ mappend = (S.<>)
71+
72+getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
73+getCostCentreStack = go []
74+ where go l ccs = if ccs == nullPtr
75+ then return l
76+ else do
77+ cc <- ccsCC ccs
78+ parent <- ccsParent ccs
79+ go (cc : l) parent
80+
81+toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
82+toCostCentreTree ccs n = do
83+ ccList <- getCostCentreStack ccs
84+ return $ foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty) ccList
85+
86+getCostCentreTree :: IO CostCentreTree
87+getCostCentreTree = do
88+ vals <- readIORef profilingData
89+ mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
90+
91+formatCostCentreTree :: CostCentreTree -> IO String
92+formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
93+ where go :: Int -> CostCentreTree -> StateT [String] IO ()
94+ go depth cct = do
95+ let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
96+ indent = mconcat $ replicate depth " "
97+ forM_ children $ \(cc, childCct) -> do
98+ lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
99+ mdl <- liftIO $ peekCString utf8 =<< ccModule cc
100+ loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
101+ let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
102+ modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
103+ go (succ depth) childCct
104+
105+showProfilingData :: IO ()
106+showProfilingData = do
107+ putStr =<< formatCostCentreTree =<< getCostCentreTree
108+
109+writeProfilingData :: FilePath -> IO ()
110+writeProfilingData p = do
111+ writeFile p =<< formatCostCentreTree =<< getCostCentreTree
112+
113+newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
114+ deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
115+
116+profileEvent :: Reflex t => Event t a -> Event t a
117+profileEvent e = unsafePerformIO $ do
118+ stack <- getCurrentCCS e
119+ let f x = unsafePerformIO $ do
120+ modifyIORef' profilingData $ Map.insertWith (+) stack 1
121+ return $ return $ Just x
122+ return $ pushCheap f e
123+
124+--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
125+
126+instance Reflex t => Reflex (ProfiledTimeline t) where
127+ newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
128+ newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
129+ newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
130+ newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
131+ type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
132+ type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
133+ never = Event_Profiled never
134+ constant = Behavior_Profiled . constant
135+ push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
136+ pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
137+ pull = Behavior_Profiled . pull . coerce
138+ mergeG :: forall (k :: z -> *) q v. GCompare k
139+ => (forall a. q a -> Event (ProfiledTimeline t) (v a))
140+ -> DMap k q -> Event (ProfiledTimeline t) (DMap k v)
141+ mergeG nt = Event_Profiled #. mergeG (coerce nt)
142+ fan (Event_Profiled e) = EventSelector $ coerce $ select (fan $ profileEvent e)
143+ switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
144+ coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
145+ current (Dynamic_Profiled d) = coerce $ current d
146+ updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
147+ unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
148+ unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
149+ mergeIncrementalG nt = (Event_Profiled . coerce) #. mergeIncrementalG nt
150+ mergeIncrementalWithMoveG nt = (Event_Profiled . coerce) #. mergeIncrementalWithMoveG nt
151+ currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
152+ updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
153+ incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
154+ behaviorCoercion (c :: Coercion a b) = case behaviorCoercion c :: Coercion (Behavior t a) (Behavior t b) of
155+ Coercion -> unsafeCoerce (Coercion :: Coercion (Behavior (ProfiledTimeline t) a) (Behavior (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
156+ eventCoercion (c :: Coercion a b) = case eventCoercion c :: Coercion (Event t a) (Event t b) of
157+ Coercion -> unsafeCoerce (Coercion :: Coercion (Event (ProfiledTimeline t) a) (Event (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
158+ dynamicCoercion (c :: Coercion a b) = case dynamicCoercion c :: Coercion (Dynamic t a) (Dynamic t b) of
159+ Coercion -> unsafeCoerce (Coercion :: Coercion (Dynamic (ProfiledTimeline t) a) (Dynamic (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
160+ mergeIntIncremental = Event_Profiled . mergeIntIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchIntMap (Event (ProfiledTimeline t) a)) -> Incremental t (PatchIntMap (Event t a)))
161+ fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
162+
163+deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
164+deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
165+deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
166+
167+instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
168+ hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
169+ holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
170+ holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
171+ buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
172+ headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
173+
174+instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
175+ sample (Behavior_Profiled b) = ProfiledM $ sample b
176+
177+instance MonadTrans ProfiledM where
178+ lift = ProfiledM
179+
180+instance MonadIO m => MonadIO (ProfiledM m) where
181+ liftIO = lift . liftIO
182+
183+instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
184+ type Performable (ProfiledM m) = Performable m
185+ performEvent_ = lift . performEvent_ . coerce
186+ performEvent = lift . fmap coerce . performEvent . coerce
187+
188+instance MonadRef m => MonadRef (ProfiledM m) where
189+ type Ref (ProfiledM m) = Ref m
190+ newRef = lift . newRef
191+ readRef = lift . readRef
192+ writeRef r = lift . writeRef r
193+
194+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
195+ newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
196+ newFanEventWithTrigger f = do
197+ es <- lift $ newFanEventWithTrigger f
198+ return $ EventSelector $ \k -> coerce $ select es k
199+
200+instance MonadReader r m => MonadReader r (ProfiledM m) where
201+ ask = lift ask
202+ local f (ProfiledM a) = ProfiledM $ local f a
203+ reader = lift . reader
204+
205+instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
206+ type EventTrigger (ProfiledTimeline t) = EventTrigger t
207+ type EventHandle (ProfiledTimeline t) = EventHandle t
208+ type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
209+
210+instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
211+ subscribeEvent = lift . subscribeEvent . coerce
212+
213+instance PrimMonad m => PrimMonad (ProfiledM m) where
214+ type PrimState (ProfiledM m) = PrimState m
215+ primitive = lift . primitive
216+
217+instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
218+ type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
219+ fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
220+ runHostFrame = lift . runHostFrame . coerce
221+
222+instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
223+ readEvent = lift . fmap coerce . readEvent
src/Reflex/Pure.hsnew file+214
@@ -0,0 +1,214 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE EmptyDataDecls #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE InstanceSigs #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE TypeFamilies #-}
8+{-# LANGUAGE RankNTypes #-}
9+{-# LANGUAGE PolyKinds #-}
10+#ifdef USE_REFLEX_OPTIMIZER
11+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12+#endif
13+
14+-- There are two expected orphan instances in this module:
15+-- * MonadSample (Pure t) ((->) t)
16+-- * MonadHold (Pure t) ((->) t)
17+{-# OPTIONS_GHC -fno-warn-orphans #-}
18+-- |
19+-- Module: Reflex.Pure
20+-- Description:
21+-- This module provides a pure implementation of Reflex, which is intended to
22+-- serve as a reference for the semantics of the Reflex class. All
23+-- implementations of Reflex should produce the same results as this
24+-- implementation, although performance and laziness/strictness may differ.
25+module Reflex.Pure
26+ ( Pure
27+ , Behavior (..)
28+ , Event (..)
29+ , Dynamic (..)
30+ , Incremental (..)
31+ ) where
32+
33+#if !MIN_VERSION_base(4,8,0)
34+import Control.Applicative
35+#endif
36+
37+import Control.Monad
38+import Data.Dependent.Map (DMap, GCompare)
39+import qualified Data.Dependent.Map as DMap
40+import Data.Functor.Identity
41+import Data.IntMap (IntMap)
42+import qualified Data.IntMap as IntMap
43+import Data.Maybe
44+import Data.MemoTrie
45+import Data.Monoid
46+import Data.Type.Coercion
47+import Reflex.Class
48+import Data.Kind (Type)
49+
50+-- | A completely pure-functional 'Reflex' timeline, identifying moments in time
51+-- with the type @/t/@.
52+data Pure (t :: Type)
53+
54+-- | The 'Enum' instance of @/t/@ must be dense: for all @/x :: t/@, there must not exist
55+-- any @/y :: t/@ such that @/'pred' x < y < x/@. The 'HasTrie' instance will be used
56+-- exclusively to memoize functions of @/t/@, not for any of its other capabilities.
57+instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where
58+
59+ newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }
60+ newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }
61+ newtype Dynamic (Pure t) a = Dynamic { unDynamic :: t -> (a, Maybe a) }
62+ newtype Incremental (Pure t) p = Incremental { unIncremental :: t -> (PatchTarget p, Maybe p) }
63+
64+ type PushM (Pure t) = (->) t
65+ type PullM (Pure t) = (->) t
66+
67+ never :: Event (Pure t) a
68+ never = Event $ \_ -> Nothing
69+
70+ constant :: a -> Behavior (Pure t) a
71+ constant x = Behavior $ \_ -> x
72+
73+ push :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
74+ push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t
75+
76+ pushCheap :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
77+ pushCheap = push
78+
79+ pull :: PullM (Pure t) a -> Behavior (Pure t) a
80+ pull = Behavior . memo
81+
82+ -- [UNUSED_CONSTRAINT]: The following type signature for merge will produce a
83+ -- warning because the GCompare instance is not used; however, removing the
84+ -- GCompare instance produces a different warning, due to that constraint
85+ -- being present in the original class definition.
86+
87+ --mergeG :: GCompare k => (forall a. q a -> Event (Pure t) (v a))
88+ -- -> DMap k q -> Event (Pure t) (DMap k v)
89+ mergeG nt events = Event $ memo $ \t ->
90+ let currentOccurrences = DMap.mapMaybeWithKey (\_ q -> case nt q of Event a -> a t) events
91+ in if DMap.null currentOccurrences
92+ then Nothing
93+ else Just currentOccurrences
94+
95+ fan :: GCompare k => Event (Pure t) (DMap k Identity) -> EventSelector (Pure t) k
96+ fan e = EventSelector $ \k -> Event $ \t -> unEvent e t >>= fmap runIdentity . DMap.lookup k
97+
98+ switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a
99+ switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
100+
101+ coincidence :: Event (Pure t) (Event (Pure t) a) -> Event (Pure t) a
102+ coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
103+
104+ current :: Dynamic (Pure t) a -> Behavior (Pure t) a
105+ current d = Behavior $ \t -> fst $ unDynamic d t
106+
107+ updated :: Dynamic (Pure t) a -> Event (Pure t) a
108+ updated d = Event $ \t -> snd $ unDynamic d t
109+
110+ unsafeBuildDynamic :: PullM (Pure t) a -> Event (Pure t) a -> Dynamic (Pure t) a
111+ unsafeBuildDynamic readV0 v' = Dynamic $ \t -> (readV0 t, unEvent v' t)
112+
113+ -- See UNUSED_CONSTRAINT, above.
114+
115+ --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p
116+ --a) -> Incremental (Pure t) p a
117+ unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)
118+
119+ mergeIncrementalG = mergeIncrementalImpl
120+ mergeIncrementalWithMoveG = mergeIncrementalImpl
121+
122+ currentIncremental i = Behavior $ \t -> fst $ unIncremental i t
123+
124+ updatedIncremental i = Event $ \t -> snd $ unIncremental i t
125+
126+ incrementalToDynamic i = Dynamic $ \t ->
127+ let (old, mPatch) = unIncremental i t
128+ e = case mPatch of
129+ Nothing -> Nothing
130+ Just patch -> apply patch old
131+ in (old, e)
132+ behaviorCoercion Coercion = Coercion
133+ eventCoercion Coercion = Coercion
134+ dynamicCoercion Coercion = Coercion
135+
136+ fanInt e = EventSelectorInt $ \k -> Event $ \t -> unEvent e t >>= IntMap.lookup k
137+
138+ mergeIntIncremental = mergeIntIncrementalImpl
139+
140+mergeIncrementalImpl :: (PatchTarget p ~ DMap k q, GCompare k)
141+ => (forall a. q a -> Event (Pure t) (v a))
142+ -> Incremental (Pure t) p -> Event (Pure t) (DMap k v)
143+mergeIncrementalImpl nt i = Event $ \t ->
144+ let results = DMap.mapMaybeWithKey (\_ q -> case nt q of Event e -> e t) $ fst $ unIncremental i t
145+ in if DMap.null results
146+ then Nothing
147+ else Just results
148+
149+mergeIntIncrementalImpl :: (PatchTarget p ~ IntMap (Event (Pure t) a)) => Incremental (Pure t) p -> Event (Pure t) (IntMap a)
150+mergeIntIncrementalImpl i = Event $ \t ->
151+ let results = IntMap.mapMaybeWithKey (\_ (Event e) -> e t) $ fst $ unIncremental i t
152+ in if IntMap.null results
153+ then Nothing
154+ else Just results
155+
156+instance Functor (Dynamic (Pure t)) where
157+ fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t
158+ in (f cur, fmap f upd)
159+
160+instance Applicative (Dynamic (Pure t)) where
161+ pure a = Dynamic $ \_ -> (a, Nothing)
162+ (<*>) = ap
163+
164+instance Monad (Dynamic (Pure t)) where
165+ return = pure
166+ (x :: Dynamic (Pure t) a) >>= (f :: a -> Dynamic (Pure t) b) = Dynamic $ \t ->
167+ let (curX :: a, updX :: Maybe a) = unDynamic x t
168+ (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t
169+ (updInner :: Maybe b, updBoth :: Maybe b) = case updX of
170+ Nothing -> (Nothing, Nothing)
171+ Just nextX -> let (c, u) = unDynamic (f nextX) t
172+ in (Just c, u)
173+ in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])
174+
175+instance MonadSample (Pure t) ((->) t) where
176+
177+ sample :: Behavior (Pure t) a -> (t -> a)
178+ sample = unBehavior
179+
180+instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
181+
182+ hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a
183+ hold initialValue e initialTime = Behavior f
184+ where f = memo $ \sampleTime ->
185+ -- Really, the sampleTime should never be prior to the initialTime,
186+ -- because that would mean the Behavior is being sampled before
187+ -- being created.
188+ if sampleTime <= initialTime
189+ then initialValue
190+ else let lastTime = pred sampleTime
191+ in fromMaybe (f lastTime) $ unEvent e lastTime
192+
193+ holdDyn v0 = buildDynamic (return v0)
194+
195+ buildDynamic :: (t -> a) -> Event (Pure t) a -> t -> Dynamic (Pure t) a
196+ buildDynamic initialValue e initialTime =
197+ let Behavior f = hold (initialValue initialTime) e initialTime
198+ in Dynamic $ \t -> (f t, unEvent e t)
199+
200+ holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p
201+ holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)
202+ where f = memo $ \sampleTime ->
203+ -- Really, the sampleTime should never be prior to the initialTime,
204+ -- because that would mean the Behavior is being sampled before
205+ -- being created.
206+ if sampleTime <= initialTime
207+ then initialValue
208+ else let lastTime = pred sampleTime
209+ lastValue = f lastTime
210+ in case unEvent e lastTime of
211+ Nothing -> lastValue
212+ Just x -> fromMaybe lastValue $ apply x lastValue
213+
214+ headE = slowHeadE
src/Reflex/Query/Base.hsnew file+336
@@ -0,0 +1,336 @@
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+ ) where
21+
22+import Control.Applicative (liftA2)
23+import Control.Monad.Exception
24+import Control.Monad.Fix
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, DSum (..))
31+import qualified Data.Dependent.Map as DMap
32+import Data.Foldable
33+import Data.Functor.Compose
34+import Data.Functor.Misc
35+import Data.IntMap (IntMap)
36+import qualified Data.IntMap as IntMap
37+import Data.Map (Map)
38+import qualified Data.Map as Map
39+import Data.Monoid ((<>))
40+import qualified Data.Semigroup as S
41+import Data.Some (Some(Some))
42+import Data.These
43+
44+import Reflex.Class
45+import Reflex.Adjustable.Class
46+import Reflex.DynamicWriter.Class
47+import Reflex.EventWriter.Base
48+import Reflex.EventWriter.Class
49+import Reflex.Host.Class
50+import qualified Reflex.Patch.MapWithMove as MapWithMove
51+import Reflex.PerformEvent.Class
52+import Reflex.PostBuild.Class
53+import Reflex.Query.Class
54+import Reflex.Requester.Class
55+import Reflex.TriggerEvent.Class
56+
57+newtype QueryT t q m a = QueryT { unQueryT :: StateT [Behavior t q] (EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m)) a }
58+ deriving (Functor, Applicative, Monad, MonadException, MonadFix, MonadIO, MonadAtomicRef)
59+
60+deriving instance MonadHold t m => MonadHold t (QueryT t q m)
61+deriving instance MonadSample t m => MonadSample t (QueryT t q m)
62+
63+runQueryT :: (MonadFix m, Additive q, Group q, Reflex t) => QueryT t q m a -> Dynamic t (QueryResult q) -> m (a, Incremental t (AdditivePatch q))
64+runQueryT (QueryT a) qr = do
65+ ((r, bs), es) <- runReaderT (runEventWriterT (runStateT a mempty)) qr
66+ return (r, unsafeBuildIncremental (foldlM (\b c -> (b <>) <$> sample c) mempty bs) (fmapCheap AdditivePatch es))
67+
68+newtype QueryTLoweredResult t q v = QueryTLoweredResult (v, [Behavior t q])
69+
70+getQueryTLoweredResultValue :: QueryTLoweredResult t q v -> v
71+getQueryTLoweredResultValue (QueryTLoweredResult (v, _)) = v
72+
73+getQueryTLoweredResultWritten :: QueryTLoweredResult t q v -> [Behavior t q]
74+getQueryTLoweredResultWritten (QueryTLoweredResult (_, w)) = w
75+
76+maskMempty :: (Eq a, Monoid a) => a -> Maybe a
77+maskMempty x = if x == mempty then Nothing else Just x
78+
79+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
80+ runWithReplace (QueryT a0) a' = do
81+ ((r0, bs0), r') <- QueryT $ lift $ runWithReplace (runStateT a0 []) $ fmapCheap (flip runStateT [] . unQueryT) a'
82+ let sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
83+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
84+ bs' = fmapCheap snd $ r'
85+ bbs <- hold bs0 bs'
86+ let patches = flip pushCheap bs' $ \newBs -> do
87+ oldBs <- sample bbs
88+ maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
89+ QueryT $ modify $ (:) $ pull $ sampleBs =<< sample bbs
90+ QueryT $ lift $ tellEvent patches
91+ return (r0, fmapCheap fst r')
92+
93+ 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'))
94+ traverseIntMapWithKeyWithAdjust f im0 im' = do
95+ let f' :: IntMap.Key -> v -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (QueryTLoweredResult t q v')
96+ f' k v = fmap QueryTLoweredResult $ flip runStateT [] $ unQueryT $ f k v
97+ (result0, result') <- QueryT $ lift $ traverseIntMapWithKeyWithAdjust f' im0 im'
98+ let liftedResult0 = IntMap.map getQueryTLoweredResultValue result0
99+ liftedResult' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
100+ IntMap.map (fmap getQueryTLoweredResultValue) p
101+ liftedBs0 :: IntMap [Behavior t q]
102+ liftedBs0 = IntMap.map getQueryTLoweredResultWritten result0
103+ liftedBs' :: Event t (PatchIntMap [Behavior t q])
104+ liftedBs' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
105+ IntMap.map (fmap getQueryTLoweredResultWritten) p
106+ sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
107+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
108+ accumBehaviors :: forall m'. MonadHold t m'
109+ => IntMap [Behavior t q]
110+ -> PatchIntMap [Behavior t q]
111+ -> m' ( Maybe (IntMap [Behavior t q])
112+ , Maybe (AdditivePatch q))
113+ -- f accumulates the child behavior state we receive from running traverseIntMapWithKeyWithAdjust for the underlying monad.
114+ -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
115+ -- bs0 is a Map denoting the behaviors of the current children.
116+ -- pbs is a PatchMap denoting an update to the behaviors of the current children
117+ accumBehaviors bs0 pbs@(PatchIntMap bs') = do
118+ let p k bs = case IntMap.lookup k bs0 of
119+ Nothing -> case bs of
120+ -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
121+ Nothing -> return mempty
122+ -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
123+ Just newBs -> sampleBs newBs
124+ Just oldBs -> case bs of
125+ -- 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
126+ Nothing -> negateG <$> sampleBs oldBs
127+ -- 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
128+ -- composed with the sampling the child's new state.
129+ Just newBs -> (~~) <$> sampleBs newBs <*> sampleBs oldBs
130+ -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
131+ -- child patches and wrap them in AdditivePatch.
132+ patch <- AdditivePatch . fold <$> IntMap.traverseWithKey p bs'
133+ return (apply pbs bs0, Just patch)
134+ (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
135+ tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
136+ return (liftedResult0, liftedResult')
137+
138+ 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'))
139+ traverseDMapWithKeyWithAdjust f dm0 dm' = do
140+ let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
141+ f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
142+ (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjust f' dm0 dm'
143+ let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
144+ liftedResult' = fforCheap result' $ \(PatchDMap p) -> PatchDMap $
145+ mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (getQueryTLoweredResultValue . getCompose) mr)) p
146+ liftedBs0 :: Map (Some k) [Behavior t q]
147+ liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
148+ liftedBs' :: Event t (PatchMap (Some k) [Behavior t q])
149+ liftedBs' = fforCheap result' $ \(PatchDMap p) -> PatchMap $
150+ Map.fromDistinctAscList $ (\(k :=> ComposeMaybe mr) -> (Some k, fmap (getQueryTLoweredResultWritten . getCompose) mr)) <$> DMap.toList p
151+ sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
152+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
153+ accumBehaviors :: forall m'. MonadHold t m'
154+ => Map (Some k) [Behavior t q]
155+ -> PatchMap (Some k) [Behavior t q]
156+ -> m' ( Maybe (Map (Some k) [Behavior t q])
157+ , Maybe (AdditivePatch q))
158+ -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjust for the underlying monad.
159+ -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
160+ -- bs0 is a Map denoting the behaviors of the current children.
161+ -- pbs is a PatchMap denoting an update to the behaviors of the current children
162+ accumBehaviors bs0 pbs@(PatchMap bs') = do
163+ let p k bs = case Map.lookup k bs0 of
164+ Nothing -> case bs of
165+ -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
166+ Nothing -> return Nothing
167+ -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
168+ Just newBs -> maskMempty <$> sampleBs newBs
169+ Just oldBs -> case bs of
170+ -- 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
171+ Nothing -> maskMempty . negateG <$> sampleBs oldBs
172+ -- 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
173+ -- composed with the sampling the child's new state.
174+ Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
175+ -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
176+ -- child patches and wrap them in AdditivePatch.
177+ patch <- fold <$> Map.traverseWithKey p bs'
178+ return (apply pbs bs0, AdditivePatch <$> patch)
179+ (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
180+ tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
181+ return (liftedResult0, liftedResult')
182+
183+ 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'))
184+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
185+ let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
186+ f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
187+ (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjustWithMove f' dm0 dm'
188+ let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
189+ liftedResult' = fforCheap result' $ mapPatchDMapWithMove (getQueryTLoweredResultValue . getCompose)
190+ liftedBs0 :: Map (Some k) [Behavior t q]
191+ liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
192+ liftedBs' :: Event t (PatchMapWithMove (Some k) [Behavior t q])
193+ liftedBs' = fforCheap result' $ weakenPatchDMapWithMoveWith (getQueryTLoweredResultWritten . getCompose) {- \(PatchDMap p) -> PatchMapWithMove $
194+ Map.fromDistinctAscList $ (\(k :=> mr) -> (Some k, fmap (fmap (getQueryTLoweredResultWritten . getCompose)) mr)) <$> DMap.toList p -}
195+ sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
196+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
197+ accumBehaviors' :: forall m'. MonadHold t m'
198+ => Map (Some k) [Behavior t q]
199+ -> PatchMapWithMove (Some k) [Behavior t q]
200+ -> m' ( Maybe (Map (Some k) [Behavior t q])
201+ , Maybe (AdditivePatch q))
202+ -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjustWithMove for the underlying monad.
203+ -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
204+ -- bs0 is a Map denoting the behaviors of the current children.
205+ -- pbs is a PatchMapWithMove denoting an update to the behaviors of the current children
206+ accumBehaviors' bs0 pbs = do
207+ let bs' = unPatchMapWithMove pbs
208+ p k bs = case Map.lookup k bs0 of
209+ Nothing -> case MapWithMove._nodeInfo_from bs of
210+ -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
211+ MapWithMove.From_Delete -> return Nothing
212+ -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
213+ MapWithMove.From_Insert newBs -> maskMempty <$> sampleBs newBs
214+ MapWithMove.From_Move k' -> case Map.lookup k' bs0 of
215+ Nothing -> return Nothing
216+ Just newBs -> maskMempty <$> sampleBs newBs
217+ Just oldBs -> case MapWithMove._nodeInfo_from bs of
218+ -- 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
219+ MapWithMove.From_Delete -> maskMempty . negateG <$> sampleBs oldBs
220+ -- 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
221+ -- composed with the sampling the child's new state.
222+ MapWithMove.From_Insert newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
223+ MapWithMove.From_Move k'
224+ | k' == k -> return Nothing
225+ | otherwise -> case Map.lookup k' bs0 of
226+ -- If we are moving from a non-existent key, that is a delete
227+ Nothing -> maskMempty . negateG <$> sampleBs oldBs
228+ Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
229+ -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
230+ -- child patches and wrap them in AdditivePatch.
231+ patch <- fold <$> Map.traverseWithKey p bs'
232+ return (apply pbs bs0, AdditivePatch <$> patch)
233+ (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors' liftedBs0 liftedBs'
234+ tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
235+ return (liftedResult0, liftedResult')
236+
237+instance MonadTrans (QueryT t q) where
238+ lift = QueryT . lift . lift . lift
239+
240+instance PrimMonad m => PrimMonad (QueryT t q m) where
241+ type PrimState (QueryT t q m) = PrimState m
242+ primitive = lift . primitive
243+
244+instance PostBuild t m => PostBuild t (QueryT t q m) where
245+ getPostBuild = lift getPostBuild
246+
247+instance (MonadAsyncException m) => MonadAsyncException (QueryT t q m) where
248+ mask f = QueryT $ mask $ \unMask -> unQueryT $ f $ QueryT . unMask . unQueryT
249+
250+instance TriggerEvent t m => TriggerEvent t (QueryT t q m) where
251+ newTriggerEvent = lift newTriggerEvent
252+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
253+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
254+
255+instance PerformEvent t m => PerformEvent t (QueryT t q m) where
256+ type Performable (QueryT t q m) = Performable m
257+ performEvent_ = lift . performEvent_
258+ performEvent = lift . performEvent
259+
260+instance MonadRef m => MonadRef (QueryT t q m) where
261+ type Ref (QueryT t q m) = Ref m
262+ newRef = QueryT . newRef
263+ readRef = QueryT . readRef
264+ writeRef r = QueryT . writeRef r
265+
266+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (QueryT t q m) where
267+ newEventWithTrigger = QueryT . newEventWithTrigger
268+ newFanEventWithTrigger a = QueryT . lift $ newFanEventWithTrigger a
269+
270+-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
271+instance (Monoid a, Monad m) => Monoid (QueryT t q m a) where
272+ mempty = pure mempty
273+ mappend = (<>)
274+
275+instance (S.Semigroup a, Monad m) => S.Semigroup (QueryT t q m a) where
276+ (<>) = liftA2 (S.<>)
277+
278+-- | withQueryT's QueryMorphism argument needs to be a group homomorphism in order to behave correctly
279+withQueryT :: (MonadFix m, PostBuild t m, Group q, Group q', Additive q, Additive q', Query q')
280+ => QueryMorphism q q'
281+ -> QueryT t q m a
282+ -> QueryT t q' m a
283+withQueryT f a = do
284+ r' <- askQueryResult
285+ (result, q) <- lift $ runQueryT a $ mapQueryResult f <$> r'
286+ tellQueryIncremental $ unsafeBuildIncremental
287+ (fmap (mapQuery f) (sample (currentIncremental q)))
288+ (fmapCheap (AdditivePatch . mapQuery f . unAdditivePatch) $ updatedIncremental q)
289+ return result
290+
291+-- | dynWithQueryT's (Dynamic t QueryMorphism) argument needs to be a group homomorphism at all times in order to behave correctly
292+dynWithQueryT :: (MonadFix m, PostBuild t m, Group q, Additive q, Group q', Additive q', Query q')
293+ => Dynamic t (QueryMorphism q q')
294+ -> QueryT t q m a
295+ -> QueryT t q' m a
296+dynWithQueryT f q = do
297+ r' <- askQueryResult
298+ (result, q') <- lift $ runQueryT q $ zipDynWith mapQueryResult f r'
299+ tellQueryIncremental $ zipDynIncrementalWith mapQuery f q'
300+ return result
301+ where zipDynIncrementalWith g da ib =
302+ let eab = align (updated da) (updatedIncremental ib)
303+ ec = flip push eab $ \case
304+ This a -> do
305+ aOld <- sample $ current da
306+ b <- sample $ currentIncremental ib
307+ return $ Just $ AdditivePatch (g a b ~~ g aOld b)
308+ That (AdditivePatch b) -> do
309+ a <- sample $ current da
310+ return $ Just $ AdditivePatch $ g a b
311+ These a (AdditivePatch b) -> do
312+ aOld <- sample $ current da
313+ bOld <- sample $ currentIncremental ib
314+ return $ Just $ AdditivePatch $ mconcat [ g a bOld, negateG (g aOld bOld), g a b]
315+ in unsafeBuildIncremental (g <$> sample (current da) <*> sample (currentIncremental ib)) ec
316+
317+instance (Monad m, Group q, Additive q, Query q, Reflex t) => MonadQuery t q (QueryT t q m) where
318+ tellQueryIncremental q = do
319+ QueryT (modify (currentIncremental q:))
320+ QueryT (lift (tellEvent (fmapCheap unAdditivePatch (updatedIncremental q))))
321+ askQueryResult = QueryT ask
322+ queryIncremental q = do
323+ tellQueryIncremental q
324+ zipDynWith crop (incrementalToDynamic q) <$> askQueryResult
325+
326+instance Requester t m => Requester t (QueryT t q m) where
327+ type Request (QueryT t q m) = Request m
328+ type Response (QueryT t q m) = Response m
329+ requesting = lift . requesting
330+ requesting_ = lift . requesting_
331+
332+instance EventWriter t w m => EventWriter t w (QueryT t q m) where
333+ tellEvent = lift . tellEvent
334+
335+instance DynamicWriter t w m => DynamicWriter t w (QueryT t q m) where
336+ tellDyn = lift . tellDyn
src/Reflex/Query/Class.hsnew file+119
@@ -0,0 +1,119 @@
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.hsnew file+537
@@ -0,0 +1,537 @@
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(Some))
70+import Data.Type.Equality
71+import Data.Unique.Tag
72+
73+import GHC.Exts (Any)
74+import Unsafe.Coerce
75+
76+--TODO: Make this module type-safe
77+
78+newtype TagMap (f :: * -> *) = TagMap (IntMap Any)
79+
80+newtype RequesterData f = RequesterData (TagMap (Entry f))
81+
82+data RequesterDataKey a where
83+ RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a
84+ 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
85+ RequesterDataKey_Multi2 :: {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
86+ RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
87+
88+singletonRequesterData :: RequesterDataKey a -> f a -> RequesterData f
89+singletonRequesterData rdk v = case rdk of
90+ RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v
91+ RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v
92+ RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
93+ RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
94+
95+requesterDataToList :: RequesterData f -> [DSum RequesterDataKey f]
96+requesterDataToList (RequesterData m) = do
97+ k :=> Entry e <- tagMapToList m
98+ case myKeyType k of
99+ MyTagType_Single -> return $ RequesterDataKey_Single k :=> e
100+ MyTagType_Multi -> do
101+ (k', e') <- IntMap.toList e
102+ k'' :=> e'' <- requesterDataToList e'
103+ return $ RequesterDataKey_Multi k k' k'' :=> e''
104+ MyTagType_Multi2 -> do
105+ (k', e') <- Map.toList e
106+ (k'', e'') <- IntMap.toList e'
107+ k''' :=> e''' <- requesterDataToList e''
108+ return $ RequesterDataKey_Multi2 k k' k'' k''' :=> e'''
109+ MyTagType_Multi3 -> do
110+ (k', e') <- IntMap.toList e
111+ (k'', e'') <- IntMap.toList e'
112+ k''' :=> e''' <- requesterDataToList e''
113+ return $ RequesterDataKey_Multi3 k k' k'' k''' :=> e'''
114+
115+singletonTagMap :: forall f a. MyTag a -> f a -> TagMap f
116+singletonTagMap (MyTag k) v = TagMap $ IntMap.singleton k $ (unsafeCoerce :: f a -> Any) v
117+
118+tagMapToList :: forall f. TagMap f -> [DSum MyTag f]
119+tagMapToList (TagMap m) = f <$> IntMap.toList m
120+ where f :: (Int, Any) -> DSum MyTag f
121+ f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v
122+
123+traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g)
124+traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m
125+ where
126+ g :: Int -> Any -> t Any
127+ g k v = (unsafeCoerce :: g a -> Any) <$> f (MyTag k) ((unsafeCoerce :: Any -> f a) v)
128+
129+-- | Runs in reverse to accommodate for the fact that we accumulate it in reverse
130+traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response)
131+traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order
132+ where go :: forall x. MyTag x -> Entry request x -> m (Entry response x)
133+ go k (Entry request) = Entry <$> case myKeyType k of
134+ MyTagType_Single -> f request
135+ MyTagType_Multi -> traverse (traverseRequesterData f) request
136+ MyTagType_Multi2 -> traverse (traverse (traverseRequesterData f)) request
137+ MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request
138+
139+-- | 'traverseRequesterData' with its arguments flipped
140+forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response)
141+forRequesterData r f = traverseRequesterData f r
142+
143+data MyTagType :: * -> * where
144+ MyTagType_Single :: MyTagType (Single a)
145+ MyTagType_Multi :: MyTagType Multi
146+ MyTagType_Multi2 :: MyTagType (Multi2 k)
147+ MyTagType_Multi3 :: MyTagType Multi3
148+
149+myKeyType :: MyTag x -> MyTagType x
150+myKeyType (MyTag k) = case k .&. 0x3 of
151+ 0x0 -> unsafeCoerce MyTagType_Single
152+ 0x1 -> unsafeCoerce MyTagType_Multi
153+ 0x2 -> unsafeCoerce MyTagType_Multi2
154+ 0x3 -> unsafeCoerce MyTagType_Multi3
155+ t -> error $ "Reflex.Requester.Base.myKeyType: no such key type" <> show t
156+
157+data Single a
158+data Multi
159+data Multi2 (k :: * -> *)
160+data Multi3
161+
162+class MyTagTypeOffset x where
163+ myTagTypeOffset :: proxy x -> Int
164+
165+instance MyTagTypeOffset (Single a) where
166+ myTagTypeOffset _ = 0x0
167+
168+instance MyTagTypeOffset Multi where
169+ myTagTypeOffset _ = 0x1
170+
171+instance MyTagTypeOffset (Multi2 k) where
172+ myTagTypeOffset _ = 0x2
173+
174+instance MyTagTypeOffset Multi3 where
175+ myTagTypeOffset _ = 0x3
176+
177+type family EntryContents request a where
178+ EntryContents request (Single a) = request a
179+ EntryContents request Multi = IntMap (RequesterData request)
180+ EntryContents request (Multi2 k) = Map (Some k) (IntMap (RequesterData request))
181+ EntryContents request Multi3 = IntMap (IntMap (RequesterData request))
182+
183+newtype Entry request x = Entry { unEntry :: EntryContents request x }
184+
185+{-# INLINE singleEntry #-}
186+singleEntry :: f a -> Entry f (Single a)
187+singleEntry = Entry
188+
189+{-# INLINE multiEntry #-}
190+multiEntry :: IntMap (RequesterData f) -> Entry f Multi
191+multiEntry = Entry
192+
193+{-# INLINE unMultiEntry #-}
194+unMultiEntry :: Entry f Multi -> IntMap (RequesterData f)
195+unMultiEntry = unEntry
196+
197+-- | 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
198+-- 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
199+newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum)
200+
201+newtype MyTagWrap (f :: * -> *) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum)
202+
203+{-# INLINE castMyTagWrap #-}
204+castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x)
205+castMyTagWrap = coerce
206+
207+instance GEq MyTag where
208+ (MyTag a) `geq` (MyTag b) =
209+ if a == b
210+ then Just $ unsafeCoerce Refl
211+ else Nothing
212+
213+instance GCompare MyTag where
214+ (MyTag a) `gcompare` (MyTag b) =
215+ case a `compare` b of
216+ LT -> GLT
217+ EQ -> unsafeCoerce GEQ
218+ GT -> GGT
219+
220+instance GEq (MyTagWrap f) where
221+ (MyTagWrap a) `geq` (MyTagWrap b) =
222+ if a == b
223+ then Just $ unsafeCoerce Refl
224+ else Nothing
225+
226+instance GCompare (MyTagWrap f) where
227+ (MyTagWrap a) `gcompare` (MyTagWrap b) =
228+ case a `compare` b of
229+ LT -> GLT
230+ EQ -> unsafeCoerce GEQ
231+ GT -> GGT
232+
233+data RequesterState t (request :: * -> *) = RequesterState
234+ { _requesterState_nextMyTag :: {-# UNPACK #-} !Int -- Starts at -4 and goes down by 4 each time, to accommodate two 'type' bits at the bottom
235+ , _requesterState_requests :: ![(Int, Event t Any)]
236+ }
237+
238+-- | A basic implementation of 'Requester'.
239+newtype RequesterT t request (response :: * -> *) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a }
240+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
241+-- MonadAsyncException can't be derived on ghc-8.0.1; we use base-4.9.1 as a proxy for ghc-8.0.2
242+#if MIN_VERSION_base(4,9,1)
243+ , MonadAsyncException
244+#endif
245+ )
246+
247+deriving instance MonadSample t m => MonadSample t (RequesterT t request response m)
248+deriving instance MonadHold t m => MonadHold t (RequesterT t request response m)
249+deriving instance PostBuild t m => PostBuild t (RequesterT t request response m)
250+deriving instance TriggerEvent t m => TriggerEvent t (RequesterT t request response m)
251+
252+instance PrimMonad m => PrimMonad (RequesterT t request response m) where
253+ type PrimState (RequesterT t request response m) = PrimState m
254+ primitive = lift . primitive
255+
256+-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
257+instance (Monoid a, Monad m) => Monoid (RequesterT t request response m a) where
258+ mempty = pure mempty
259+ mappend = liftA2 mappend
260+
261+instance (S.Semigroup a, Monad m) => S.Semigroup (RequesterT t request response m a) where
262+ (<>) = liftA2 (S.<>)
263+
264+
265+-- | Run a 'RequesterT' action. The resulting 'Event' will fire whenever
266+-- requests are made, and responses should be provided in the input 'Event'.
267+-- The 'Tag' keys will be used to return the responses to the same place the
268+-- requests were issued.
269+runRequesterT :: (Reflex t, Monad m)
270+ => RequesterT t request response m a
271+ -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse
272+ -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild
273+runRequesterT (RequesterT a) responses = do
274+ (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $
275+ coerceEvent responses
276+ return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s)
277+
278+-- | Map a function over the request and response of a 'RequesterT'
279+withRequesterT
280+ :: (Reflex t, MonadFix m)
281+ => (forall x. req x -> req' x) -- ^ The function to map over the request
282+ -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response
283+ -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed
284+ -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT'
285+withRequesterT freq frsp child = do
286+ rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp'
287+ (a, req) <- lift $ runRequesterT child rsp
288+ rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $
289+ fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req
290+ return a
291+
292+instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where
293+ type Request (RequesterT t request response m) = request
294+ type Response (RequesterT t request response m) = response
295+ requesting = fmap coerceEvent . responseFromTag . castMyTagWrap <=< tagRequest . (coerceEvent :: Event t (request a) -> Event t (Entry request (Single a)))
296+ requesting_ = void . tagRequest . fmapCheap singleEntry
297+
298+{-# INLINE tagRequest #-}
299+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))
300+tagRequest req = do
301+ old <- RequesterT get
302+ let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x)
303+ t = MyTagWrap n
304+ RequesterT $ put $ RequesterState
305+ { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4
306+ , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old
307+ }
308+ return t
309+
310+{-# INLINE responseFromTag #-}
311+responseFromTag :: Monad m => MyTagWrap response (Entry response x) -> RequesterT t request response m (Event t (Entry response x))
312+responseFromTag (MyTagWrap t) = do
313+ responses :: EventSelectorInt t Any <- RequesterT ask
314+ return $ (unsafeCoerce :: Event t Any -> Event t (Entry response x)) $ selectInt responses t
315+
316+instance MonadTrans (RequesterT t request response) where
317+ lift = RequesterT . lift . lift
318+
319+instance PerformEvent t m => PerformEvent t (RequesterT t request response m) where
320+ type Performable (RequesterT t request response m) = Performable m
321+ performEvent_ = lift . performEvent_
322+ performEvent = lift . performEvent
323+
324+instance MonadRef m => MonadRef (RequesterT t request response m) where
325+ type Ref (RequesterT t request response m) = Ref m
326+ newRef = lift . newRef
327+ readRef = lift . readRef
328+ writeRef r = lift . writeRef r
329+
330+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequesterT t request response m) where
331+ newEventWithTrigger = lift . newEventWithTrigger
332+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
333+
334+instance MonadReader r m => MonadReader r (RequesterT t request response m) where
335+ ask = lift ask
336+ local f (RequesterT a) = RequesterT $ mapStateT (mapReaderT $ local f) a
337+ reader = lift . reader
338+
339+instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where
340+ runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
341+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental
342+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
343+ traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental
344+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove
345+
346+requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x))
347+requesting' = responseFromTag . castMyTagWrap <=< tagRequest
348+
349+{-# INLINABLE runWithReplaceRequesterTWith #-}
350+runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m
351+ , MonadFix m
352+ )
353+ => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))
354+ -> RequesterT t request response m a
355+ -> Event t (RequesterT t request response m b)
356+ -> RequesterT t request response m (a, Event t b)
357+runWithReplaceRequesterTWith f a0 a' = do
358+ rec na' <- numberOccurrencesFrom 1 a'
359+ responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here
360+ let responses' = fanInt responses
361+ ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na'
362+ requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v'
363+ return (result0, fmapCheap (fst . snd) v')
364+
365+{-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-}
366+traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p.
367+ ( Reflex t
368+ , MonadHold t m
369+ , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))
370+ , Patch (p (Event t (IntMap (RequesterData request))))
371+ , Functor p
372+ , MonadFix m
373+ )
374+ => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))
375+ -> IntMap (IntMap.Key, v)
376+ -> Event t (p (IntMap.Key, v))
377+ -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))
378+ )
379+ -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))
380+ -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))
381+ -> (IntMap.Key -> v -> RequesterT t request response m v')
382+ -> IntMap v
383+ -> Event t (p v)
384+ -> RequesterT t request response m (IntMap v', Event t (p v'))
385+traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do
386+ rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
387+ let responses :: EventSelectorInt t (IntMap (RequesterData response))
388+ responses = fanInt $ fmapCheap unpack response
389+ unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response))
390+ unpack = unEntry
391+ pack :: IntMap (IntMap (RequesterData request)) -> Entry request Multi3
392+ pack = Entry
393+ f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v')
394+ f' k (n, v) = do
395+ (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?
396+ return (fmapCheap (IntMap.singleton n) myRequests, result)
397+ ndm' <- numberOccurrencesFrom 1 dm'
398+ (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
399+ let result0 = fmap snd children0
400+ result' = fforCheap children' $ fmap snd
401+ requests0 :: IntMap (Event t (IntMap (RequesterData request)))
402+ requests0 = fmap fst children0
403+ requests' :: Event t (p (Event t (IntMap (RequesterData request))))
404+ requests' = fforCheap children' $ fmap fst
405+ promptRequests :: Event t (IntMap (IntMap (RequesterData request)))
406+ promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
407+ requests <- holdIncremental requests0 requests'
408+ return (result0, result')
409+
410+{-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-}
411+traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'.
412+ ( GCompare k
413+ , Reflex t
414+ , MonadHold t m
415+ , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))
416+ , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))
417+ , MonadFix m
418+ )
419+ => (forall k' v1 v2. GCompare k'
420+ => (forall a. k' a -> v1 a -> m (v2 a))
421+ -> DMap k' v1
422+ -> Event t (p k' v1)
423+ -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))
424+ )
425+ -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)
426+ -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)
427+ -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)
428+ -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))
429+ -> (forall a. k a -> v a -> RequesterT t request response m (v' a))
430+ -> DMap k v
431+ -> Event t (p k v)
432+ -> RequesterT t request response m (DMap k v', Event t (p k v'))
433+traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do
434+ rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
435+ let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response)))
436+ responses = fanMap $ fmapCheap unpack response
437+ unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response))
438+ unpack = unEntry
439+ pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k)
440+ pack = Entry
441+ f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a)
442+ f' k (Compose (n, v)) = do
443+ (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some k))
444+ return $ Compose (fmapCheap (IntMap.singleton n) myRequests, result)
445+ ndm' <- numberOccurrencesFrom 1 dm'
446+ (children0, children') <- base f' (DMap.map (\v -> Compose (0, v)) dm0) $ fmap (\(n, dm) -> mapPatch (\v -> Compose (n, v)) dm) ndm'
447+ let result0 = DMap.map (snd . getCompose) children0
448+ result' = fforCheap children' $ mapPatch $ snd . getCompose
449+ requests0 :: Map (Some k) (Event t (IntMap (RequesterData request)))
450+ requests0 = weakenDMapWith (fst . getCompose) children0
451+ requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request))))
452+ requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
453+ promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request)))
454+ promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
455+ requests <- holdIncremental requests0 requests'
456+ return (result0, result')
457+
458+data Decoder rawResponse response =
459+ forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)
460+
461+-- | Matches incoming responses with previously-sent requests
462+-- and uses the provided request "decoder" function to process
463+-- incoming responses.
464+matchResponsesWithRequests
465+ :: forall t rawRequest rawResponse request response m.
466+ ( MonadFix m
467+ , MonadHold t m
468+ , Reflex t
469+ )
470+ => (forall a. request a -> (rawRequest, rawResponse -> response a))
471+ -- ^ Given a request (from 'Requester'), produces the wire format of the
472+ -- request and a function used to process the associated response
473+ -> Event t (RequesterData request)
474+ -- ^ The outgoing requests
475+ -> Event t (Int, rawResponse)
476+ -- ^ The incoming responses, tagged by an identifying key
477+ -> m ( Event t (Map Int rawRequest)
478+ , Event t (RequesterData response)
479+ )
480+ -- ^ A map of outgoing wire-format requests and an event of responses keyed
481+ -- by the 'RequesterData' key of the associated outgoing request
482+matchResponsesWithRequests f send recv = do
483+ rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing
484+ waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <-
485+ holdIncremental mempty $ leftmost
486+ [ fmap (\(_, outstanding, _) -> outstanding) outgoing
487+ , snd <$> incoming
488+ ]
489+ let outgoing = processOutgoing nextId send
490+ incoming = processIncoming waitingFor recv
491+ return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming)
492+ where
493+ -- Tags each outgoing request with an identifying integer key
494+ -- and returns the next available key, a map of response decoders
495+ -- for requests for which there are outstanding responses, and the
496+ -- raw requests to be sent out.
497+ processOutgoing
498+ :: Behavior t Int
499+ -- The next available key
500+ -> Event t (RequesterData request)
501+ -- The outgoing request
502+ -> Event t ( Int
503+ , PatchMap Int (Decoder rawResponse response)
504+ , Map Int rawRequest )
505+ -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests
506+ processOutgoing nextId out = flip pushAlways out $ \dm -> do
507+ oldNextId <- sample nextId
508+ let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do
509+ n <- get
510+ put $ succ n
511+ let (rawReq, rspF) = f v
512+ return (n, rawReq, Decoder k rspF)
513+ patchWaitingFor = PatchMap $ Map.fromList $
514+ (\(n, _, dec) -> (n, Just dec)) <$> result
515+ toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result
516+ return (newNextId, patchWaitingFor, toSend)
517+ -- Looks up the each incoming raw response in a map of response
518+ -- decoders and returns the decoded response and a patch that can
519+ -- be used to clear the ID of the consumed response out of the queue
520+ -- of expected responses.
521+ processIncoming
522+ :: Incremental t (PatchMap Int (Decoder rawResponse response))
523+ -- A map of outstanding expected responses
524+ -> Event t (Int, rawResponse)
525+ -- A incoming response paired with its identifying key
526+ -> Event t (RequesterData response, PatchMap Int v)
527+ -- The decoded response and a patch that clears the outstanding responses queue
528+ processIncoming waitingFor inc = flip push inc $ \(n, rawRsp) -> do
529+ wf <- sample $ currentIncremental waitingFor
530+ case Map.lookup n wf of
531+ Nothing -> return Nothing -- TODO How should lookup failures be handled here? They shouldn't ever happen..
532+ Just (Decoder k rspF) -> do
533+ let rsp = rspF rawRsp
534+ return $ Just
535+ ( singletonRequesterData k rsp
536+ , PatchMap $ Map.singleton n Nothing
537+ )
src/Reflex/Requester/Class.hsnew file+73
@@ -0,0 +1,73 @@
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.hsnew file+20
@@ -0,0 +1,20 @@
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.hsnew file+2665
@@ -0,0 +1,2665 @@
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+{-# LANGUAGE PolyKinds #-}
21+{-# LANGUAGE InstanceSigs #-}
22+#ifdef USE_REFLEX_OPTIMIZER
23+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
24+#endif
25+{-# OPTIONS_GHC -Wunused-binds #-}
26+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
27+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
28+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
29+
30+#if MIN_VERSION_base(4,10,0)
31+import Control.Applicative (liftA2)
32+#endif
33+import Control.Concurrent
34+import Control.Exception
35+import Control.Monad hiding (forM, forM_, mapM, mapM_)
36+import Control.Monad.Exception
37+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
38+import Control.Monad.Primitive
39+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
40+import Control.Monad.Ref
41+import Data.Align
42+import Data.Coerce
43+import Data.Dependent.Map (DMap, DSum (..))
44+import qualified Data.Dependent.Map as DMap
45+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
46+import qualified Data.FastMutableIntMap as FastMutableIntMap
47+import Data.Foldable hiding (concat, elem, sequence_)
48+import Data.Functor.Constant
49+import Data.Functor.Misc
50+import Data.Functor.Product
51+import Data.GADT.Compare
52+import Data.IntMap.Strict (IntMap)
53+import qualified Data.IntMap.Strict as IntMap
54+import Data.IORef
55+import Data.Kind (Type)
56+import Data.Maybe hiding (mapMaybe)
57+import Data.Monoid ((<>))
58+import Data.Proxy
59+import Data.These
60+import Data.Traversable
61+import Data.Witherable (Filterable, mapMaybe)
62+import GHC.Exts
63+import GHC.IORef (IORef (..))
64+import GHC.Stack
65+import Reflex.FastWeak
66+import System.IO.Unsafe
67+import System.Mem.Weak
68+import Unsafe.Coerce
69+
70+#ifdef DEBUG_CYCLES
71+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
72+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
73+import qualified Data.List.NonEmpty as NonEmpty
74+import Data.Monoid (mempty)
75+import Data.Tree (Forest, Tree (..), drawForest)
76+#endif
77+
78+import Data.FastWeakBag (FastWeakBag)
79+import qualified Data.FastWeakBag as FastWeakBag
80+import Data.Reflection
81+import Data.Some (Some(Some))
82+import Data.Type.Coercion
83+import Data.Profunctor.Unsafe ((#.), (.#))
84+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
85+import qualified Data.WeakBag as WeakBag
86+import qualified Reflex.Class
87+import qualified Reflex.Class as R
88+import qualified Reflex.Host.Class
89+import Reflex.NotReady.Class
90+import Reflex.Patch
91+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
92+
93+#ifdef DEBUG_TRACE_EVENTS
94+import qualified Data.ByteString.Char8 as BS8
95+import System.IO (stderr)
96+#endif
97+
98+#ifdef DEBUG_TRACE_EVENTS
99+
100+withStackOneLine :: (BS8.ByteString -> a) -> a
101+withStackOneLine expr = unsafePerformIO $ do
102+ stack <- currentCallStack
103+ return (expr (BS8.pack (unwords (reverse stack))))
104+
105+#endif
106+
107+debugPropagate :: Bool
108+
109+debugInvalidateHeight :: Bool
110+
111+debugInvalidate :: Bool
112+
113+#ifdef DEBUG
114+
115+#define DEBUG_NODEIDS
116+
117+debugPropagate = True
118+
119+debugInvalidateHeight = False
120+
121+debugInvalidate = True
122+
123+class HasNodeId a where
124+ getNodeId :: a -> Int
125+
126+instance HasNodeId (Hold x p a) where
127+ getNodeId = holdNodeId
128+
129+instance HasNodeId (PushSubscribed x a b) where
130+ getNodeId = pushSubscribedNodeId
131+
132+instance HasNodeId (SwitchSubscribed x a) where
133+ getNodeId = switchSubscribedNodeId
134+
135+instance HasNodeId (FanSubscribed x a) where
136+ getNodeId = fanSubscribedNodeId
137+
138+instance HasNodeId (CoincidenceSubscribed x a) where
139+ getNodeId = coincidenceSubscribedNodeId
140+
141+instance HasNodeId (RootSubscribed x a) where
142+ getNodeId = rootSubscribedNodeId
143+
144+instance HasNodeId (Pull x a) where
145+ getNodeId = pullNodeId
146+
147+{-# INLINE showNodeId #-}
148+showNodeId :: HasNodeId a => a -> String
149+showNodeId = ("#"<>) . show . getNodeId
150+
151+showSubscriberType :: Subscriber x a -> String
152+showSubscriberType = \case
153+ SubscriberPush _ _ -> "SubscriberPush"
154+ SubscriberMerge _ _ -> "SubscriberMerge"
155+ SubscriberFan _ -> "SubscriberFan"
156+ SubscriberMergeChange _ -> "SubscriberMergeChange"
157+ SubscriberHold _ -> "SubscriberHold"
158+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
159+ SubscriberSwitch _ -> "SubscriberSwitch"
160+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
161+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
162+ SubscriberHandle -> "SubscriberHandle"
163+
164+showEventType :: Event x a -> String
165+showEventType = \case
166+ EventRoot _ _ -> "EventRoot"
167+ EventNever -> "EventNever"
168+ EventPush _ -> "EventPush"
169+ EventMerge _ -> "EventMerge"
170+ EventFan _ _ -> "EventFan"
171+ EventSwitch _ -> "EventSwitch"
172+ EventCoincidence _ -> "EventCoincidence"
173+ EventHold _ -> "EventHold"
174+ EventDyn _ -> "EventDyn"
175+ EventHoldIdentity _ -> "EventHoldIdentity"
176+ EventDynIdentity _ -> "EventDynIdentity"
177+
178+#else
179+
180+debugPropagate = False
181+
182+debugInvalidateHeight = False
183+
184+debugInvalidate = False
185+
186+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
187+{-# INLINE showNodeId #-}
188+showNodeId :: a -> String
189+showNodeId _ = ""
190+
191+#endif
192+
193+#ifdef DEBUG_NODEIDS
194+{-# NOINLINE nextNodeIdRef #-}
195+nextNodeIdRef :: IORef Int
196+nextNodeIdRef = unsafePerformIO $ newIORef 1
197+
198+newNodeId :: IO Int
199+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
200+
201+{-# NOINLINE unsafeNodeId #-}
202+unsafeNodeId :: a -> Int
203+unsafeNodeId a = unsafePerformIO $ do
204+ touch a
205+ newNodeId
206+#endif
207+
208+--------------------------------------------------------------------------------
209+-- EventSubscription
210+--------------------------------------------------------------------------------
211+
212+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
213+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
214+data EventSubscription x = EventSubscription
215+ { _eventSubscription_unsubscribe :: !(IO ())
216+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
217+ }
218+
219+unsubscribe :: EventSubscription x -> IO ()
220+unsubscribe (EventSubscription u _) = u
221+
222+--------------------------------------------------------------------------------
223+-- Event
224+--------------------------------------------------------------------------------
225+
226+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
227+
228+{-# INLINE subscribeAndRead #-}
229+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
230+subscribeAndRead = unEvent
231+
232+{-# RULES
233+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
234+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
235+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
236+ #-}
237+
238+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
239+-- caching; if the computation function is very cheap, this is (much) more
240+-- efficient than 'push'
241+{-# INLINE [1] pushCheap #-}
242+pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
243+pushCheap !f e = Event $ \sub -> do
244+ (subscription, occ) <- subscribeAndRead e $ sub
245+ { subscriberPropagate = \a -> do
246+ mb <- f a
247+ mapM_ (subscriberPropagate sub) mb
248+ }
249+ occ' <- join <$> mapM f occ
250+ return (subscription, occ')
251+
252+-- | A subscriber that never triggers other 'Event's
253+{-# INLINE terminalSubscriber #-}
254+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
255+terminalSubscriber p = Subscriber
256+ { subscriberPropagate = p
257+ , subscriberInvalidateHeight = \_ -> return ()
258+ , subscriberRecalculateHeight = \_ -> return ()
259+ }
260+
261+-- | Subscribe to an Event only for the duration of one occurrence
262+{-# INLINE subscribeAndReadHead #-}
263+subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
264+subscribeAndReadHead e sub = do
265+ subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
266+ (subscription, occ) <- subscribeAndRead e $ sub
267+ { subscriberPropagate = \a -> do
268+ liftIO $ unsubscribe =<< readIORef subscriptionRef
269+ subscriberPropagate sub a
270+ }
271+ liftIO $ case occ of
272+ Nothing -> writeIORef subscriptionRef $! subscription
273+ Just _ -> unsubscribe subscription
274+ return (subscription, occ)
275+
276+--TODO: Make this lazy in its input event
277+headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
278+headE originalE = do
279+ parent <- liftIO $ newIORef $ Just originalE
280+ defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
281+ let clearParent = liftIO $ writeIORef parent Nothing
282+ (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
283+ when (isJust occ) clearParent
284+ return $ Event $ \sub -> do
285+ liftIO (readIORef parent) >>= \case
286+ Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
287+ Just e -> subscribeAndReadHead e sub
288+
289+data CacheSubscribed x a
290+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
291+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
292+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
293+ }
294+
295+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
296+-- repeatedly
297+--
298+--TODO: Try a caching strategy where we subscribe directly to the parent when
299+--there's only one subscriber, and then build our own FastWeakBag only when a second
300+--subscriber joins
301+{-# NOINLINE [0] cacheEvent #-}
302+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
303+cacheEvent e =
304+#ifdef DEBUG_TRACE_EVENTS
305+ withStackOneLine $ \callSite -> Event $
306+#else
307+ Event $
308+#endif
309+ let mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
310+ !mSubscribedRef = unsafeNewIORef e emptyFastWeak
311+ in \sub -> {-# SCC "cacheEvent" #-} do
312+#ifdef DEBUG_TRACE_EVENTS
313+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
314+#endif
315+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
316+ Just subscribedTicket -> return subscribedTicket
317+ Nothing -> do
318+ subscribers <- liftIO FastWeakBag.empty
319+ occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
320+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
321+ { subscriberPropagate = \a -> do
322+ liftIO $ writeIORef occRef $ Just a
323+ scheduleClear occRef
324+ propagateFast a subscribers
325+ , subscriberInvalidateHeight = \old -> do
326+ FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
327+ , subscriberRecalculateHeight = \new -> do
328+ FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
329+ }
330+ when (isJust occ) $ do
331+ liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
332+ scheduleClear occRef
333+ let !subscribed = CacheSubscribed
334+ { _cacheSubscribed_subscribers = subscribers
335+ , _cacheSubscribed_parent = parentSub
336+ , _cacheSubscribed_occurrence = occRef
337+ }
338+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
339+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
340+ return subscribedTicket
341+ liftIO $ do
342+ subscribed <- getFastWeakTicketValue subscribedTicket
343+ ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
344+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
345+ let es = EventSubscription
346+ { _eventSubscription_unsubscribe = do
347+ FastWeakBag.remove ticket
348+ isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
349+ when isEmpty $ do
350+ writeIORef mSubscribedRef emptyFastWeak
351+ unsubscribe $ _cacheSubscribed_parent subscribed
352+ touch ticket
353+ touch subscribedTicket
354+ , _eventSubscription_subscribed = EventSubscribed
355+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
356+ , eventSubscribedRetained = toAny subscribedTicket
357+ }
358+ }
359+ return (es, occ)
360+
361+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
362+subscribe e s = fst <$> subscribeAndRead e s
363+
364+{-# INLINE wrap #-}
365+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
366+wrap tag getSpecificSubscribed sub = do
367+ (sln, subd, occ) <- getSpecificSubscribed sub
368+ let es = tag subd
369+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
370+
371+eventRoot :: GCompare k => k a -> Root x k -> Event x a
372+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
373+
374+eventNever :: Event x a
375+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
376+
377+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
378+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
379+
380+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
381+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
382+
383+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
384+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
385+
386+eventHold :: Hold x p -> Event x p
387+eventHold !h = Event $ subscribeHoldEvent h
388+
389+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
390+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
391+
392+{-# INLINE subscribeCoincidenceInner #-}
393+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
394+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
395+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
396+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
397+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
398+ let height = max innerHeight outerHeight
399+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
400+ return (innerOcc, height, innerSubd)
401+
402+--------------------------------------------------------------------------------
403+-- Subscriber
404+--------------------------------------------------------------------------------
405+
406+data Subscriber x a = Subscriber
407+ { subscriberPropagate :: !(a -> EventM x ())
408+ , subscriberInvalidateHeight :: !(Height -> IO ())
409+ , subscriberRecalculateHeight :: !(Height -> IO ())
410+ }
411+
412+--TODO: Move this comment to WeakBag
413+-- These function are constructor functions that are marked NOINLINE so they are
414+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
415+-- so any weak references that are attached to the constructors will have their
416+-- finalizer run. Using the opaque constructor, does not see the
417+-- constructor application, so it behaves like an IORef and cannot be fused away.
418+--
419+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
420+-- the weak pointer to it in some cases.
421+
422+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
423+newSubscriberHold h = return $ Subscriber
424+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
425+ , subscriberInvalidateHeight = \_ -> return ()
426+ , subscriberRecalculateHeight = \_ -> return ()
427+ }
428+
429+newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
430+newSubscriberFan subscribed = return $ Subscriber
431+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
432+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
433+ tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
434+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
435+ scheduleClear $ fanSubscribedOccurrence subscribed
436+ let f _ (Pair (Identity v) subsubs) = do
437+ propagate v $ _fanSubscribedChildren_list subsubs
438+ return $ Constant ()
439+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
440+ return ()
441+ , subscriberInvalidateHeight = \old -> do
442+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
443+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
444+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
445+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
446+ , subscriberRecalculateHeight = \new -> do
447+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
448+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
449+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
450+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
451+ }
452+
453+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
454+newSubscriberSwitch subscribed = return $ Subscriber
455+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
456+ tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
457+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
458+ scheduleClear $ switchSubscribedOccurrence subscribed
459+ propagate a $ switchSubscribedSubscribers subscribed
460+ , subscriberInvalidateHeight = \_ -> do
461+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
462+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
463+ when (oldHeight /= invalidHeight) $ do
464+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
465+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
466+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
467+ , subscriberRecalculateHeight = \new -> do
468+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
469+ updateSwitchHeight new subscribed
470+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
471+ }
472+
473+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
474+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
475+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
476+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
477+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
478+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
479+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
480+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
481+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
482+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
483+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
484+ case occ of
485+ Nothing -> do
486+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
487+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
488+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
489+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
490+ Just o -> do -- Since it's already firing, no need to adjust height
491+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
492+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
493+ propagate o $ coincidenceSubscribedSubscribers subscribed
494+ , subscriberInvalidateHeight = \_ -> do
495+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
496+ invalidateCoincidenceHeight subscribed
497+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
498+ , subscriberRecalculateHeight = \_ -> do
499+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
500+ recalculateCoincidenceHeight subscribed
501+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
502+ }
503+
504+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
505+newSubscriberCoincidenceInner subscribed = return $ Subscriber
506+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
507+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
508+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
509+ case occ of
510+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
511+ Nothing -> do
512+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
513+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
514+ propagate a $ coincidenceSubscribedSubscribers subscribed
515+ , subscriberInvalidateHeight = \_ -> do
516+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
517+ invalidateCoincidenceHeight subscribed
518+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
519+ , subscriberRecalculateHeight = \_ -> do
520+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
521+ recalculateCoincidenceHeight subscribed
522+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
523+ }
524+
525+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
526+invalidateSubscriberHeight = flip subscriberInvalidateHeight
527+
528+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
529+recalculateSubscriberHeight = flip subscriberRecalculateHeight
530+
531+-- | Propagate everything at the current height
532+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
533+propagate a subscribers = withIncreasedDepth $ do
534+ -- 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
535+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
536+ WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
537+
538+-- | Propagate everything at the current height
539+propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
540+propagateFast a subscribers = withIncreasedDepth $ do
541+ -- 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
542+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
543+ FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
544+
545+--------------------------------------------------------------------------------
546+-- EventSubscribed
547+--------------------------------------------------------------------------------
548+
549+toAny :: a -> Any
550+toAny = unsafeCoerce
551+
552+data EventSubscribed x = EventSubscribed
553+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
554+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
555+#ifdef DEBUG_CYCLES
556+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
557+ , eventSubscribedHasOwnHeightRef :: !Bool
558+ , eventSubscribedWhoCreated :: !(IO [String])
559+#endif
560+ }
561+
562+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
563+eventSubscribedRoot !r = EventSubscribed
564+ { eventSubscribedHeightRef = zeroRef
565+ , eventSubscribedRetained = toAny r
566+#ifdef DEBUG_CYCLES
567+ , eventSubscribedGetParents = return []
568+ , eventSubscribedHasOwnHeightRef = False
569+ , eventSubscribedWhoCreated = return ["root"]
570+#endif
571+ }
572+
573+eventSubscribedNever :: EventSubscribed x
574+eventSubscribedNever = EventSubscribed
575+ { eventSubscribedHeightRef = zeroRef
576+ , eventSubscribedRetained = toAny ()
577+#ifdef DEBUG_CYCLES
578+ , eventSubscribedGetParents = return []
579+ , eventSubscribedHasOwnHeightRef = False
580+ , eventSubscribedWhoCreated = return ["never"]
581+#endif
582+ }
583+
584+eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
585+eventSubscribedFan !subscribed = EventSubscribed
586+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
587+ , eventSubscribedRetained = toAny subscribed
588+#ifdef DEBUG_CYCLES
589+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
590+ , eventSubscribedHasOwnHeightRef = False
591+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
592+#endif
593+ }
594+
595+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
596+eventSubscribedSwitch !subscribed = EventSubscribed
597+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
598+ , eventSubscribedRetained = toAny subscribed
599+#ifdef DEBUG_CYCLES
600+ , eventSubscribedGetParents = do
601+ s <- readIORef $ switchSubscribedCurrentParent subscribed
602+ return [Some $ _eventSubscription_subscribed s]
603+ , eventSubscribedHasOwnHeightRef = True
604+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
605+#endif
606+ }
607+
608+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
609+eventSubscribedCoincidence !subscribed = EventSubscribed
610+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
611+ , eventSubscribedRetained = toAny subscribed
612+#ifdef DEBUG_CYCLES
613+ , eventSubscribedGetParents = do
614+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
615+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
616+ innerParents = maybeToList $ fmap Some innerSubscription
617+ return $ outerParent : innerParents
618+ , eventSubscribedHasOwnHeightRef = True
619+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
620+#endif
621+ }
622+
623+getEventSubscribedHeight :: EventSubscribed x -> IO Height
624+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
625+
626+#ifdef DEBUG_CYCLES
627+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
628+whoCreatedEventSubscribed = eventSubscribedWhoCreated
629+
630+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
631+walkInvalidHeightParents s0 = do
632+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
633+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
634+ when (h == invalidHeight) $ do
635+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
636+ modify (Some s :)
637+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
638+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
639+ return subscribers
640+#endif
641+
642+{-# INLINE subscribeHoldEvent #-}
643+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
644+subscribeHoldEvent = subscribeAndRead . holdEvent
645+
646+--------------------------------------------------------------------------------
647+-- Behavior
648+--------------------------------------------------------------------------------
649+
650+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
651+
652+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
653+behaviorHold !h = Behavior $ readHoldTracked h
654+
655+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
656+behaviorHoldIdentity = behaviorHold
657+
658+behaviorConst :: a -> Behavior x a
659+behaviorConst !a = Behavior $ return a
660+
661+behaviorPull :: Pull x a -> Behavior x a
662+behaviorPull !p = Behavior $ do
663+ val <- liftIO $ readIORef $ pullValue p
664+ case val of
665+ Just subscribed -> do
666+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
667+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
668+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
669+ return $ pullSubscribedValue subscribed
670+ Nothing -> do
671+ i <- liftIO $ newInvalidatorPull p
672+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
673+ parentsRef <- liftIO $ newIORef []
674+ holdInits <- askBehaviorHoldInits
675+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
676+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
677+ parents <- liftIO $ readIORef parentsRef
678+ let subscribed = PullSubscribed
679+ { pullSubscribedValue = a
680+ , pullSubscribedInvalidators = invsRef
681+ , pullSubscribedOwnInvalidator = i
682+ , pullSubscribedParents = parents
683+ }
684+ liftIO $ writeIORef (pullValue p) $ Just subscribed
685+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
686+ return a
687+
688+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
689+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
690+
691+{-# INLINE readHoldTracked #-}
692+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
693+readHoldTracked h = do
694+ result <- liftIO $ readIORef $ holdValue h
695+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
696+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
697+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
698+ return result
699+
700+{-# INLINABLE readBehaviorUntracked #-}
701+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
702+readBehaviorUntracked b = do
703+ holdInits <- getDeferralQueue
704+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
705+
706+--------------------------------------------------------------------------------
707+-- Dynamic
708+--------------------------------------------------------------------------------
709+
710+data Dynamic x p = Dynamic
711+ { dynamicCurrent :: !(Behavior x (PatchTarget p))
712+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
713+ }
714+
715+dynamicHold :: Hold x p -> Dynamic x p
716+dynamicHold !h = Dynamic
717+ { dynamicCurrent = behaviorHold h
718+ , dynamicUpdated = eventHold h
719+ }
720+
721+dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
722+dynamicHoldIdentity = dynamicHold
723+
724+dynamicConst :: PatchTarget p -> Dynamic x p
725+dynamicConst !a = Dynamic
726+ { dynamicCurrent = behaviorConst a
727+ , dynamicUpdated = eventNever
728+ }
729+
730+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
731+dynamicDyn !d = Dynamic
732+ { dynamicCurrent = behaviorDyn d
733+ , dynamicUpdated = eventDyn d
734+ }
735+
736+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
737+dynamicDynIdentity = dynamicDyn
738+
739+--------------------------------------------------------------------------------
740+-- Combinators
741+--------------------------------------------------------------------------------
742+
743+--TODO: Figure out why certain things are not 'representational', then make them
744+--representational so we can use coerce
745+
746+--type role Hold representational
747+data Hold x p
748+ = Hold { holdValue :: !(IORef (PatchTarget p))
749+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
750+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
751+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
752+#ifdef DEBUG_NODEIDS
753+ , holdNodeId :: Int
754+#endif
755+ }
756+
757+-- | A statically allocated 'SpiderTimeline'
758+data Global
759+
760+{-# NOINLINE globalSpiderTimelineEnv #-}
761+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
762+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
763+
764+-- | Stores all global data relevant to a particular Spider timeline; only one
765+-- value should exist for each type @x@
766+data SpiderTimelineEnv x = SpiderTimelineEnv
767+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
768+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
769+#ifdef DEBUG
770+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
771+#endif
772+ }
773+type role SpiderTimelineEnv nominal
774+
775+instance Eq (SpiderTimelineEnv x) where
776+ _ == _ = True -- Since only one exists of each type
777+
778+instance GEq SpiderTimelineEnv where
779+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
780+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
781+ else Nothing
782+
783+data EventEnv x
784+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
785+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
786+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
787+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
788+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
789+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
790+ , eventEnvIntClears :: !(IORef [Some IntClear])
791+ , eventEnvRootClears :: !(IORef [Some RootClear])
792+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
793+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
794+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
795+ }
796+
797+{-# INLINE runEventM #-}
798+runEventM :: EventM x a -> IO a
799+runEventM = unEventM
800+
801+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
802+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
803+
804+class MonadIO m => Defer a m where
805+ getDeferralQueue :: m (IORef [a])
806+
807+{-# INLINE defer #-}
808+defer :: Defer a m => a -> m ()
809+defer a = do
810+ q <- getDeferralQueue
811+ liftIO $ modifyIORef' q (a:)
812+
813+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
814+ {-# INLINE getDeferralQueue #-}
815+ getDeferralQueue = asksEventEnv eventEnvAssignments
816+
817+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
818+ {-# INLINE getDeferralQueue #-}
819+ getDeferralQueue = asksEventEnv eventEnvHoldInits
820+
821+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
822+ {-# INLINE getDeferralQueue #-}
823+ getDeferralQueue = asksEventEnv eventEnvDynInits
824+
825+instance Defer (SomeHoldInit x) (BehaviorM x) where
826+ {-# INLINE getDeferralQueue #-}
827+ getDeferralQueue = BehaviorM $ asks snd
828+
829+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
830+ {-# INLINE getDeferralQueue #-}
831+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
832+
833+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
834+ {-# INLINE getDeferralQueue #-}
835+ getDeferralQueue = asksEventEnv eventEnvMergeInits
836+
837+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
838+ getCurrentHeight :: m Height
839+ scheduleMerge :: Height -> EventM x () -> m ()
840+
841+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
842+ {-# INLINE getCurrentHeight #-}
843+ getCurrentHeight = do
844+ heightRef <- asksEventEnv eventEnvCurrentHeight
845+ liftIO $ readIORef heightRef
846+ {-# INLINE scheduleMerge #-}
847+ scheduleMerge height subscribed = do
848+ delayedRef <- asksEventEnv eventEnvDelayedMerges
849+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
850+
851+class HasSpiderTimeline x where
852+ -- | Retrieve the current SpiderTimelineEnv
853+ spiderTimeline :: SpiderTimelineEnv x
854+
855+instance HasSpiderTimeline Global where
856+ spiderTimeline = globalSpiderTimelineEnv
857+
858+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
859+putCurrentHeight h = do
860+ heightRef <- asksEventEnv eventEnvCurrentHeight
861+ liftIO $ writeIORef heightRef $! h
862+
863+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
864+ {-# INLINE getDeferralQueue #-}
865+ getDeferralQueue = asksEventEnv eventEnvClears
866+
867+{-# INLINE scheduleClear #-}
868+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
869+scheduleClear r = defer $ Some $ Clear r
870+
871+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
872+ {-# INLINE getDeferralQueue #-}
873+ getDeferralQueue = asksEventEnv eventEnvIntClears
874+
875+{-# INLINE scheduleIntClear #-}
876+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
877+scheduleIntClear r = defer $ Some $ IntClear r
878+
879+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
880+ {-# INLINE getDeferralQueue #-}
881+ getDeferralQueue = asksEventEnv eventEnvRootClears
882+
883+{-# INLINE scheduleRootClear #-}
884+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
885+scheduleRootClear r = defer $ Some $ RootClear r
886+
887+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
888+ {-# INLINE getDeferralQueue #-}
889+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
890+
891+-- Note: hold cannot examine its event until after the phase is over
892+{-# INLINE [1] hold #-}
893+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
894+hold v0 e = do
895+ valRef <- liftIO $ newIORef v0
896+ invsRef <- liftIO $ newIORef []
897+ parentRef <- liftIO $ newIORef Nothing
898+#ifdef DEBUG_NODEIDS
899+ nodeId <- liftIO newNodeId
900+#endif
901+ let h = Hold
902+ { holdValue = valRef
903+ , holdInvalidators = invsRef
904+ , holdEvent = e
905+ , holdParent = parentRef
906+#ifdef DEBUG_NODEIDS
907+ , holdNodeId = nodeId
908+#endif
909+ }
910+ defer $ SomeHoldInit h
911+ return h
912+
913+{-# INLINE getHoldEventSubscription #-}
914+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
915+getHoldEventSubscription h = do
916+ ep <- liftIO $ readIORef $ holdParent h
917+ case ep of
918+ Just subd -> return subd
919+ Nothing -> do
920+ let e = holdEvent h
921+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
922+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
923+ liftIO $ writeIORef subscriptionRef $! subscription
924+ case occ of
925+ Nothing -> return ()
926+ Just o -> do
927+ old <- liftIO $ readIORef $ holdValue h
928+ case apply o old of
929+ Nothing -> return ()
930+ Just new -> do
931+ -- Need to evaluate these so that we don't retain the Hold itself
932+ v <- liftIO $ evaluate $ holdValue h
933+ i <- liftIO $ evaluate $ holdInvalidators h
934+ defer $ SomeAssignment v i new
935+ liftIO $ writeIORef (holdParent h) $ Just subscription
936+ return subscription
937+
938+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
939+
940+--type role BehaviorM representational
941+-- BehaviorM can sample behaviors
942+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
943+
944+instance Monad (BehaviorM x) where
945+ {-# INLINE (>>=) #-}
946+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
947+ {-# INLINE (>>) #-}
948+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
949+ {-# INLINE return #-}
950+ return x = BehaviorM $ return x
951+ {-# INLINE fail #-}
952+ fail s = BehaviorM $ fail s
953+
954+data BehaviorSubscribed x a
955+ = forall p. BehaviorSubscribedHold (Hold x p)
956+ | BehaviorSubscribedPull (PullSubscribed x a)
957+
958+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
959+
960+--type role PullSubscribed representational
961+data PullSubscribed x a
962+ = PullSubscribed { pullSubscribedValue :: !a
963+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
964+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
965+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
966+ }
967+
968+--type role Pull representational
969+data Pull x a
970+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
971+ , pullCompute :: !(BehaviorM x a)
972+#ifdef DEBUG_NODEIDS
973+ , pullNodeId :: Int
974+#endif
975+ }
976+
977+data Invalidator x
978+ = forall a. InvalidatorPull (Pull x a)
979+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
980+
981+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
982+ { rootSubscribedKey :: !(k a)
983+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
984+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
985+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
986+ , rootSubscribedUninit :: IO ()
987+ , 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?
988+#ifdef DEBUG_NODEIDS
989+ , rootSubscribedNodeId :: Int
990+#endif
991+ }
992+
993+data Root x (k :: * -> *)
994+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
995+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
996+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
997+ }
998+
999+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1000+
1001+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1002+
1003+data SomeMergeUpdate x = SomeMergeUpdate
1004+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1005+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1006+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1007+ }
1008+
1009+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1010+
1011+-- EventM can do everything BehaviorM can, plus create holds
1012+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
1013+
1014+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1015+
1016+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1017+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1018+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1019+ }
1020+
1021+data HeightBag = HeightBag
1022+ { _heightBag_size :: {-# UNPACK #-} !Int
1023+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1024+ }
1025+ deriving (Show, Read, Eq, Ord)
1026+
1027+heightBagEmpty :: HeightBag
1028+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1029+
1030+heightBagSize :: HeightBag -> Int
1031+heightBagSize = _heightBag_size
1032+
1033+heightBagFromList :: [Height] -> HeightBag
1034+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1035+
1036+heightBagAdd :: Height -> HeightBag -> HeightBag
1037+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1038+
1039+heightBagRemove :: Height -> HeightBag -> HeightBag
1040+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1041+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1042+ Just old -> HeightBag (pred s) $ case old of
1043+ 0 -> IntMap.delete h c
1044+ _ -> IntMap.insert h (pred old) c
1045+
1046+heightBagMax :: HeightBag -> Height
1047+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1048+ Just ((h, _), _) -> Height h
1049+ Nothing -> zeroHeight
1050+
1051+heightBagVerify :: HeightBag -> HeightBag
1052+#ifdef DEBUG
1053+heightBagVerify b@(HeightBag s c) = if
1054+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1055+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1056+ | unHeight invalidHeight `IntMap.member` c
1057+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1058+ | otherwise -> b
1059+#else
1060+heightBagVerify = id
1061+#endif
1062+
1063+data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1064+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1065+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1066+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1067+ }
1068+
1069+data FanSubscribed (x :: *) k
1070+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1071+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1072+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1073+ , fanSubscribedParent :: !(EventSubscription x)
1074+#ifdef DEBUG_NODEIDS
1075+ , fanSubscribedNodeId :: Int
1076+#endif
1077+ }
1078+
1079+data Fan x k
1080+ = Fan { fanParent :: !(Event x (DMap k Identity))
1081+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1082+ }
1083+
1084+data SwitchSubscribed x a
1085+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1086+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1087+ , switchSubscribedHeight :: !(IORef Height)
1088+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1089+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1090+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1091+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1092+ , switchSubscribedParent :: !(Behavior x (Event x a))
1093+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1094+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1095+#ifdef DEBUG_NODEIDS
1096+ , switchSubscribedNodeId :: Int
1097+#endif
1098+ }
1099+
1100+data Switch x a
1101+ = Switch { switchParent :: !(Behavior x (Event x a))
1102+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1103+ }
1104+
1105+#ifdef USE_TEMPLATE_HASKELL
1106+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1107+#endif
1108+data CoincidenceSubscribed x a
1109+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1110+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1111+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1112+ , coincidenceSubscribedHeight :: !(IORef Height)
1113+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1114+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1115+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1116+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1117+#ifdef DEBUG_NODEIDS
1118+ , coincidenceSubscribedNodeId :: Int
1119+#endif
1120+ }
1121+
1122+data Coincidence x a
1123+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1124+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1125+ }
1126+
1127+{-# NOINLINE newInvalidatorSwitch #-}
1128+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1129+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1130+
1131+{-# NOINLINE newInvalidatorPull #-}
1132+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1133+newInvalidatorPull p = return $! InvalidatorPull p
1134+
1135+instance HasSpiderTimeline x => Filterable (Event x) where
1136+ mapMaybe f = push $ return . f
1137+
1138+instance HasSpiderTimeline x => Align (Event x) where
1139+ nil = eventNever
1140+#if MIN_VERSION_these(0, 8, 0)
1141+instance HasSpiderTimeline x => Semialign (Event x) where
1142+#endif
1143+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1144+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1145+
1146+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1147+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1148+ | HoldDyn !(Hold x p)
1149+
1150+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1151+
1152+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1153+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1154+
1155+--TODO: Avoid the duplication between this and R.zipDynWith
1156+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1157+zipDynWith f da db =
1158+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1159+ ec = flip push eab $ \o -> do
1160+ (a, b) <- case o of
1161+ This (Identity a) -> do
1162+ b <- readBehaviorUntracked $ dynamicCurrent db
1163+ return (a, b)
1164+ That (Identity b) -> do
1165+ a <- readBehaviorUntracked $ dynamicCurrent da
1166+ return (a, b)
1167+ These (Identity a) (Identity b) -> return (a, b)
1168+ return $ Just $ Identity $ f a b
1169+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1170+
1171+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1172+buildDynamic readV0 v' = do
1173+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1174+ let !d = Dyn result
1175+ defer $ SomeDynInit d
1176+ return d
1177+
1178+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1179+unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ UnsafeDyn x
1180+ where x = (readV0, v')
1181+
1182+-- ResultM can read behaviors and events
1183+type ResultM = EventM
1184+
1185+{-# NOINLINE unsafeNewIORef #-}
1186+unsafeNewIORef :: a -> b -> IORef b
1187+unsafeNewIORef a b = unsafePerformIO $ do
1188+ touch a
1189+ newIORef b
1190+
1191+instance HasSpiderTimeline x => Functor (Event x) where
1192+ fmap f = push $ return . Just . f
1193+
1194+instance Functor (Behavior x) where
1195+ fmap f = pull . fmap f . readBehaviorTracked
1196+
1197+{-# INLINE push #-}
1198+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1199+push f e = cacheEvent (pushCheap f e)
1200+
1201+{-# INLINABLE pull #-}
1202+pull :: BehaviorM x a -> Behavior x a
1203+pull a = behaviorPull $ Pull
1204+ { pullCompute = a
1205+ , pullValue = unsafeNewIORef a Nothing
1206+#ifdef DEBUG_NODEIDS
1207+ , pullNodeId = unsafeNodeId a
1208+#endif
1209+ }
1210+
1211+{-# INLINABLE switch #-}
1212+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1213+switch a = eventSwitch $ Switch
1214+ { switchParent = a
1215+ , switchSubscribed = unsafeNewIORef a Nothing
1216+ }
1217+
1218+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1219+coincidence a = eventCoincidence $ Coincidence
1220+ { coincidenceParent = a
1221+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1222+ }
1223+
1224+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1225+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1226+run roots after = do
1227+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1228+ let t = spiderTimeline :: SpiderTimelineEnv x
1229+ result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1230+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1231+ occBefore <- liftIO $ do
1232+ occBefore <- readIORef occRef
1233+ writeIORef occRef $! DMap.insert k a occBefore
1234+ return occBefore
1235+ if DMap.null occBefore
1236+ then do scheduleRootClear occRef
1237+ return $ Just r
1238+ else return Nothing
1239+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1240+ propagate a subscribersRef
1241+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1242+ let go = do
1243+ delayed <- liftIO $ readIORef delayedRef
1244+ case IntMap.minViewWithKey delayed of
1245+ Nothing -> return ()
1246+ Just ((currentHeight, cur), future) -> do
1247+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1248+ putCurrentHeight $ Height currentHeight
1249+ liftIO $ writeIORef delayedRef $! future
1250+ sequence_ cur
1251+ go
1252+ go
1253+ putCurrentHeight maxBound
1254+ after
1255+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1256+ return result
1257+
1258+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1259+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1260+ height <- liftIO $ readIORef heightRef
1261+ currentHeight <- getCurrentHeight
1262+ case height `compare` currentHeight of
1263+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1264+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1265+ EQ -> a
1266+
1267+newtype Clear a = Clear (IORef (Maybe a))
1268+
1269+newtype IntClear a = IntClear (IORef (IntMap a))
1270+
1271+newtype RootClear k = RootClear (IORef (DMap k Identity))
1272+
1273+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1274+
1275+debugFinalize :: Bool
1276+debugFinalize = False
1277+
1278+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1279+mkWeakPtrWithDebug x debugNote = do
1280+ x' <- evaluate x
1281+ mkWeakPtr x' $
1282+ if debugFinalize
1283+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1284+ else Nothing
1285+
1286+type WeakList a = [Weak a]
1287+
1288+{-# INLINE withIncreasedDepth #-}
1289+#ifdef DEBUG
1290+withIncreasedDepth :: CanTrace x m => m a -> m a
1291+withIncreasedDepth a = do
1292+ spiderTimeline <- askSpiderTimelineEnv
1293+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1294+ result <- a
1295+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1296+ return result
1297+#else
1298+withIncreasedDepth :: m a -> m a
1299+withIncreasedDepth = id
1300+#endif
1301+
1302+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1303+
1304+{-# INLINE tracePropagate #-}
1305+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1306+tracePropagate p = traceWhen p debugPropagate
1307+
1308+{-# INLINE traceInvalidate #-}
1309+traceInvalidate :: String -> IO ()
1310+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1311+
1312+{-# INLINE traceWhen #-}
1313+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1314+traceWhen p b message = traceMWhen p b $ return message
1315+
1316+{-# INLINE traceMWhen #-}
1317+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1318+traceMWhen _ b getMessage = when b $ do
1319+ message <- getMessage
1320+#ifdef DEBUG
1321+ spiderTimeline <- askSpiderTimelineEnv
1322+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1323+#else
1324+ let d = 0
1325+#endif
1326+ liftIO $ putStrLn $ replicate d ' ' <> message
1327+
1328+whoCreatedIORef :: IORef a -> IO [String]
1329+whoCreatedIORef (IORef a) = whoCreated $! a
1330+
1331+#ifdef DEBUG_CYCLES
1332+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1333+groupByHead = \case
1334+ [] -> []
1335+ (x :| xs) : t -> case groupByHead t of
1336+ [] -> [(x, xs :| [])]
1337+ l@((y, yss) : t')
1338+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1339+ | otherwise -> (x, xs :| []) : l
1340+
1341+listsToForest :: Eq a => [[a]] -> Forest a
1342+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1343+#endif
1344+
1345+{-# INLINE propagateSubscriberHold #-}
1346+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1347+propagateSubscriberHold h a = do
1348+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1349+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1350+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1351+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1352+ case {-# SCC "apply" #-} apply a v of
1353+ Nothing -> return ()
1354+ Just v' -> do
1355+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1356+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1357+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1358+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1359+
1360+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1361+
1362+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1363+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1364+
1365+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1366+askInvalidator = do
1367+ (!m, _) <- BehaviorM ask
1368+ case m of
1369+ Nothing -> return Nothing
1370+ Just (!wi, _) -> return $ Just wi
1371+
1372+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1373+askParentsRef = do
1374+ (!m, _) <- BehaviorM ask
1375+ case m of
1376+ Nothing -> return Nothing
1377+ Just (_, !p) -> return $ Just p
1378+
1379+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1380+askBehaviorHoldInits = do
1381+ (_, !his) <- BehaviorM ask
1382+ return his
1383+
1384+{-# INLINE getDynHold #-}
1385+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1386+getDynHold d = do
1387+ mh <- liftIO $ readIORef $ unDyn d
1388+ case mh of
1389+ HoldDyn h -> return h
1390+ UnsafeDyn (readV0, v') -> do
1391+ holdInits <- getDeferralQueue
1392+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1393+ hold' v0 v'
1394+ BuildDyn (readV0, v') -> do
1395+ v0 <- liftIO $ runEventM readV0
1396+ hold' v0 v'
1397+ where
1398+ hold' v0 v' = do
1399+ h <- hold v0 v'
1400+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1401+ return h
1402+
1403+
1404+-- Always refers to 0
1405+{-# NOINLINE zeroRef #-}
1406+zeroRef :: IORef Height
1407+zeroRef = unsafePerformIO $ newIORef zeroHeight
1408+
1409+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1410+getRootSubscribed k r sub = do
1411+ mSubscribed <- readIORef $ rootSubscribed r
1412+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1413+ case DMap.lookup k mSubscribed of
1414+ Just subscribed -> {-# SCC "hitRoot" #-} do
1415+ sln <- subscribeRootSubscribed subscribed sub
1416+ occ <- getOcc
1417+ return (sln, subscribed, occ)
1418+ Nothing -> {-# SCC "missRoot" #-} do
1419+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1420+ let !cached = rootSubscribed r
1421+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1422+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1423+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1424+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1425+ writeIORef uninitRef $! uninit
1426+ let !subscribed = RootSubscribed
1427+ { rootSubscribedKey = k
1428+ , rootSubscribedCachedSubscribed = cached
1429+ , rootSubscribedOccurrence = getOcc
1430+ , rootSubscribedSubscribers = subs
1431+ , rootSubscribedUninit = uninit
1432+ , rootSubscribedWeakSelf = weakSelf
1433+#ifdef DEBUG_NODEIDS
1434+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1435+#endif
1436+ }
1437+ -- If we die at the same moment that all our children die, they will
1438+ -- try to clean us up but will fail because their Weak reference to us
1439+ -- will also be dead. So, if we are dying, check if there are any
1440+ -- children; since children don't bother cleaning themselves up if
1441+ -- their parents are already dead, I don't think there's a race
1442+ -- condition here. However, if there are any children, then we can
1443+ -- infer that we need to clean ourselves up, so we do.
1444+ finalCleanup = do
1445+ cs <- readIORef $ _weakBag_children subs
1446+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1447+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1448+ 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
1449+ occ <- getOcc
1450+ return (sln, subscribed, occ)
1451+
1452+#ifdef USE_TEMPLATE_HASKELL
1453+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1454+#endif
1455+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1456+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1457+ rootSubscribedUninit self
1458+ modifyIORef' cached $ DMap.delete k
1459+
1460+{-# INLINE subscribeRootSubscribed #-}
1461+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1462+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1463+
1464+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1465+
1466+data FanInt x a = FanInt
1467+ { _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
1468+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1469+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1470+ }
1471+
1472+newFanInt :: IO (FanInt x a)
1473+newFanInt = do
1474+ 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
1475+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1476+ occRef <- newIORef $ error "fanInt: no occurrence"
1477+ return $ FanInt
1478+ { _fanInt_subscribers = subscribers
1479+ , _fanInt_subscriptionRef = subscriptionRef
1480+ , _fanInt_occRef = occRef
1481+ }
1482+
1483+{-# NOINLINE unsafeNewFanInt #-}
1484+unsafeNewFanInt :: b -> FanInt x a
1485+unsafeNewFanInt b = unsafePerformIO $ do
1486+ touch b
1487+ newFanInt
1488+
1489+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1490+fanInt p =
1491+ let self = unsafeNewFanInt p
1492+ in EventSelectorInt $ \k -> Event $ \sub -> do
1493+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1494+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1495+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1496+ { subscriberPropagate = \m -> do
1497+ liftIO $ writeIORef (_fanInt_occRef self) m
1498+ scheduleIntClear $ _fanInt_occRef self
1499+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1500+ FastWeakBag.traverse b $ \s -> do
1501+ subscriberPropagate s v
1502+ , subscriberInvalidateHeight = \old -> do
1503+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1504+ FastWeakBag.traverse b $ \s -> do
1505+ subscriberInvalidateHeight s old
1506+ , subscriberRecalculateHeight = \new -> do
1507+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1508+ FastWeakBag.traverse b $ \s -> do
1509+ subscriberRecalculateHeight s new
1510+ }
1511+ liftIO $ do
1512+ writeIORef (_fanInt_subscriptionRef self) subscription
1513+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1514+ scheduleIntClear $ _fanInt_occRef self
1515+ liftIO $ do
1516+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1517+ Nothing -> do
1518+ b <- FastWeakBag.empty
1519+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1520+ return b
1521+ Just b -> return b
1522+ t <- liftIO $ FastWeakBag.insert sub b
1523+ currentOcc <- readIORef (_fanInt_occRef self)
1524+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1525+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1526+
1527+{-# INLINABLE getFanSubscribed #-}
1528+getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a)
1529+getFanSubscribed k f sub = do
1530+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1531+ case mSubscribed of
1532+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1533+ sln <- subscribeFanSubscribed k subscribed sub
1534+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1535+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1536+ Nothing -> {-# SCC "missFan" #-} do
1537+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1538+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1539+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1540+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1541+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1542+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1543+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1544+ occRef <- liftIO $ newIORef parentOcc
1545+ when (isJust parentOcc) $ scheduleClear occRef
1546+ let subscribed = FanSubscribed
1547+ { fanSubscribedCachedSubscribed = fanSubscribed f
1548+ , fanSubscribedOccurrence = occRef
1549+ , fanSubscribedParent = subscription
1550+ , fanSubscribedSubscribers = subscribersRef
1551+#ifdef DEBUG_NODEIDS
1552+ , fanSubscribedNodeId = unsafeNodeId f
1553+#endif
1554+ }
1555+ let !self = (k, subscribed)
1556+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1557+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1558+ liftIO $ writeIORef subscribedRef $! subscribed
1559+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1560+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1561+
1562+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1563+cleanupFanSubscribed (k, subscribed) = do
1564+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1565+ let reducedSubscribers = DMap.delete k subscribers
1566+ if DMap.null reducedSubscribers
1567+ then do
1568+ unsubscribe $ fanSubscribedParent subscribed
1569+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1570+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1571+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1572+
1573+{-# INLINE subscribeFanSubscribed #-}
1574+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1575+subscribeFanSubscribed k subscribed sub = do
1576+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1577+ case DMap.lookup k subscribers of
1578+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1579+ let !self = (k, subscribed)
1580+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1581+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1582+ 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
1583+ return sln
1584+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1585+
1586+{-# INLINABLE getSwitchSubscribed #-}
1587+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1588+getSwitchSubscribed s sub = do
1589+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1590+ case mSubscribed of
1591+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1592+ sln <- subscribeSwitchSubscribed subscribed sub
1593+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1594+ return (sln, subscribed, occ)
1595+ Nothing -> {-# SCC "missSwitch" #-} do
1596+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1597+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1598+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1599+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1600+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1601+ wiRef <- liftIO $ newIORef wi
1602+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1603+ holdInits <- getDeferralQueue
1604+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1605+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1606+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1607+ subscriptionRef <- liftIO $ newIORef subscription
1608+ occRef <- liftIO $ newIORef parentOcc
1609+ when (isJust parentOcc) $ scheduleClear occRef
1610+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1611+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1612+ let !subscribed = SwitchSubscribed
1613+ { switchSubscribedCachedSubscribed = switchSubscribed s
1614+ , switchSubscribedOccurrence = occRef
1615+ , switchSubscribedHeight = heightRef
1616+ , switchSubscribedSubscribers = subs
1617+ , switchSubscribedOwnInvalidator = i
1618+ , switchSubscribedOwnWeakInvalidator = wiRef
1619+ , switchSubscribedBehaviorParents = parentsRef
1620+ , switchSubscribedParent = switchParent s
1621+ , switchSubscribedCurrentParent = subscriptionRef
1622+ , switchSubscribedWeakSelf = weakSelf
1623+#ifdef DEBUG_NODEIDS
1624+ , switchSubscribedNodeId = unsafeNodeId s
1625+#endif
1626+ }
1627+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1628+ liftIO $ writeIORef subscribedRef $! subscribed
1629+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1630+ return (slnForSub, subscribed, parentOcc)
1631+
1632+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1633+cleanupSwitchSubscribed subscribed = do
1634+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1635+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1636+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1637+
1638+{-# INLINE subscribeSwitchSubscribed #-}
1639+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1640+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1641+
1642+{-# INLINABLE getCoincidenceSubscribed #-}
1643+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1644+getCoincidenceSubscribed c sub = do
1645+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1646+ case mSubscribed of
1647+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1648+ sln <- subscribeCoincidenceSubscribed subscribed sub
1649+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1650+ return (sln, subscribed, occ)
1651+ Nothing -> {-# SCC "missCoincidence" #-} do
1652+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1653+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1654+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1655+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1656+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1657+ (occ, height, mInnerSubd) <- case outerOcc of
1658+ Nothing -> return (Nothing, outerHeight, Nothing)
1659+ Just o -> do
1660+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1661+ return (occ, height, Just innerSubd)
1662+ occRef <- liftIO $ newIORef occ
1663+ when (isJust occ) $ scheduleClear occRef
1664+ heightRef <- liftIO $ newIORef height
1665+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1666+ scheduleClear innerSubdRef
1667+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1668+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1669+ let subscribed = CoincidenceSubscribed
1670+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1671+ , coincidenceSubscribedOccurrence = occRef
1672+ , coincidenceSubscribedHeight = heightRef
1673+ , coincidenceSubscribedSubscribers = subs
1674+ , coincidenceSubscribedOuter = subOuter
1675+ , coincidenceSubscribedOuterParent = outerSubscription
1676+ , coincidenceSubscribedInnerParent = innerSubdRef
1677+ , coincidenceSubscribedWeakSelf = weakSelf
1678+#ifdef DEBUG_NODEIDS
1679+ , coincidenceSubscribedNodeId = unsafeNodeId c
1680+#endif
1681+ }
1682+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1683+ liftIO $ writeIORef subscribedRef $! subscribed
1684+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1685+ return (slnForSub, subscribed, occ)
1686+
1687+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1688+cleanupCoincidenceSubscribed subscribed = do
1689+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1690+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1691+
1692+{-# INLINE subscribeCoincidenceSubscribed #-}
1693+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1694+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1695+
1696+{-# INLINE mergeG #-}
1697+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1698+ => (forall a. q a -> Event x (v a))
1699+ -> Dynamic x (PatchDMap k q) -> Event x (DMap k v)
1700+mergeG nt d = cacheEvent (mergeCheap nt d)
1701+
1702+{-# INLINE mergeWithMove #-}
1703+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1704+ => (forall a. q a -> Event x (v a))
1705+ -> Dynamic x (PatchDMapWithMove k q) -> Event x (DMap k v)
1706+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1707+
1708+{-# INLINE [1] mergeCheap #-}
1709+mergeCheap
1710+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1711+ => (forall a. q a -> Event x (v a))
1712+ -> Dynamic x (PatchDMap k q)
1713+ -> Event x (DMap k v)
1714+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1715+ where
1716+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1717+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1718+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1719+ (mOldSubd, newPs) <- case me of
1720+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1721+ Just e -> do
1722+ let s = subscriber $ return k
1723+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1724+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1725+ let newParent = MergeSubscribedParent subscription
1726+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1727+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1728+ forM_ mOldSubd $ \oldSubd -> do
1729+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1730+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1731+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1732+ foldM f ([], oldParents) $ DMap.toList p
1733+
1734+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1735+ getInitialSubscribers initialParents subscriber = do
1736+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1737+ let s = subscriber $ return k
1738+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1739+ height <- liftIO $ getEventSubscribedHeight parentSubd
1740+ return (fmap (\x -> k :=> x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1741+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1742+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1743+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1744+ )
1745+
1746+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1747+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1748+
1749+{-# INLINE [1] mergeCheapWithMove #-}
1750+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1751+ => (forall a. q a -> Event x (v a))
1752+ -> Dynamic x (PatchDMapWithMove k q)
1753+ -> Event x (DMap k v)
1754+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1755+ where
1756+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1757+ updateMe subscriber heightBagRef oldParents p = do
1758+ -- Prepare new parents for insertion
1759+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1760+ subscribeParent k e = do
1761+ keyRef <- liftIO $ newIORef k
1762+ let s = subscriber $ liftIO $ readIORef keyRef
1763+ subscription@(EventSubscription _ subd) <- subscribe e s
1764+ liftIO $ do
1765+ newParentHeight <- getEventSubscribedHeight subd
1766+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1767+ return $ MergeSubscribedParentWithMove subscription keyRef
1768+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1769+ -- Collect old parents for deletion and update the keys of moved parents
1770+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1771+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1772+ Nothing -> do
1773+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1774+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1775+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1776+ Just toKey -> do
1777+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1778+ return Nothing
1779+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1780+ return (toDelete, applyAlways p' oldParents)
1781+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1782+ getInitialSubscribers initialParents subscriber = do
1783+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1784+ keyRef <- liftIO $ newIORef k
1785+ let s = subscriber $ liftIO $ readIORef keyRef
1786+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1787+ height <- liftIO $ getEventSubscribedHeight parentSubd
1788+ return (fmap (\x -> k :=> x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1789+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1790+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1791+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1792+ )
1793+
1794+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1795+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1796+
1797+type MergeUpdateFunc k v x p s
1798+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1799+ -> IORef HeightBag
1800+ -> DMap k s
1801+ -> p
1802+ -> EventM x ([EventSubscription x], DMap k s)
1803+
1804+type MergeInitFunc k v q x s
1805+ = DMap k q
1806+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1807+ -> EventM x (DMap k v, [Height], DMap k s)
1808+
1809+type MergeDestroyFunc k s
1810+ = DMap k s
1811+ -> IO ()
1812+
1813+data Merge x k v s = Merge
1814+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1815+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1816+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1817+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1818+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1819+ }
1820+
1821+invalidateMergeHeight :: Merge x k v s -> IO ()
1822+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1823+
1824+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1825+invalidateMergeHeight' heightRef sub = do
1826+ oldHeight <- readIORef heightRef
1827+ 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
1828+ writeIORef heightRef $! invalidHeight
1829+ subscriberInvalidateHeight sub oldHeight
1830+
1831+revalidateMergeHeight :: Merge x k v s -> IO ()
1832+revalidateMergeHeight m = do
1833+ currentHeight <- readIORef $ _merge_heightRef m
1834+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1835+ heights <- readIORef $ _merge_heightBagRef m
1836+ parents <- readIORef $ _merge_parentsRef m
1837+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1838+ case heightBagSize heights `compare` DMap.size parents of
1839+ LT -> return ()
1840+ EQ -> do
1841+ let height = succHeight $ heightBagMax heights
1842+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1843+ writeIORef (_merge_heightRef m) $! height
1844+ subscriberRecalculateHeight (_merge_sub m) height
1845+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1846+
1847+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1848+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1849+ vals <- liftIO $ readIORef $ _merge_accumRef m
1850+ 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
1851+ --TODO: Assert that m is not empty
1852+ subscriberPropagate (_merge_sub m) vals
1853+
1854+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1855+mergeSubscriber m getKey = Subscriber
1856+ { subscriberPropagate = \a -> do
1857+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1858+ k <- getKey
1859+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1860+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1861+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1862+ when (DMap.null oldM) $ do -- Only schedule the firing once
1863+ height <- liftIO $ readIORef $ _merge_heightRef m
1864+ --TODO: assertions about height
1865+ currentHeight <- getCurrentHeight
1866+ when (height <= currentHeight) $ do
1867+ if height /= invalidHeight
1868+ then do
1869+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1870+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1871+ else liftIO $ do
1872+#ifdef DEBUG_CYCLES
1873+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1874+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1875+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1876+#else
1877+ let cycleInfo = ""
1878+#endif
1879+ error $ "Causality loop found" <> cycleInfo
1880+ scheduleMergeSelf m height
1881+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1882+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1883+ invalidateMergeHeight m
1884+ , subscriberRecalculateHeight = \new -> do
1885+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1886+ revalidateMergeHeight m
1887+ }
1888+
1889+--TODO: Be able to run as much of this as possible promptly
1890+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1891+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1892+ where updateMe = do
1893+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1894+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1895+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1896+ return subscriptionsToKill
1897+
1898+{-# INLINE mergeGCheap' #-}
1899+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1900+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> Dynamic x p -> Event x (DMap k v)
1901+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1902+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1903+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1904+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1905+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1906+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1907+ let m = Merge
1908+ { _merge_parentsRef = parentsRef
1909+ , _merge_heightBagRef = heightBagRef
1910+ , _merge_heightRef = heightRef
1911+ , _merge_sub = sub
1912+ , _merge_accumRef = accumRef
1913+ }
1914+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1915+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1916+ myHeight = if invalidHeight `elem` heights
1917+ then invalidHeight
1918+ else succHeight $ heightBagMax myHeightBag
1919+ currentHeight <- getCurrentHeight
1920+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1921+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1922+ else (Nothing, dm)
1923+ unless (DMap.null accum) $ do
1924+ scheduleMergeSelf m myHeight
1925+ liftIO $ writeIORef accumRef $! accum
1926+ liftIO $ writeIORef heightRef $! myHeight
1927+ liftIO $ writeIORef heightBagRef $! myHeightBag
1928+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1929+ liftIO $ writeIORef parentsRef $! initialParentState
1930+ defer $ SomeMergeInit $ do
1931+ let s = Subscriber
1932+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1933+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1934+ defer $ updateMerge m updateFunc a
1935+ , subscriberInvalidateHeight = \_ -> return ()
1936+ , subscriberRecalculateHeight = \_ -> return ()
1937+ }
1938+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1939+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1940+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1941+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1942+ -- its subscription.
1943+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1944+ let unsubscribeAll = destroy =<< readIORef parentsRef
1945+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1946+ , occ
1947+ )
1948+
1949+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1950+mergeInt = cacheEvent . mergeIntCheap
1951+
1952+{-# INLINABLE mergeIntCheap #-}
1953+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1954+mergeIntCheap d = Event $ \sub -> do
1955+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1956+ accum <- liftIO $ FastMutableIntMap.newEmpty
1957+ heightRef <- liftIO $ newIORef zeroHeight
1958+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1959+ parents <- liftIO $ FastMutableIntMap.newEmpty
1960+ let scheduleSelf = do
1961+ height <- liftIO $ readIORef $ heightRef
1962+ scheduleMerge' height heightRef $ do
1963+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1964+ subscriberPropagate sub vals
1965+ invalidateMyHeight = do
1966+ invalidateMergeHeight' heightRef sub
1967+ recalculateMyHeight = do
1968+ currentHeight <- readIORef heightRef
1969+ 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?
1970+ heights <- readIORef heightBagRef
1971+ numParents <- FastMutableIntMap.size parents
1972+ case heightBagSize heights `compare` numParents of
1973+ LT -> return ()
1974+ EQ -> do
1975+ let height = succHeight $ heightBagMax heights
1976+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1977+ writeIORef heightRef $! height
1978+ subscriberRecalculateHeight sub height
1979+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1980+ mySubscriber k = Subscriber
1981+ { subscriberPropagate = \a -> do
1982+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1983+ liftIO $ FastMutableIntMap.insert accum k a
1984+ when wasEmpty scheduleSelf
1985+ , subscriberInvalidateHeight = \old -> do
1986+ modifyIORef' heightBagRef $ heightBagRemove old
1987+ invalidateMyHeight
1988+ , subscriberRecalculateHeight = \new -> do
1989+ modifyIORef' heightBagRef $ heightBagAdd new
1990+ recalculateMyHeight
1991+ }
1992+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
1993+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
1994+ liftIO $ do
1995+ forM_ parentOcc $ FastMutableIntMap.insert accum k
1996+ FastMutableIntMap.insert parents k subscription
1997+ height <- getEventSubscribedHeight parentSubd
1998+ if height == invalidHeight
1999+ then writeIORef heightRef invalidHeight
2000+ else do
2001+ modifyIORef' heightBagRef $ heightBagAdd height
2002+ modifyIORef' heightRef $ \oldHeight ->
2003+ if oldHeight == invalidHeight
2004+ then invalidHeight
2005+ else max (succHeight height) oldHeight
2006+ myHeight <- liftIO $ readIORef heightRef
2007+ currentHeight <- getCurrentHeight
2008+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2009+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2010+ then if isEmpty
2011+ then return Nothing
2012+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2013+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2014+ return Nothing
2015+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2016+ defer $ SomeMergeInit $ do
2017+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2018+ where
2019+ u = do
2020+ let f k newParent = do
2021+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2022+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2023+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2024+ return subscription
2025+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2026+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2027+ liftIO $ for_ oldParents $ \oldParent -> do
2028+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2029+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2030+ return $ IntMap.elems oldParents
2031+ let s = Subscriber
2032+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2033+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2034+ defer $ updateMe a
2035+ , subscriberInvalidateHeight = \_ -> return ()
2036+ , subscriberRecalculateHeight = \_ -> return ()
2037+ }
2038+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2039+ forM_ change $ \c -> defer $ updateMe c
2040+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2041+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2042+ -- its subscription.
2043+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2044+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2045+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2046+ , occ
2047+ )
2048+
2049+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2050+
2051+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2052+fan e =
2053+ let f = Fan
2054+ { fanParent = e
2055+ , fanSubscribed = unsafeNewIORef e Nothing
2056+ }
2057+ in EventSelector $ \k -> eventFan k f
2058+
2059+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2060+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2061+ holdInits <- liftIO $ readIORef holdInitRef
2062+ dynInits <- liftIO $ readIORef dynInitRef
2063+ mergeInits <- liftIO $ readIORef mergeInitRef
2064+ unless (null holdInits && null dynInits && null mergeInits) $ do
2065+ liftIO $ writeIORef holdInitRef []
2066+ liftIO $ writeIORef dynInitRef []
2067+ liftIO $ writeIORef mergeInitRef []
2068+ mapM_ initHold holdInits
2069+ mapM_ initDyn dynInits
2070+ mapM_ unSomeMergeInit mergeInits
2071+ runHoldInits holdInitRef dynInitRef mergeInitRef
2072+
2073+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2074+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2075+
2076+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2077+initDyn (SomeDynInit d) = void $ getDynHold d
2078+
2079+newEventEnv :: IO (EventEnv x)
2080+newEventEnv = do
2081+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2082+ holdInitRef <- newIORef []
2083+ dynInitRef <- newIORef []
2084+ mergeUpdateRef <- newIORef []
2085+ mergeInitRef <- newIORef []
2086+ heightRef <- newIORef zeroHeight
2087+ toClearRef <- newIORef []
2088+ toClearIntRef <- newIORef []
2089+ toClearRootRef <- newIORef []
2090+ coincidenceInfosRef <- newIORef []
2091+ delayedRef <- newIORef IntMap.empty
2092+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2093+
2094+clearEventEnv :: EventEnv x -> IO ()
2095+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2096+ writeIORef toAssignRef []
2097+ writeIORef holdInitRef []
2098+ writeIORef dynInitRef []
2099+ writeIORef mergeUpdateRef []
2100+ writeIORef mergeInitRef []
2101+ writeIORef heightRef zeroHeight
2102+ writeIORef toClearRef []
2103+ writeIORef toClearIntRef []
2104+ writeIORef toClearRootRef []
2105+ writeIORef coincidenceInfosRef []
2106+ writeIORef delayedRef IntMap.empty
2107+
2108+-- | Run an event action outside of a frame
2109+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2110+runFrame a = SpiderHost $ do
2111+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2112+ let go = do
2113+ result <- a
2114+ 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
2115+ return result
2116+ result <- runEventM go
2117+ toClear <- readIORef $ eventEnvClears env
2118+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2119+ toClearInt <- readIORef $ eventEnvIntClears env
2120+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2121+ toClearRoot <- readIORef $ eventEnvRootClears env
2122+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2123+ toAssign <- readIORef $ eventEnvAssignments env
2124+ toReconnectRef <- newIORef []
2125+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2126+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2127+ writeIORef vRef v
2128+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2129+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2130+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2131+ writeIORef (eventEnvMergeUpdates env) []
2132+ when debugPropagate $ putStrLn "Updating merges"
2133+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2134+ when debugPropagate $ putStrLn "Updating merges done"
2135+ toReconnect <- readIORef toReconnectRef
2136+ clearEventEnv env
2137+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2138+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2139+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2140+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2141+ finalize wi
2142+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2143+ wi' <- mkWeakPtrWithDebug i "wi'"
2144+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2145+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2146+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2147+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2148+ 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
2149+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2150+ sub <- newSubscriberSwitch subscribed
2151+ 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
2152+ {-
2153+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2154+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2155+ EventRoot _ -> "EventRoot"
2156+ EventNever -> "EventNever"
2157+ _ -> "something else"
2158+ -}
2159+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2160+ return oldSubscription
2161+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2162+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2163+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2164+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2165+ parentHeight <- getEventSubscribedHeight subd'
2166+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2167+ when (parentHeight /= myHeight) $ do
2168+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2169+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2170+ 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
2171+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2172+ unsubscribe subscription
2173+ mapM_ invalidateCoincidenceHeight mcs
2174+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2175+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2176+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2177+ height <- calculateSwitchHeight subscribed
2178+ updateSwitchHeight height subscribed
2179+ return result
2180+
2181+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2182+
2183+{-# INLINE zeroHeight #-}
2184+zeroHeight :: Height
2185+zeroHeight = Height 0
2186+
2187+{-# INLINE invalidHeight #-}
2188+invalidHeight :: Height
2189+invalidHeight = Height (-1000)
2190+
2191+#ifdef DEBUG_CYCLES
2192+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2193+{-# INLINE invalidHeightBeingTraversed #-}
2194+invalidHeightBeingTraversed :: Height
2195+invalidHeightBeingTraversed = Height (-1001)
2196+#endif
2197+
2198+{-# INLINE succHeight #-}
2199+succHeight :: Height -> Height
2200+succHeight h@(Height a) =
2201+ if h == invalidHeight
2202+ then invalidHeight
2203+ else Height $ succ a
2204+
2205+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2206+invalidateCoincidenceHeight subscribed = do
2207+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2208+ when (oldHeight /= invalidHeight) $ do
2209+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2210+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2211+
2212+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2213+updateSwitchHeight new subscribed = do
2214+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2215+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2216+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2217+ writeIORef (switchSubscribedHeight subscribed) $! new
2218+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2219+
2220+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2221+recalculateCoincidenceHeight subscribed = do
2222+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2223+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2224+ height <- calculateCoincidenceHeight subscribed
2225+ when (height /= invalidHeight) $ do
2226+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2227+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2228+
2229+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2230+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2231+
2232+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2233+calculateCoincidenceHeight subscribed = do
2234+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2235+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2236+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2237+
2238+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2239+
2240+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2241+invalidate toReconnectRef wis = do
2242+ forM_ wis $ \wi -> do
2243+ mi <- deRefWeak wi
2244+ case mi of
2245+ Nothing -> do
2246+ traceInvalidate "invalidate Dead"
2247+ return () --TODO: Should we clean this up here?
2248+ Just i -> do
2249+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2250+ case i of
2251+ InvalidatorPull p -> do
2252+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2253+ mVal <- readIORef $ pullValue p
2254+ forM_ mVal $ \val -> do
2255+ writeIORef (pullValue p) Nothing
2256+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2257+ InvalidatorSwitch subscribed -> do
2258+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2259+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2260+ 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
2261+
2262+--------------------------------------------------------------------------------
2263+-- Reflex integration
2264+--------------------------------------------------------------------------------
2265+
2266+-- | Designates the default, global Spider timeline
2267+data SpiderTimeline x
2268+type role SpiderTimeline nominal
2269+
2270+-- | The default, global Spider environment
2271+type Spider = SpiderTimeline Global
2272+
2273+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2274+ {-# INLINABLE sample #-}
2275+ sample (SpiderBehavior b) = readBehaviorUntracked b
2276+
2277+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2278+ {-# INLINABLE hold #-}
2279+ hold = holdSpiderEventM
2280+ {-# INLINABLE holdDyn #-}
2281+ holdDyn = holdDynSpiderEventM
2282+ {-# INLINABLE holdIncremental #-}
2283+ holdIncremental = holdIncrementalSpiderEventM
2284+ {-# INLINABLE buildDynamic #-}
2285+ buildDynamic = buildDynamicSpiderEventM
2286+ {-# INLINABLE headE #-}
2287+ headE = R.slowHeadE
2288+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2289+
2290+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2291+ {-# INLINABLE sample #-}
2292+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2293+
2294+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2295+ {-# INLINABLE sample #-}
2296+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2297+
2298+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2299+ {-# INLINABLE hold #-}
2300+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2301+ {-# INLINABLE holdDyn #-}
2302+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2303+ {-# INLINABLE holdIncremental #-}
2304+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2305+ {-# INLINABLE buildDynamic #-}
2306+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2307+ {-# INLINABLE headE #-}
2308+ headE = R.slowHeadE
2309+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2310+
2311+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2312+ {-# INLINE return #-}
2313+ return = pure
2314+ {-# INLINE (>>=) #-}
2315+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2316+ {-# INLINE (>>) #-}
2317+ (>>) = (*>)
2318+ {-# INLINE fail #-}
2319+ fail _ = error "Dynamic does not support 'fail'"
2320+
2321+{-# INLINABLE newJoinDyn #-}
2322+newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2323+newJoinDyn d =
2324+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2325+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2326+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2327+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2328+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2329+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2330+
2331+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2332+ fmap = mapDynamicSpider
2333+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2334+
2335+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2336+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2337+{-# INLINE [1] mapDynamicSpider #-}
2338+
2339+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2340+ pure = SpiderDynamic . dynamicConst
2341+#if MIN_VERSION_base(4,10,0)
2342+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2343+#endif
2344+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2345+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2346+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2347+
2348+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2349+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2350+
2351+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2352+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2353+
2354+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2355+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2356+
2357+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2358+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2359+
2360+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2361+ {-# INLINABLE hold #-}
2362+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2363+ {-# INLINABLE holdDyn #-}
2364+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2365+ {-# INLINABLE holdIncremental #-}
2366+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2367+ {-# INLINABLE buildDynamic #-}
2368+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2369+ {-# INLINABLE headE #-}
2370+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2371+
2372+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2373+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2374+
2375+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2376+ {-# INLINABLE hold #-}
2377+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2378+ {-# INLINABLE holdDyn #-}
2379+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2380+ {-# INLINABLE holdIncremental #-}
2381+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2382+ {-# INLINABLE buildDynamic #-}
2383+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2384+ {-# INLINABLE headE #-}
2385+ headE = R.slowHeadE
2386+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2387+
2388+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2389+ {-# INLINABLE sample #-}
2390+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2391+
2392+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2393+ {-# INLINABLE sample #-}
2394+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2395+
2396+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2397+ {-# INLINABLE hold #-}
2398+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2399+ {-# INLINABLE holdDyn #-}
2400+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2401+ {-# INLINABLE holdIncremental #-}
2402+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2403+ {-# INLINABLE buildDynamic #-}
2404+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2405+ {-# INLINABLE headE #-}
2406+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2407+
2408+--------------------------------------------------------------------------------
2409+-- Deprecated items
2410+--------------------------------------------------------------------------------
2411+
2412+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2413+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2414+type SpiderEnv = SpiderTimeline
2415+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2416+ {-# INLINABLE subscribeEvent #-}
2417+ subscribeEvent e = SpiderHostFrame $ do
2418+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2419+ val <- liftIO $ newIORef Nothing
2420+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2421+ { subscriberPropagate = \a -> do
2422+ liftIO $ writeIORef val $ Just a
2423+ scheduleClear val
2424+ , subscriberInvalidateHeight = \_ -> return ()
2425+ , subscriberRecalculateHeight = \_ -> return ()
2426+ }
2427+ return $ SpiderEventHandle
2428+ { spiderEventHandleSubscription = subscription
2429+ , spiderEventHandleValue = val
2430+ }
2431+
2432+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2433+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2434+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2435+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2436+
2437+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2438+ {-# NOINLINE readEvent #-}
2439+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2440+ result <- readIORef $ spiderEventHandleValue h
2441+ touch h
2442+ return result
2443+
2444+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2445+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2446+ newFanEventWithTrigger f = SpiderHost $ do
2447+ es <- newFanEventWithTriggerIO f
2448+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2449+
2450+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2451+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2452+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2453+ es <- newFanEventWithTriggerIO f
2454+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2455+
2456+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2457+ {-# INLINABLE subscribeEvent #-}
2458+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2459+
2460+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2461+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2462+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2463+ runHostFrame = runFrame . runSpiderHostFrame
2464+
2465+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2466+unsafeNewSpiderTimelineEnv = do
2467+ lock <- newMVar ()
2468+ env <- newEventEnv
2469+#ifdef DEBUG
2470+ depthRef <- newIORef 0
2471+#endif
2472+ return $ SpiderTimelineEnv
2473+ { _spiderTimeline_lock = lock
2474+ , _spiderTimeline_eventEnv = env
2475+#ifdef DEBUG
2476+ , _spiderTimeline_depth = depthRef
2477+#endif
2478+ }
2479+
2480+-- | Create a new SpiderTimelineEnv
2481+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2482+newSpiderTimeline = withSpiderTimeline (pure . Some)
2483+
2484+data LocalSpiderTimeline (x :: Type) s
2485+
2486+instance Reifies s (SpiderTimelineEnv x) =>
2487+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2488+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2489+
2490+localSpiderTimeline
2491+ :: Proxy s
2492+ -> SpiderTimelineEnv x
2493+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2494+localSpiderTimeline _ = unsafeCoerce
2495+
2496+-- | Pass a new timeline to the given function.
2497+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2498+withSpiderTimeline k = do
2499+ env <- unsafeNewSpiderTimelineEnv
2500+ reify env $ \s -> k $ localSpiderTimeline s env
2501+
2502+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2503+
2504+type ComputeM = EventM
2505+
2506+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2507+
2508+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2509+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2510+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2511+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2512+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2513+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2514+ type PullM (SpiderTimeline x) = SpiderPullM x
2515+ type PushM (SpiderTimeline x) = SpiderPushM x
2516+ {-# INLINABLE never #-}
2517+ never = SpiderEvent eventNever
2518+ {-# INLINABLE constant #-}
2519+ constant = SpiderBehavior . behaviorConst
2520+ {-# INLINE push #-}
2521+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2522+ {-# INLINE pushCheap #-}
2523+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2524+ {-# INLINABLE pull #-}
2525+ pull = SpiderBehavior . pull . coerce
2526+ {-# INLINABLE mergeG #-}
2527+ mergeG
2528+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2529+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2530+ -> DMap k q
2531+ -> R.Event (SpiderTimeline x) (DMap k v)
2532+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2533+ {-# INLINABLE fan #-}
2534+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2535+ {-# INLINABLE switch #-}
2536+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2537+ {-# INLINABLE coincidence #-}
2538+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2539+ {-# INLINABLE current #-}
2540+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2541+ {-# INLINABLE updated #-}
2542+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2543+ {-# INLINABLE unsafeBuildDynamic #-}
2544+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2545+ {-# INLINABLE unsafeBuildIncremental #-}
2546+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2547+ {-# INLINABLE mergeIncrementalG #-}
2548+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2549+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2550+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2551+ {-# INLINABLE currentIncremental #-}
2552+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2553+ {-# INLINABLE updatedIncremental #-}
2554+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2555+ {-# INLINABLE incrementalToDynamic #-}
2556+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2557+ c <- readBehaviorUntracked $ dynamicCurrent i
2558+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2559+ eventCoercion Coercion = Coercion
2560+ behaviorCoercion Coercion = Coercion
2561+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2562+ {-# INLINABLE mergeIntIncremental #-}
2563+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2564+ {-# INLINABLE fanInt #-}
2565+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2566+
2567+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2568+
2569+data SpiderEventHandle x a = SpiderEventHandle
2570+ { spiderEventHandleSubscription :: EventSubscription x
2571+ , spiderEventHandleValue :: IORef (Maybe a)
2572+ }
2573+
2574+instance MonadRef (EventM x) where
2575+ type Ref (EventM x) = Ref IO
2576+ {-# INLINABLE newRef #-}
2577+ {-# INLINABLE readRef #-}
2578+ {-# INLINABLE writeRef #-}
2579+ newRef = liftIO . newRef
2580+ readRef = liftIO . readRef
2581+ writeRef r a = liftIO $ writeRef r a
2582+
2583+instance MonadAtomicRef (EventM x) where
2584+ {-# INLINABLE atomicModifyRef #-}
2585+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2586+
2587+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2588+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2589+
2590+instance Monad (SpiderHost x) where
2591+ {-# INLINABLE (>>=) #-}
2592+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2593+ {-# INLINABLE (>>) #-}
2594+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2595+ {-# INLINABLE return #-}
2596+ return x = SpiderHost $ return x
2597+ {-# INLINABLE fail #-}
2598+ fail s = SpiderHost $ fail s
2599+
2600+-- | Run an action affecting the global Spider timeline; this will be guarded by
2601+-- a mutex for that timeline
2602+runSpiderHost :: SpiderHost Global a -> IO a
2603+runSpiderHost (SpiderHost a) = a
2604+
2605+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2606+-- mutex for that timeline
2607+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2608+runSpiderHostForTimeline (SpiderHost a) _ = a
2609+
2610+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2611+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2612+
2613+instance Monad (SpiderHostFrame x) where
2614+ {-# INLINABLE (>>=) #-}
2615+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2616+ {-# INLINABLE (>>) #-}
2617+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2618+ {-# INLINABLE return #-}
2619+ return x = SpiderHostFrame $ return x
2620+ {-# INLINABLE fail #-}
2621+ fail s = SpiderHostFrame $ fail s
2622+
2623+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2624+ notReadyUntil _ = pure ()
2625+ notReady = pure ()
2626+
2627+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2628+newEventWithTriggerIO f = do
2629+ es <- newFanEventWithTriggerIO $ \Refl -> f
2630+ return $ select es Refl
2631+
2632+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2633+newFanEventWithTriggerIO f = do
2634+ occRef <- newIORef DMap.empty
2635+ subscribedRef <- newIORef DMap.empty
2636+ let !r = Root
2637+ { rootOccurrence = occRef
2638+ , rootSubscribed = subscribedRef
2639+ , rootInit = f
2640+ }
2641+ return $ EventSelector $ \k -> eventRoot k r
2642+
2643+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2644+
2645+instance MonadRef (SpiderHost x) where
2646+ type Ref (SpiderHost x) = Ref IO
2647+ newRef = SpiderHost . newRef
2648+ readRef = SpiderHost . readRef
2649+ writeRef r = SpiderHost . writeRef r
2650+
2651+instance MonadAtomicRef (SpiderHost x) where
2652+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2653+
2654+instance MonadRef (SpiderHostFrame x) where
2655+ type Ref (SpiderHostFrame x) = Ref IO
2656+ newRef = SpiderHostFrame . newRef
2657+ readRef = SpiderHostFrame . readRef
2658+ writeRef r = SpiderHostFrame . writeRef r
2659+
2660+instance MonadAtomicRef (SpiderHostFrame x) where
2661+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2662+
2663+instance PrimMonad (SpiderHostFrame x) where
2664+ type PrimState (SpiderHostFrame x) = PrimState IO
2665+ primitive = SpiderHostFrame . EventM . primitive
src/Reflex/Time.hsnew file+384
@@ -0,0 +1,384 @@
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.hsnew file+148
@@ -0,0 +1,148 @@
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.hsnew file+50
@@ -0,0 +1,50 @@
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.hsnew file+44
@@ -0,0 +1,44 @@
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.hsnew file+50
@@ -0,0 +1,50 @@
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 return 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.hsnew file+132
@@ -0,0 +1,132 @@
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.hsnew file+101
@@ -0,0 +1,101 @@
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+import Data.Coerce
31+
32+main :: IO ()
33+main = do
34+ ref <- newIORef Nothing
35+ hostPerf ref
36+ readIORef ref >>= maybe exitFailure (putStrLn . ("Result " <>) . show)
37+
38+hostPerf :: IORef (Maybe Int) -> IO ()
39+hostPerf ref = S.runSpiderHost $ do
40+ ---- body
41+ liftIO $ putStrLn "#creating triggers"
42+ (response', responseTrigger) <- Host.newEventWithTriggerRef
43+ (eadd', addTriggerRef) <- Host.newEventWithTriggerRef
44+ let response = S.unSpiderEvent response'
45+ eadd = S.unSpiderEvent eadd'
46+ liftIO $ putStrLn "#creating event graph"
47+ eventToPerform <- Host.runHostFrame $ do
48+ (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity))
49+ <- S.SpiderHostFrame
50+ $ fmap ( S.mergeG coerce
51+ . S.dynamicHold)
52+ $ S.hold DMap.empty
53+ -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained
54+ $ (\e -> S.Event $ \sub -> do
55+ (s, o) <- S.subscribeAndRead e $ sub
56+ { S.subscriberPropagate = S.subscriberPropagate sub
57+ }
58+ return (s, o))
59+ $ runIdentity <$> S.select
60+ (S.fan $ S.pushCheap (return . Just . mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e)) response)
61+ (WrapArg Request)
62+ return $ alignWith (mergeThese (<>))
63+ (flip S.pushCheap eadd $ \_ -> return $ Just $ DMap.singleton Request $ do
64+ liftIO $ putStrLn "#eadd fired"
65+ return $ PatchDMap $ DMap.singleton (Const2 (1 :: Int)) $ ComposeMaybe $ Just
66+ $ S.pushCheap (return . Just . DMap.singleton Action . (\_ -> liftIO (writeIORef ref (Just 1)))) $ eadd)
67+ (flip S.pushCheap reqMap $ \m -> return $ Just $ mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m)
68+ ---- epilogue
69+ eventToPerformHandle <- Host.subscribeEvent (S.SpiderEvent eventToPerform)
70+ liftIO $ putStrLn "#performing GC" >> performMajorGC
71+ liftIO $ putStrLn "#attempting to fire eadd"
72+ mAddTrigger <- readRef addTriggerRef
73+ forM_ mAddTrigger $ \t -> replicateM_ 2 $ do
74+ liftIO $ putStrLn "#firing eadd"
75+ mToPerform <- Host.fireEventsAndRead [t :=> Identity ()] $ sequence =<< Host.readEvent eventToPerformHandle
76+ case mToPerform of
77+ Nothing -> return ()
78+ Just toPerform -> do
79+ responses <- Host.runHostFrame $ DMap.traverseWithKey (\_ v -> Identity <$> v) toPerform
80+ mrt <- readRef responseTrigger
81+ let followupEventTriggers = case mrt of
82+ Just rt -> [rt :=> Identity responses]
83+ Nothing -> []
84+ Host.fireEventsAndRead followupEventTriggers $ return ()
85+ return ()
86+ return ()
87+
88+data Tell a where
89+ Action :: Tell ()
90+ Request :: Tell (PatchDMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) (S.Event S.Global))
91+
92+instance GEq Tell where
93+ geq Action Action = Just Refl
94+ geq Request Request = Just Refl
95+ geq _ _ = Nothing
96+
97+instance GCompare Tell where
98+ gcompare Action Action = GEQ
99+ gcompare Request Request = GEQ
100+ gcompare Action Request = GLT
101+ gcompare Request Action = GGT
test/QueryT.hsnew file+138
@@ -0,0 +1,138 @@
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.hsnew file+369
@@ -0,0 +1,369 @@
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.hsnew file+72
@@ -0,0 +1,72 @@
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.hsnew file+135
@@ -0,0 +1,135 @@
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.hsnew file+66
@@ -0,0 +1,66 @@
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.hsnew file+257
@@ -0,0 +1,257 @@
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.hsnew file+346
@@ -0,0 +1,346 @@
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.hsnew file+52
@@ -0,0 +1,52 @@
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.hsnew file+169
@@ -0,0 +1,169 @@
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.hsnew file+74
@@ -0,0 +1,74 @@
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+8−3
@@ -1,7 +1,7 @@
1module Main where
1module Main where
2
2
3import Control.Monad
3import Control.Monad
4−import Language.Haskell.HLint (hlint)
4+import Language.Haskell.HLint3 (hlint)
5import System.Directory
5import System.Directory
6import System.Exit (exitFailure, exitSuccess)
6import System.Exit (exitFailure, exitSuccess)
7import System.FilePath
7import System.FilePath
@@ -22,8 +22,6 @@ main = do
22 , "--ignore=Use unless"
22 , "--ignore=Use unless"
23 , "--ignore=Reduce duplication"
23 , "--ignore=Reduce duplication"
24 , "--cpp-define=USE_TEMPLATE_HASKELL"
24 , "--cpp-define=USE_TEMPLATE_HASKELL"
25− , "--ignore=Use tuple-section"
26− , "--ignore=Unused LANGUAGE pragma" -- hlint3 falsely believes that TypeOperators is not needed
27 ]
25 ]
28 recurseInto = and <$> sequence
26 recurseInto = and <$> sequence
29 [ fileType ==? Directory
27 [ fileType ==? Directory
@@ -31,9 +29,16 @@ main = do
31 ]
29 ]
32 matchFile = and <$> sequence
30 matchFile = and <$> sequence
33 [ extension ==? ".hs"
31 [ extension ==? ".hs"
32+ , let notElem' = liftOp notElem
33+ in filePath `notElem'` filePathExceptions pwd
34 ]
34 ]
35 files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
35 files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
36 ideas <- fmap concat $ forM files $ \f -> do
36 ideas <- fmap concat $ forM files $ \f -> do
37 putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
37 putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
38 runHlint f
38 runHlint f
39 if null ideas then exitSuccess else exitFailure
39 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.hsnew file+25
@@ -0,0 +1,25 @@
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.hsnew file+47
@@ -0,0 +1,47 @@
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.hsdeleted−43
@@ -1,43 +0,0 @@
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