on develop help sign in
54 files changed+2266−7058
since splitsnapshots
unifiedsplit
.github/workflows/haskell.yml+47 .gitignore+4 .stylish-haskell.yaml+2−3 .travis.yml−26 CONTRIBUTING.md+66 ChangeLog.md+61 Quickref.md−176 README.md+44−11 bench-cbits/checkCapability.c+11−12 bench/Main.hs−109 bench/RunAll.hs−157 cabal.project+1 default.nix−26 dep/reflex-platform/default.nix+8 dep/reflex-platform/github.json+8 patch.cabal+100 reflex.cabal−134 release.nix+49 src/Data/Functor/Misc.hs+119−58 src/Data/Monoid/DecidablyEmpty.hs+115 src/Data/Patch.hs+95 src/Data/Patch/Class.hs+45 src/Data/Patch/DMap.hs+93 src/Data/Patch/DMapWithMove.hs+371 src/Data/Patch/IntMap.hs+76 src/Data/Patch/Map.hs+72 src/Data/Patch/MapWithMove.hs+312 src/Data/Patch/MapWithPatchingMove.hs+432 src/Data/Semigroup/Additive.hs+54 src/Data/WeakBag.hs−117 src/Reflex.hs−12 src/Reflex/Class.hs−891 src/Reflex/Dynamic.hs−561 src/Reflex/Dynamic/TH.hs−88 src/Reflex/Dynamic/Uniq.hs−101 src/Reflex/DynamicWriter.hs−194 src/Reflex/Host/Class.hs−282 src/Reflex/PerformEvent/Base.hs−286 src/Reflex/PerformEvent/Class.hs−92 src/Reflex/PostBuild/Class.hs−103 src/Reflex/Pure.hs−171 src/Reflex/Spider.hs−16 src/Reflex/Spider/Internal.hs−2156 stylize+4 test/Reflex/Bench/Focused.hs−369 test/Reflex/Plan/Pure.hs−70 test/Reflex/Plan/Reflex.hs−135 test/Reflex/Test.hs−66 test/Reflex/Test/CrossImpl.hs−244 test/Reflex/Test/Micro.hs−280 test/Reflex/TestPlan.hs−52 test/hlint.hs+34−11 test/semantics.hs−49 test/tests.hs+43
.github/workflows/haskell.ymlnew file+47
@@ -0,0 +1,47 @@
1+name: github-action
2+
3+on: [push, pull_request]
4+
5+jobs:
6+ build:
7+ strategy:
8+ matrix:
9+ ghc: ['8.0.2', '8.2.2', '8.4.4', '8.6.5', '8.8.4', '8.10.2']
10+ os: ['ubuntu-latest', 'macos-latest']
11+ exclude:
12+ # There are some linker warnings in 802 on darwin that
13+ # cause compilation to fail
14+ # See https://github.com/NixOS/nixpkgs/issues/25139
15+ - ghc: '8.0.2'
16+ os: 'macos-latest'
17+ runs-on: ${{ matrix.os }}
18+
19+ name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20+ steps:
21+ - uses: actions/checkout@v2
22+ - uses: actions/setup-haskell@v1
23+ with:
24+ ghc-version: ${{ matrix.ghc }}
25+ - name: Cache
26+ uses: actions/cache@v1
27+ env:
28+ cache-name: cache-cabal
29+ with:
30+ path: ~/.cabal
31+ key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32+ restore-keys: |
33+ ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34+ ${{ runner.os }}-${{ matrix.ghc }}-build-
35+ ${{ runner.os }}-${{ matrix.ghc }}-
36+ ${{ runner.os }}
37+
38+ - name: Install dependencies
39+ run: |
40+ cabal update
41+ cabal build --only-dependencies --enable-tests --enable-benchmarks
42+ - name: Build
43+ run: cabal build --enable-tests --enable-benchmarks all
44+ - name: Run tests
45+ run: cabal test --enable-tests all
46+ - name: Build Docs
47+ run: cabal haddock
.gitignore+4
@@ -1,4 +1,6 @@
11dist
2+cabal.sandbox.config
3+.cabal-sandbox/
24dist-*
35cabal-dev
46*.o
@@ -32,3 +34,5 @@ hsenv.log
3234.#*
3335/shell.nix
3436/ghci-tmp
37+*.dump-*
38+*.verbose-core2core
.stylish-haskell.yaml+2−3
@@ -149,6 +149,5 @@ columns: 110
149149# needs to be aware of these, so it can parse the file correctly.
150150#
151151# No language extensions are enabled by default.
152−# language_extensions:
153− # - TemplateHaskell
154− # - QuasiQuotes
152+language_extensions:
153+ - TemplateHaskell
.travis.ymldeleted−26
@@ -1,26 +0,0 @@
1−sudo: false
2−before_install:
3− - travis_retry cabal-$CABALVER update
4− - export PATH=/opt/ghc/$GHCVER/bin:/opt/happy/1.19.5/bin:/opt/alex/3.1.4/bin:$PATH
5−install:
6− - travis_retry cabal-$CABALVER install --only-dependencies -j --enable-tests
7−script:
8− - cabal-$CABALVER configure -v2 --enable-tests
9− - travis_wait cabal-$CABALVER build
10− - cabal-$CABALVER test
11− - cabal-$CABALVER sdist # tests that a source-distribution can be generated
12−# Check that the resulting source distribution can be built & installed.
13−# If there are no other `.tar.gz` files in `dist`, this can be even simpler:
14−# `cabal install --force-reinstalls dist/*-*.tar.gz`
15− - SRC_TGZ=$(cabal-$CABALVER info . | awk '{print $2;exit}').tar.gz &&
16− (cd dist && cabal-$CABALVER install --force-reinstalls "$SRC_TGZ")
17−
18−matrix:
19− include:
20− - env: CABALVER=1.18 GHCVER=7.8.4
21− addons: {apt: {packages: [cabal-install-1.18, ghc-7.8.4, alex-3.1.4, happy-1.19.5], sources: [hvr-ghc]}}
22− - env: CABALVER=1.22 GHCVER=7.10.1
23− addons: {apt: {packages: [cabal-install-1.22, ghc-7.10.1, alex-3.1.4, happy-1.19.5],sources: [hvr-ghc]}}
24− - env: CABALVER=1.24 GHCVER=8.0.1
25− addons: {apt: {packages: [cabal-install-1.24, ghc-8.0.1, alex-3.1.4, happy-1.19.5],sources: [hvr-ghc]}}
26− fast_finish: true
CONTRIBUTING.mdnew file+66
@@ -0,0 +1,66 @@
1+# Contribution Guide
2+
3+Contributions and issue reports are encouraged and appreciated!
4+
5+- [Opening Issues](#opening-issues)
6+- [Submitting Changes](#submitting-changes)
7+ - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
8+ - [Guidelines for Pull Requests](#guidelines-for-pull-requests)
9+ - [Code Quality](#code-quality)
10+ - [Documentation](#documentation)
11+
12+## Opening Issues
13+
14+Before opening an issue, please check whether your issue has already been reported. Assuming it has not:
15+
16+* 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.
18+* Let us know what version of patch you were using. If you're using a github checkout, provide the git hash.
19+* Describe how you're building patch (i.e., via reflex-platform, cabal install, stack, obelisk, etc.). If you're using reflex-platform or obelisk, provide the git hash of your checkout.
20+
21+## Submitting Changes
22+
23+### Guidelines for Commit Messages
24+
25+#### Summary Line
26+The summary line of your commit message should summarize the changes being made. Commit messages should be written in the imperative mood and should describe what happens when the commit is applied.
27+
28+One way to think about it is that your commit message should be able to complete the sentence:
29+"When applied, this commit will..."
30+
31+#### Body
32+For 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+
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
39+
40+#### Warnings
41+
42+Your pull request should add no new warnings to the project. It should also generally not disable any warnings.
43+
44+#### Build and Test
45+
46+Make 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+
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
53+
54+#### In the code
55+We're always striving to improve documentation. Please include [haddock](https://haskell-haddock.readthedocs.io/en/latest/index.html) documentation for any added code, and update the documentation for any code you modify.
56+
57+#### In the [Changelog](ChangeLog.md)
58+Add an entry to the changelog when your PR:
59+* Adds a feature
60+* Deprecates something
61+* Includes a breaking change
62+* Makes any other change that will impact users
63+
64+#### In the [Readme](README.md)
65+The readme is the first place a lot of people look for information about the repository. Update any parts of the readme that are affected by your PR.
66+
ChangeLog.mdnew file+61
@@ -0,0 +1,61 @@
1+# Revision history for patch
2+
3+## Unreleased
4+
5+* New dep of `data-orphans` for old GHC to get instances honestly instead of
6+ via `monoidal-containers`.
7+
8+## 0.0.5.0 - 2021-12-17
9+
10+* `Additive` now lives in `Data.Semigroup.Additive`, but is still reexported
11+ from `Data.Patch` for compatability.
12+
13+* Rewrite `PatchMapWithMove` in terms of `PatchMapWithPatchingMove`.
14+ Care is taken to make this not a breaking change.
15+ In particular, `PatchMapWithMove` is a newtype of `PatchMapWithPatchingMove`, as is the `NodeInfo` and `From` of `PatchMapWithPatchingMove`'s versions of those.
16+ There are complete constructor and field patterns too, and everything is
17+ exported under the newtype as real constructors and fields would be.
18+
19+## 0.0.4.0 - 2021-04-20
20+
21+* Enable PolyKinds
22+
23+## 0.0.3.2 - 2020-11-06
24+
25+* Update version bounds
26+
27+## 0.0.3.1 - 2020-02-05
28+
29+* Replace `fromJust` with something easier to debug.
30+
31+## 0.0.3.0 - 2020-02-05
32+
33+* Create `PatchMapWithPatchingMove` variant which supports moves with a patch.
34+
35+* Create `DecidablyEmpty` subclass of `Monoid`.
36+
37+## 0.0.2.0 - 2020-01-17
38+
39+* Consistently provide:
40+
41+ - `Wrapped` instances
42+
43+ - `*WithIndex` instances
44+
45+ - `un*` newtype unwrappers
46+
47+ for `PatchMap`, `PatchIntMap`, and `PatchMapWithMove`.
48+
49+## 0.0.1.0 - 2020-01-09
50+
51+* Support older GHCs with `split-these` flag.
52+
53+* Additional instances for the `Group` class for basic types.
54+
55+## 0.0.0.1 - 2020-01-08
56+
57+* Remove unneeded dependencies
58+
59+## 0.0.0.0 - 2020-01-08
60+
61+* Extract patching functionality from Reflex.
Quickref.mddeleted−176
@@ -1,176 +0,0 @@
1−# Reflex Quick(ish) Reference
2−
3−## Typeclasses
4−
5−Many Reflex functions operate in monadic context `m a`, where the monad 'm' supports various additional typeclasses such as MonadWidget, MonadHold, or MonadSample in addition to Monad itself. The actual 'm' in use will be determined by the top-level entry point of the FRP host (such as Reflex-Dom -- see the bottom of the Reflex-Dom quick reference for details).
6−
7−The function signatures here have been simplified by removing many typeclass constraints and adding simple annotations to each function. Also the ubiquitous 't' type parameter has been removed.
8−
9−Some of these functions are *pure*: They operate on Events, Behaviors, or Dynamics uniformly without regard to the "current time". Other functions must operate in some monadic context, because they produce a result "as of now" (e.g., any function that takes an "initial" value, or returns a "current" value). Annotations are used to distinguish these cases:
10−
11−```haskell
12−[ ] -- Pure function
13−[S] -- Function runs in any monad supporting MonadSample
14−[H] -- Function runs in any monad supporting MonadHold
15−```
16−
17−Since MonadHold depends on MonadSample, any [S] function also runs in [H] context.
18−
19−## Functions producing Event
20−
21−```haskell
22−-- Trivial Event
23−[ ] never :: Event a
24−
25−-- Extract Event from Dynamic
26−[ ] updated :: Dynamic a -> Event a
27−
28−-- Transform Event to Event using function
29−[ ] fmap :: (a -> b) -> Event a -> Event b
30−[ ] fmapMaybe :: (a -> Maybe b) -> Event a -> Event b
31−[ ] ffilter :: (a -> Bool) -> Event a -> Event a
32−[ ] ffor :: Event a -> (a -> b) -> Event b
33−[ ] fforMaybe :: Event a -> (a -> Maybe b) -> Event b
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−
50−-- Combine multiple Events
51−[ ] <> :: Monoid a => Event a -> Event a -> Event a
52−[ ] mergeWith :: (a -> a -> a) -> [Event a] -> Event a
53−[ ] leftmost :: [Event a] -> Event a
54−[ ] mergeList :: [Event a] -> Event (NonEmpty a)
55−[ ] merge :: GCompare k => DMap (WrapArg Event k) -> Event (DMap k)
56−[ ] mergeMap :: Ord k => Map k (Event a) -> Event (Map k a)
57−
58−-- Efficient one-to-many fanout
59−[ ] fanMap :: Ord k => Event (Map k a) -> EventSelector (Const2 k a)
60−[ ] fan :: GCompare k => Event (DMap k) -> EventSelector k
61−[ ] select :: EventSelector k -> k a -> Event a
62−
63−-- Event to Event via function that can sample current values
64−[ ] push :: (a -> m (Maybe b)) -> Event a -> Event b
65−[ ] pushAlways :: (a -> m b ) -> Event a -> Event b
66− -- Note supplied function operates in [H] context
67−
68−-- Split Event into next occurrence and all other future occurrences, as of now.
69−[H] headE :: Event a -> m (Event a)
70−[H] tailE :: Event a -> m (Event a)
71−[H] headTailE :: Event a -> m (Event a, Event a)
72−```
73−
74−## Functions producing Behavior
75−
76−```haskell
77−-- Trivial Behavior
78−[ ] constant :: a -> Behavior a
79−
80−-- Extract Behavior from Dynamic
81−[ ] current :: Dynamic a -> Behavior a
82−
83−-- Create Behavior with given initial value, updated when the Event fires.
84−[H] hold :: a -> Event a -> m (Behavior a)
85−
86−-- Transform Behavior to Behavior using function
87−[ ] fmap :: (a -> b) -> Behavior a -> Behavior b
88−[ ] ffor :: Behavior a -> (a -> b) -> Behavior b
89−[ ] <*> :: Behavior (a -> b) -> Behavior a -> Behavior b
90−[ ] >>= :: Behavior a -> (a -> Behavior b) -> Behavior b
91−[ ] <> :: Monoid a => Behavior a -> Behavior a -> Behavior a
92−-- ... plus many more due to typeclass membership
93−
94−-- Behavior to Behavior by sampling current values
95−[S] sample :: Behavior a -> m a
96−[ ] pull :: m a -> Behavior a
97− -- Note supplied value is in [S] context
98−```
99−
100−## Functions producing Dynamic
101−
102−```haskell
103−-- Trivial Dynamic
104−[ ] constDyn :: a -> Dynamic a
105−
106−-- Create Dynamic with given initial value, updated (various ways) when the Event fires.
107−[H] holdDyn :: a -> Event a -> m (Dynamic a)
108−[H] foldDyn :: (a -> b -> b ) -> b -> Event a -> m (Dynamic b)
109−[H] foldDynMaybe :: (a -> b -> Maybe b ) -> b -> Event a -> m (Dynamic b)
110−[H] foldDynM :: (a -> b -> m' b ) -> b -> Event a -> m (Dynamic b)
111−[H] foldDynMaybeM :: (a -> b -> m' (Maybe b)) -> b -> Event a -> m (Dynamic b)
112− -- Note m' supplies [H] context
113−
114−-- Initial value is 0; counts Event firings from now.
115−[H] count :: Num b => Event a -> m (Dynamic b)
116−-- Initial Bool value is supplied; toggles at each Event firing.
117−[H] toggle :: Bool -> Event a -> m (Dynamic Bool)
118−
119−-- Transform Dynamic to Dynamic using function
120−[ ] ffor :: Dynamic a -> (a -> b) -> Dynamic b
121−[ ] fmap :: (a -> b) -> Dynamic a -> Dynamic b
122−[ ] splitDynPure :: Dynamic (a, b) -> (Dynamic a, Dynamic b)
123−
124−-- Combine multiple Dynamics
125−[ ] mconcat :: Monoid a => [Dynamic a] -> Dynamic a
126−[ ] distributeDMapOverDynPure :: GCompare k => DMap (WrapArg Dynamic k) -> Dynamic (DMap k)
127−[ ] zipDynWith :: (a -> b -> c) -> Dynamic a -> Dynamic b -> Dynamic c
128−
129−-- Efficient one-to-many fanout
130−[ ] demux :: Ord k => Dynamic k -> Demux k
131−[ ] demuxed :: Eq k => Demux k -> k -> Dynamic Bool
132−
133−-- Dynamic to Dynamic, removing updates w/o value change
134−[ ] uniqDyn :: Eq a => Dynamic a -> Dynamic a
135−
136−-- Dynamic to identical Dynamic with debug trace. (Only prints if Dynamic is ultimately used.)
137−[ ] traceDyn :: Show a => String -> Dynamic a -> Dynamic a
138−[ ] traceDynWith :: (a -> String) -> Dynamic a -> Dynamic a
139−```
140−
141−## Flattening functions
142−
143−These functions flatten nested types such as Event-of-Event, Behavior-of-Event, Event-of-Behavior etc, removing the outer wrapper.
144−
145−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.
146−
147−```haskell
148−-- Flatten Behavior-of-Event to Event. Old Event is used during switchover.
149−[ ] switch :: Behavior (Event a) -> Event a
150−
151−-- Flatten Dyanmic-of-Event to Event. New Event is used immediately.
152−[ ] switchPromptlyDyn :: Dynamic (Event a) -> Event a
153−
154−-- Flatten Event-of-Event to Event that fires when both wrapper AND new Event fire.
155−[ ] coincidence :: Event (Event a) -> Event a
156−
157−-- Flatten Behavior-of-Behavior to Behavior. Behavior is an instance of Monad,
158−-- so the 'join' function from 'Control.Monad' suffices. The output of 'join' is
159−-- a Behavior whose value is equal to the current value of the current value of
160−-- the input.
161−[ ] join :: Behavior (Behavior a) -> Behavior a
162−
163−
164−-- Flatten Dynamic-of-Dynamic to Dynamic. New Dynamic is used immediately.
165−-- Output updated whenever inner OR outer Dynamic updates.
166−[ ] join :: Dynamic (Dynamic a) -> Dynamic a
167−[ ] joinDynThroughMap :: Ord k => Dynamic (Map k (Dynamic a)) -> Dynamic (Map k a)
168−
169−-- Analogous to 'hold': Create a Behavior that is initially identical to the
170−-- supplied Behavior. Updated to track a new Behavior whenever the Event fires.
171−[H] switcher :: Behavior a -> Event (Behavior a) -> m (Behavior a)
172−
173−-- Similar to above, for Events. Created Event initially tracks the first argument.
174−-- At switchover, the output Event immediately tracks the new Event.
175−[H] switchPromptly :: Event a -> Event (Event a) -> m (Event a)
176−```
README.md+44−11
@@ -1,19 +1,52 @@
1−## Reflex
2−### Practical Functional Reactive Programming
1+# patch
32
4−Reflex is an fully-deterministic, higher-order Functional Reactive Programming (FRP) interface and an engine that efficiently implements that interface.
3+[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/patch.svg)](https://hackage.haskell.org/package/patch) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/patch/badge)](https://matrix.hackage.haskell.org/#/package/patch) [![Travis CI](https://api.travis-ci.org/reflex-frp/patch.svg?branch=develop)](https://travis-ci.org/reflex-frp/patch) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/reflex-frp/patch/LICENSE)
54
6−[Reflex-DOM](https://github.com/reflex-frp/reflex-dom) is a framework built on Reflex that facilitates the development of web pages, including highly-interactive single-page apps.
5+Data structures for describing changes to other data structures.
76
8−Comprehensive documentation is still a work in progress, but a tutorial for Reflex and Reflex-DOM is available at https://github.com/reflex-frp/reflex-platform and an introductory talk given at the New York Haskell Meetup is available here: [Part 1](https://www.youtube.com/watch?v=mYvkcskJbc4) / [Part 2](https://www.youtube.com/watch?v=3qfc9XFVo2c).
7+A `Patch` type represents a kind of change made to a data structure.
98
10−A summary of Reflex functions is available in the [quick reference](Quickref.md).
9+```haskell
10+class Patch p where
11+ type PatchTarget p :: *
12+ -- | Apply the patch p a to the value a. If no change is needed, return
13+ -- 'Nothing'.
14+ apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
15+```
1116
12−### Additional resources
13−[Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
17+## Patching Maps
18+For example, `Data.Patch.Map` defines the `PatchMap` type which can be used to patch `Map`s. A `PatchMap` represents updates to a `Map` that can insert, remove, or replace items in the `Map`. In this example, the `Map` is the `PatchTarget` and the `PatchMap` is the `Patch`. Keep in mind that there are many other possible `Patch`es that can be applied to a `Map` (i.e., `Map` can be the `PatchTarget` for many different `Patch` instances).
1419
15−[/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
20+`PatchMap` is defined as:
1621
17−[hackage](https://hackage.haskell.org/package/reflex)
22+```haskell
23+newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
24+```
1825
19−[irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
26+The `Maybe` around the value is used to represent insertion/updates or deletion of the element at a given key.
27+
28+Its `Patch` instance begins with:
29+
30+```haskell
31+instance Ord k => Patch (PatchMap k v) where
32+ type PatchTarget (PatchMap k v) = Map k v
33+ ...
34+```
35+
36+When a `PatchMap` is applied to its `PatchTarget`, the following changes can occur:
37+
38+- If the key is present in the `Patch` and the `PatchTarget`...
39+
40+ - And the `Patch` value at that key is `Nothing`: delete that key from the `PatchTarget`.
41+
42+ - And the `Patch` value at that key is `Just x`: update the value at that key in the `PatchTarget` to `x`.
43+
44+- If the key is present in the `Patch` and not present in the `PatchTarget`...
45+
46+ - And the `Patch` value at that key is `Nothing`: do nothing because we're trying to delete a key that doesn't exist in the target in the first place.
47+
48+ - And the `Patch` value at that key is `Just x`: insert the key and the value `x` into the `PatchTarget`
49+
50+- If the key is *not* present in the `Patch` but present in the `PatchTarget`: do nothing.
51+
52+There are, of course, more complicated ways of patching maps involving, for example, moving values from one key to another. You can find the code for that in `Data.Patch.PatchMapWithMove`. Note that the `PatchTarget` type associated with the `PatchMapWithMove` patch instance is still `Map k v`!
bench-cbits/checkCapability.c+11−12
@@ -42,7 +42,7 @@ typedef struct Task_ {
4242 // or just continue immediately. It's a workaround for the fact
4343 // that signalling a condition variable doesn't do anything if the
4444 // thread is already running, but we want it to be sticky.
45− rtsBool wakeup;
45+ HsBool wakeup;
4646#endif
4747
4848 // This points to the Capability that the Task "belongs" to. If
@@ -62,14 +62,14 @@ typedef struct Task_ {
6262 // The current top-of-stack InCall
6363 struct InCall_ *incall;
6464
65− nat n_spare_incalls;
65+ uint32_t n_spare_incalls;
6666 struct InCall_ *spare_incalls;
6767
68− rtsBool worker; // == rtsTrue if this is a worker Task
69− rtsBool stopped; // this task has stopped or exited Haskell
68+ HsBool worker; // == rtsTrue if this is a worker Task
69+ HsBool stopped; // this task has stopped or exited Haskell
7070
7171 // So that we can detect when a finalizer illegally calls back into Haskell
72− rtsBool running_finalizers;
72+ HsBool running_finalizers;
7373
7474 // Links tasks on the returning_tasks queue of a Capability, and
7575 // on spare_workers.
@@ -88,7 +88,7 @@ struct Capability_ {
8888 StgFunTable f;
8989 StgRegTable r;
9090
91− nat no; // capability number.
91+ uint32_t no; // capability number.
9292
9393 // The Task currently holding this Capability. This task has
9494 // exclusive access to the contents of this Capability (apart from
@@ -98,12 +98,12 @@ struct Capability_ {
9898
9999 // true if this Capability is running Haskell code, used for
100100 // catching unsafe call-ins.
101− rtsBool in_haskell;
101+ HsBool in_haskell;
102102
103103 // Has there been any activity on this Capability since the last GC?
104− nat idle;
104+ uint32_t idle;
105105
106− rtsBool disabled;
106+ HsBool disabled;
107107
108108 // The run queue. The Task owning this Capability has exclusive
109109 // access to its run queue, so can wake up threads without
@@ -159,7 +159,7 @@ struct Capability_ {
159159#if defined(THREADED_RTS)
160160 // Worker Tasks waiting in the wings. Singly-linked.
161161 Task *spare_workers;
162− nat n_spare_workers; // count of above
162+ uint32_t n_spare_workers; // count of above
163163
164164 // This lock protects:
165165 // running_task
@@ -192,10 +192,9 @@ struct Capability_ {
192192
193193 // Per-capability STM-related data
194194 StgTVarWatchQueue *free_tvar_watch_queues;
195− StgInvariantCheckQueue *free_invariant_check_queues;
196195 StgTRecChunk *free_trec_chunks;
197196 StgTRecHeader *free_trec_headers;
198− nat transaction_tokens;
197+ uint32_t transaction_tokens;
199198} // typedef Capability is defined in RtsAPI.h
200199 // We never want a Capability to overlap a cache line with anything
201200 // else, so round it up to a cache line size:
bench/Main.hsdeleted−109
@@ -1,109 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−{-# LANGUAGE TupleSections #-}
5−{-# LANGUAGE TypeFamilies #-}
6−
7−-- The instance for NFData (TVar a) is an orphan, but necessary here
8−{-# OPTIONS_GHC -fno-warn-orphans #-}
9−
10−module Main where
11−
12−import Control.Concurrent.STM
13−import Control.DeepSeq
14−import Control.Exception (evaluate)
15−import Control.Monad.Identity
16−import Control.Monad.IO.Class
17−import Criterion.Main
18−import Data.Dependent.Map (DMap)
19−import qualified Data.Dependent.Map as DMap
20−import Data.Dependent.Sum
21−import Data.Functor.Misc
22−import Data.IORef
23−import Reflex
24−import Reflex.Host.Class
25−
26−main :: IO ()
27−main = defaultMain
28− [ bgroup "micro" micros ]
29−
30−#if !(MIN_VERSION_deepseq(1,4,2))
31−instance NFData (IORef a) where
32− rnf x = seq x ()
33−#endif
34−
35−instance NFData (TVar a) where
36− rnf x = seq x ()
37−
38−newtype WHNF a = WHNF a
39−instance NFData (WHNF a) where
40− rnf (WHNF a) = seq a ()
41−
42−withSetup :: NFData b => String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
43−withSetup name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
44− bench name . nfIO $ runSpiderHost (action a)
45−
46−withSetupWHNF :: String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
47−withSetupWHNF name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
48− bench name . whnfIO $ runSpiderHost (action a)
49−
50−micros :: [Benchmark]
51−micros =
52− [ bench "newIORef" $ whnfIO $ void $ newIORef ()
53− , env (newIORef (42 :: Int)) (bench "readIORef" . whnfIO . readIORef)
54− , bench "newTVar" $ whnfIO $ void $ newTVarIO ()
55− , env (newTVarIO (42 :: Int)) (bench "readTVar" . whnfIO . readTVarIO)
56− , bench "newEventWithTrigger" $ whnfIO . void $ runSpiderHost $ newEventWithTrigger $
57− \trigger -> return () <$ evaluate trigger
58− , bench "newEventWithTriggerRef" $ whnfIO . void $ runSpiderHost newEventWithTriggerRef
59− , withSetupWHNF "subscribeEvent" newEventWithTriggerRef $ subscribeEvent . fst
60− , withSetupWHNF "subscribeSwitch"
61− (join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)
62− (subscribeEvent . switch)
63− , withSetupWHNF "subscribeMerge(1)" (setupMerge 1) $ \(ev,_) -> subscribeEvent ev
64− , withSetupWHNF "subscribeMerge(100)" (setupMerge 100) (subscribeEvent . fst)
65− , withSetupWHNF "subscribeMerge(10000)" (setupMerge 10000) (subscribeEvent . fst)
66− , bench "runHostFrame" $ whnfIO $ runSpiderHost $ runHostFrame $ return ()
67− , withSetupWHNF "fireEventsAndRead(single/single)"
68− (newEventWithTriggerRef >>= subscribePair)
69− (\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)
70− , withSetupWHNF "fireEventsOnly"
71− (newEventWithTriggerRef >>= subscribePair)
72− (\(_, trigger) -> do
73− Just key <- liftIO $ readIORef trigger
74− fireEvents [key :=> Identity (42 :: Int)])
75− , withSetupWHNF "fireEventsAndRead(head/merge1)"
76− (setupMerge 1 >>= subscribePair)
77− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
78− , withSetupWHNF "fireEventsAndRead(head/merge100)"
79− (setupMerge 100 >>= subscribePair)
80− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
81− , withSetupWHNF "fireEventsAndRead(head/merge10000)"
82− (setupMerge 10000 >>= subscribePair)
83− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
84− , withSetupWHNF "fireEventsOnly(head/merge100)"
85− (setupMerge 100 >>= subscribePair)
86− (\(_, t:_) -> do
87− Just key <- liftIO $ readIORef t
88− fireEvents [key :=> Identity (42 :: Int)])
89− , withSetupWHNF "hold" newEventWithTriggerRef $ \(ev, _) -> hold (42 :: Int) ev
90− , withSetupWHNF "sample" (newEventWithTriggerRef >>= hold (42 :: Int) . fst) sample
91− ]
92−
93−setupMerge :: Int
94− -> SpiderHost Global ( Event (SpiderEnv Global) (DMap (Const2 Int a) Identity)
95− , [IORef (Maybe (EventTrigger Spider a))]
96− )
97−setupMerge num = do
98− (evs, triggers) <- unzip <$> replicateM num newEventWithTriggerRef
99− let !m = DMap.fromList [Const2 i :=> v | (i,v) <- zip [0..] evs]
100− pure (merge m, triggers)
101−
102−subscribePair :: (Event (SpiderEnv Global) a, b) -> SpiderHost Global (EventHandle (SpiderEnv Global) a, b)
103−subscribePair (ev, b) = (,b) <$> subscribeEvent ev
104−
105−fireAndRead :: IORef (Maybe (EventTrigger (SpiderEnv Global) a)) -> a -> EventHandle (SpiderEnv Global) b
106− -> SpiderHost Global (Maybe b)
107−fireAndRead trigger val subd = do
108− Just key <- liftIO $ readIORef trigger
109− fireEventsAndRead [key :=> Identity val] $ readEvent subd >>= sequence
bench/RunAll.hsdeleted−157
@@ -1,157 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE ForeignFunctionInterface #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE PatternSynonyms #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TemplateHaskell #-}
13−{-# LANGUAGE TupleSections #-}
14−{-# LANGUAGE TypeSynonymInstances #-}
15−{-# LANGUAGE ViewPatterns #-}
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−
18−module Main where
19−
20−import Criterion.Main
21−import Criterion.Types
22−
23−import Reflex
24−import Reflex.Host.Class
25−
26−import Reflex.Plan.Reflex
27−import Reflex.TestPlan
28−
29−import qualified Reflex.Bench.Focused as Focused
30−import Reflex.Spider.Internal (SpiderEventHandle)
31−
32−import Control.Applicative
33−import Control.DeepSeq (NFData (..))
34−
35−import Prelude
36−import System.IO
37−import System.Mem
38−
39−import Control.Arrow
40−import Control.Concurrent
41−import Control.Concurrent.STM
42−import Control.Exception
43−import Control.Monad
44−import Control.Monad.Trans
45−import Data.Bool
46−import Data.Function
47−import Data.Int
48−import Data.IORef
49−import Data.Monoid
50−import Data.Time.Clock
51−import Debug.Trace.LocationTH
52−import GHC.Stats
53−import System.Environment
54−import System.Mem.Weak
55−import System.Process
56−import Text.Read
57−
58−import Unsafe.Coerce
59−
60−import Data.Map (Map)
61−import qualified Data.Map as Map
62−
63−type MonadReflexHost' t m = (MonadReflexHost t m, MonadIORef m, MonadIORef (HostFrame t))
64−
65−
66−setupFiring :: (MonadReflexHost t m, MonadIORef m) => Plan t (Event t a) -> m (EventHandle t a, Schedule t)
67−setupFiring p = do
68− (e, s) <- runPlan p
69− h <- subscribeEvent e
70− return (h, s)
71−
72−-- Hack to avoid the NFData constraint for EventHandle which is a synonym
73−newtype Ignore a = Ignore a
74−instance NFData (Ignore a) where
75− rnf !_ = ()
76−
77−instance NFData (SpiderEventHandle x a) where
78− rnf !_ = ()
79−
80−instance NFData (Behavior t a) where
81− rnf !_ = ()
82−
83−instance NFData (Firing t) where
84− rnf !_ = ()
85−
86−-- Measure the running time
87−benchFiring :: forall t m. (MonadReflexHost' t m, MonadSample t m) => (forall a. m a -> IO a) -> TestCase -> Int -> IO ()
88−benchFiring runHost tc n = runHost $ do
89− let runIterations :: m a -> m ()
90− runIterations test = replicateM_ (10*n) $ do
91− result <- test
92− liftIO $ evaluate result
93− case tc of
94− TestE p -> do
95− (h, s) <- setupFiring p
96− runIterations $ readSchedule_ s $ readEvent' h
97− TestB p -> do
98− (b, s) <- runPlan p
99− runIterations $ readSchedule_ (makeDense s) $ sample b
100−
101−waitForFinalizers :: IO ()
102−waitForFinalizers = do
103− performGC
104− x <- getCurrentTime
105− isFinalized <- newIORef False
106− mkWeakPtr x $ Just $ writeIORef isFinalized True
107− performGC
108− fix $ \loop -> do
109− f <- readIORef isFinalized
110− unless f $ do
111− threadDelay 1
112− loop
113−
114−benchmarks :: [(String, Int -> IO ())]
115−benchmarks = implGroup "spider" runSpiderHost cases
116− where
117− implGroup :: (MonadReflexHost' t m, MonadSample t m) => String -> (forall a. m a -> IO a) -> [(String, TestCase)] -> [(String, Int -> IO ())]
118− implGroup name runHost = group name . fmap (second (benchFiring runHost))
119− group name = fmap $ first ((name <> "/") <>)
120− sub n frames = group ("subscribing " ++ show (n, frames)) $ Focused.subscribing n frames
121− firing n = group ("firing " <> show n) $ Focused.firing n
122− merging n = group ("merging " <> show n) $ Focused.merging n
123− dynamics n = group ("dynamics " <> show n) $ Focused.dynamics n
124− cases = concat
125− [ sub 100 40
126− , dynamics 100
127− , dynamics 1000
128− , firing 1000
129− , firing 10000
130− , merging 10
131− , merging 50
132− , merging 100
133− , merging 200
134− ]
135−
136−pattern RunTestCaseFlag = "--run-test-case"
137−
138−spawnBenchmark :: String -> Benchmark
139−spawnBenchmark name = Benchmark name $ Benchmarkable $ \n -> do
140− self <- getExecutablePath
141− callProcess self [RunTestCaseFlag, name, show n, "+RTS", "-N1"]
142−
143−foreign import ccall unsafe "myCapabilityHasOtherRunnableThreads" myCapabilityHasOtherRunnableThreads :: IO Bool
144−
145−main :: IO ()
146−main = do
147− args <- getArgs
148− case args of
149− RunTestCaseFlag : t -> case t of
150− [name, readMaybe -> Just count] -> do
151− case lookup name benchmarks of
152− Just testCase -> testCase count
153− performGC
154− fix $ \loop -> bool (return ()) (yield >> loop) =<< myCapabilityHasOtherRunnableThreads
155− return ()
156− _ -> $failure "--run-test-case: expected test name and iteration count to follow"
157− _ -> defaultMainWith (defaultConfig { timeLimit = 20, csvFile = Just "dmap-original.csv", reportFile = Just "report.html" }) $ fmap (spawnBenchmark . fst) benchmarks
cabal.projectnew file+1
@@ -0,0 +1 @@
1+packages: .
default.nixdeleted−26
@@ -1,26 +0,0 @@
1−{ mkDerivation, 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, ref-tf, semigroupoids
5−, semigroups, split, stdenv, stm, syb, template-haskell
6−, these, transformers, transformers-compat, prim-uniq
7−}:
8−mkDerivation {
9− pname = "reflex";
10− version = "0.5.0";
11− src = builtins.filterSource (path: type: baseNameOf path != ".git") ./.;
12− libraryHaskellDepends = [
13− base bifunctors containers dependent-map dependent-sum
14− exception-transformers haskell-src-exts haskell-src-meta lens
15− MemoTrie monad-control mtl primitive ref-tf semigroupoids
16− semigroups stm syb template-haskell these transformers
17− transformers-compat prim-uniq
18− ];
19− testHaskellDepends = [
20− base bifunctors containers deepseq dependent-map dependent-sum
21− hlint mtl ref-tf split transformers
22− ];
23− homepage = "https://github.com/reflex-frp/reflex";
24− description = "Higher-order Functional Reactive Programming";
25− license = stdenv.lib.licenses.bsd3;
26−}
dep/reflex-platform/default.nixnew file+8
@@ -0,0 +1,8 @@
1+# DO NOT HAND-EDIT THIS FILE
2+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3+ if !fetchSubmodules && !private then builtins.fetchTarball {
4+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5+ } else (import <nixpkgs> {}).fetchFromGitHub {
6+ inherit owner repo rev sha256 fetchSubmodules private;
7+ };
8+in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))
dep/reflex-platform/github.jsonnew file+8
@@ -0,0 +1,8 @@
1+{
2+ "owner": "reflex-frp",
3+ "repo": "reflex-platform",
4+ "branch": "master",
5+ "private": false,
6+ "rev": "c9d11db1b98855fe8ab24a3ff6a5dbe0ad902ad9",
7+ "sha256": "0sfzkqdvyah5mwvmli0wq1nl0b8cvk2cmfgfy4rz57wv42x3099y"
8+}
patch.cabalnew file+100
@@ -0,0 +1,100 @@
1+Name: patch
2+Version: 0.0.5.0
3+Synopsis: Data structures for describing changes to other data structures.
4+Description:
5+ Data structures for describing changes to other data structures.
6+ .
7+ In this library, a patch is something which can be applied, analogous to a
8+ function, and which distinguishes returning the argument it was provided from
9+ returning something else.
10+License: BSD3
11+License-file: LICENSE
12+Author: Ryan Trinkle
13+Maintainer: maintainer@obsidian.systems
14+Stability: Experimental
15+Category: FRP
16+Build-type: Simple
17+Cabal-version: >=1.10
18+homepage: https://obsidian.systems
19+bug-reports: https://github.com/reflex-frp/patch/issues
20+extra-source-files:
21+ README.md
22+ ChangeLog.md
23+
24+tested-with:
25+ GHC ==8.0.2 || ==8.2.2 || ==8.4.4 || ==8.6.5 || ==8.8.1
26+ GHCJS ==8.4
27+
28+flag split-these
29+ description: Use split these/semialign packages
30+ manual: False
31+ default: True
32+
33+library
34+ hs-source-dirs: src
35+ default-language: Haskell2010
36+ build-depends: base >= 4.9 && < 4.15
37+ , constraints-extras >= 0.3 && < 0.4
38+ , containers >= 0.6 && < 0.7
39+ , dependent-map >= 0.3 && < 0.5
40+ , dependent-sum >= 0.6 && < 0.8
41+ , lens >= 4.7 && < 5
42+ , semigroupoids >= 4.0 && < 6
43+ , transformers >= 0.5.6.0 && < 0.6
44+ , witherable >= 0.3 && < 0.5
45+
46+ if impl(ghc < 8.6) -- really, if base < 8.12
47+ build-depends: base-orphans >= 0.8 && < 0.9
48+
49+ exposed-modules: Data.Functor.Misc
50+ , Data.Monoid.DecidablyEmpty
51+ , Data.Patch
52+ , Data.Patch.Class
53+ , Data.Patch.DMap
54+ , Data.Patch.DMapWithMove
55+ , Data.Patch.IntMap
56+ , Data.Patch.Map
57+ , Data.Patch.MapWithMove
58+ , Data.Patch.MapWithPatchingMove
59+ , Data.Semigroup.Additive
60+
61+ ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs
62+ default-extensions: PolyKinds
63+
64+ if flag(split-these)
65+ build-depends: these >= 1 && <1.2
66+ , semialign >=1 && <1.2
67+ , monoidal-containers >= 0.6 && < 0.7
68+ else
69+ build-depends: these >= 0.4 && <0.9
70+ , monoidal-containers == 0.4.0.0
71+
72+test-suite tests
73+ default-language: Haskell2010
74+ type: exitcode-stdio-1.0
75+ main-is: tests.hs
76+ hs-source-dirs: test
77+ build-depends: base
78+ , patch
79+ , containers
80+ , hedgehog
81+ , HUnit
82+ if impl(ghcjs)
83+ buildable: False
84+
85+test-suite hlint
86+ default-language: Haskell2010
87+ type: exitcode-stdio-1.0
88+ main-is: hlint.hs
89+ hs-source-dirs: test
90+ build-depends: base
91+ , directory
92+ , filepath
93+ , filemanip
94+ , hlint (< 2.1 || >= 2.2.2) && < 3.3
95+ if impl(ghcjs)
96+ buildable: False
97+
98+source-repository head
99+ type: git
100+ location: https://github.com/reflex-frp/patch
reflex.cabaldeleted−134
@@ -1,134 +0,0 @@
1−Name: reflex
2−Version: 0.5.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://github.com/reflex-frp/reflex
14−bug-reports: https://github.com/reflex-frp/reflex/issues
15−
16−library
17− hs-source-dirs: src
18− build-depends:
19− MemoTrie == 0.6.*,
20− base >= 4.7 && < 4.10,
21− bifunctors >= 5.2 && < 5.5,
22− containers == 0.5.*,
23− dependent-map >= 0.2.2 && < 0.3,
24− dependent-sum == 0.3.*,
25− exception-transformers == 0.4.*,
26− haskell-src-exts >= 1.16 && < 1.18,
27− haskell-src-meta == 0.6.*,
28− lens >= 4.7 && < 5,
29− monad-control >= 1.0.1 && < 1.1,
30− mtl >= 2.1 && < 2.3,
31− primitive >= 0.5 && < 0.7,
32− prim-uniq >= 0.1.0.1 && < 0.2,
33− ref-tf == 0.4.*,
34− semigroupoids >= 4.0 && < 6,
35− semigroups >= 0.16 && < 0.19,
36− stm == 2.4.*,
37− syb >= 0.5 && < 0.7,
38− template-haskell >= 2.9 && < 2.12,
39− these >= 0.4 && < 0.8,
40− transformers >= 0.2,
41− transformers-compat >= 0.3
42−
43− exposed-modules:
44− Data.Functor.Misc,
45− Data.WeakBag,
46− Reflex,
47− Reflex.Class,
48− Reflex.Dynamic,
49− Reflex.Dynamic.TH,
50− Reflex.Dynamic.Uniq,
51− Reflex.DynamicWriter,
52− Reflex.Host.Class,
53− Reflex.PerformEvent.Base,
54− Reflex.PerformEvent.Class,
55− Reflex.PostBuild.Class,
56− Reflex.Pure,
57− Reflex.Spider,
58− Reflex.Spider.Internal
59−
60− other-extensions: TemplateHaskell
61− ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2
62− ghc-prof-options: -auto-all
63−
64−test-suite semantics
65− type: exitcode-stdio-1.0
66− main-is: semantics.hs
67− hs-source-dirs: test
68− ghc-options: -O2 -Wall -rtsopts
69− build-depends:
70− base,
71− bifunctors,
72− containers,
73− deepseq >= 1.3 && < 1.5,
74− dependent-map,
75− dependent-sum,
76− mtl,
77− ref-tf,
78− reflex,
79− split,
80− transformers >= 0.3
81−
82−test-suite hlint
83− type: exitcode-stdio-1.0
84− main-is: hlint.hs
85− hs-source-dirs: test
86− build-depends: base, hlint == 1.9.*
87− if impl(ghcjs)
88− buildable: False
89−
90−benchmark spider-bench
91− type: exitcode-stdio-1.0
92− hs-source-dirs: bench
93− main-is: Main.hs
94− ghc-options: -Wall -O2 -rtsopts
95− build-depends:
96− base,
97− criterion == 1.1.*,
98− deepseq >= 1.3 && < 1.5,
99− dependent-map,
100− dependent-sum,
101− mtl,
102− primitive,
103− reflex,
104− stm,
105− transformers >= 0.3
106−
107−benchmark saulzar-bench
108− type: exitcode-stdio-1.0
109− hs-source-dirs: bench test
110− c-sources: bench-cbits/checkCapability.c
111− main-is: RunAll.hs
112− ghc-options: -Wall -O2 -rtsopts -threaded
113− ghc-prof-options: -auto-all
114− build-depends:
115− base,
116− containers == 0.5.*,
117− criterion == 1.1.*,
118− deepseq >= 1.3 && < 1.5,
119− dependent-map,
120− dependent-sum,
121− loch-th,
122− mtl,
123− primitive,
124− process,
125− ref-tf,
126− reflex,
127− split,
128− stm,
129− time,
130− transformers >= 0.3
131−
132−source-repository head
133− type: git
134− location: https://github.com/reflex-frp/reflex
release.nixnew file+49
@@ -0,0 +1,49 @@
1+{ reflex-platform-fun ? import ./dep/reflex-platform
2+}:
3+
4+let
5+ native-reflex-platform = reflex-platform-fun {};
6+ inherit (native-reflex-platform.nixpkgs) lib;
7+ systems = ["x86_64-linux" "x86_64-darwin"];
8+
9+ perPlatform = lib.genAttrs systems (system: let
10+ reflex-platform = reflex-platform-fun { inherit system; };
11+ compilers = [
12+ "ghc"
13+ "ghcjs"
14+ ] ++ lib.optionals (reflex-platform.androidSupport) [
15+ "ghcAndroidAarch64"
16+ "ghcAndroidAarch32"
17+ ] ++ lib.optionals (reflex-platform.iosSupport) [
18+ "ghcIosAarch64"
19+ ];
20+ compilerPkgs = lib.genAttrs compilers (ghc: let
21+ reflex-platform = reflex-platform-fun {
22+ inherit system;
23+ haskellOverlays = [
24+ # Use this package's source for reflex
25+ (self: super: {
26+ _dep = super._dep // {
27+ patch = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
28+ "release.nix"
29+ ".git"
30+ "dist"
31+ "dist-newstyle"
32+ "cabal.haskell-ci"
33+ "cabal.project"
34+ ".travis.yml"
35+ ])) ./.;
36+ };
37+ })
38+ ];
39+ };
40+ in reflex-platform.${ghc}.patch);
41+ in compilerPkgs // {
42+ cache = reflex-platform.pinBuildInputs "patch-${system}"
43+ (builtins.attrValues compilerPkgs);
44+ });
45+
46+ metaCache = native-reflex-platform.pinBuildInputs "patch-everywhere"
47+ (map (a: a.cache) (builtins.attrValues perPlatform));
48+
49+in perPlatform // { inherit metaCache; }
src/Data/Functor/Misc.hs+119−58
@@ -1,8 +1,10 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveFunctor #-}
24{-# LANGUAGE FlexibleContexts #-}
35{-# LANGUAGE FlexibleInstances #-}
46{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE KindSignatures #-}
7+{-# LANGUAGE LambdaCase #-}
68{-# LANGUAGE MultiParamTypeClasses #-}
79{-# LANGUAGE PolyKinds #-}
810{-# LANGUAGE RankNTypes #-}
@@ -12,35 +14,42 @@
1214-- which are relevant to the use of 'Functor'-based datastructures like
1315-- 'Data.Dependent.Map.DMap'.
1416module Data.Functor.Misc
15− ( -- * Const2
16− Const2 (..)
17− , dmapToMap
18− , mapToDMap
19− -- * WrapArg
20− , WrapArg (..)
21− -- * Convenience functions for DMap
22− , mapWithFunctorToDMap
23− , mapKeyValuePairsMonotonic
24− , combineDMapsWithKey
25− -- * Deprecated functions
26− , sequenceDmap
27− , wrapDMap
28− , rewrapDMap
29− , unwrapDMap
30− , unwrapDMapMaybe
31− , extractFunctorDMap
32− ) where
33−
34−import Control.Applicative (Applicative, (<$>))
35−import Control.Monad.Identity
17+ ( -- * Const2
18+ Const2 (..)
19+ , unConst2
20+ , dmapToMap
21+ , dmapToIntMap
22+ , dmapToMapWith
23+ , mapToDMap
24+ , weakenDMapWith
25+ -- * WrapArg
26+ , WrapArg (..)
27+ -- * Convenience functions for DMap
28+ , mapWithFunctorToDMap
29+ , intMapWithFunctorToDMap
30+ , mapKeyValuePairsMonotonic
31+ , combineDMapsWithKey
32+ , EitherTag (..)
33+ , dmapToThese
34+ , eitherToDSum
35+ , dsumToEither
36+ , ComposeMaybe (..)
37+ ) where
38+
39+import Control.Applicative ((<$>))
3640import Data.Dependent.Map (DMap)
3741import qualified Data.Dependent.Map as DMap
3842import Data.Dependent.Sum
43+import Data.Functor.Identity
3944import Data.GADT.Compare
4045import Data.GADT.Show
46+import Data.IntMap (IntMap)
47+import qualified Data.IntMap as IntMap
4148import Data.Map (Map)
4249import qualified Data.Map as Map
50+import Data.Some (Some, mkSome)
4351import Data.These
52+import Data.Type.Equality ((:~:)(Refl))
4453import Data.Typeable hiding (Refl)
4554
4655--------------------------------------------------------------------------------
@@ -53,14 +62,18 @@ data Const2 :: * -> x -> x -> * where
5362 Const2 :: k -> Const2 k v v
5463 deriving (Typeable)
5564
56−deriving instance Show k => Show (Const2 k v v)
65+-- | Extract the value from a Const2
66+unConst2 :: Const2 k v v' -> k
67+unConst2 (Const2 k) = k
68+
69+deriving instance Eq k => Eq (Const2 k v v')
70+deriving instance Ord k => Ord (Const2 k v v')
71+deriving instance Show k => Show (Const2 k v v')
72+deriving instance Read k => Read (Const2 k v v)
5773
5874instance Show k => GShow (Const2 k v) where
5975 gshowsPrec n x@(Const2 _) = showsPrec n x
6076
61−instance (Show k, Show (f v)) => ShowTag (Const2 k v) f where
62− showTaggedPrec (Const2 _) = showsPrec
63−
6477instance Eq k => GEq (Const2 k v) where
6578 geq (Const2 a) (Const2 b) =
6679 if a == b
@@ -77,6 +90,15 @@ instance Ord k => GCompare (Const2 k v) where
7790dmapToMap :: DMap (Const2 k v) Identity -> Map k v
7891dmapToMap = Map.fromDistinctAscList . map (\(Const2 k :=> Identity v) -> (k, v)) . DMap.toAscList
7992
93+-- | Convert a 'DMap' to an 'IntMap'
94+dmapToIntMap :: DMap (Const2 IntMap.Key v) Identity -> IntMap v
95+dmapToIntMap = IntMap.fromDistinctAscList . map (\(Const2 k :=> Identity v) -> (k, v)) . DMap.toAscList
96+
97+-- | Convert a 'DMap' to a regular 'Map', applying the given function to remove
98+-- the wrapping 'Functor'
99+dmapToMapWith :: (f v -> v') -> DMap (Const2 k v) f -> Map k v'
100+dmapToMapWith f = Map.fromDistinctAscList . map (\(Const2 k :=> v) -> (k, f v)) . DMap.toAscList
101+
80102-- | Convert a regular 'Map' to a 'DMap'
81103mapToDMap :: Map k v -> DMap (Const2 k v) Identity
82104mapToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> Identity v) . Map.toAscList
@@ -86,6 +108,16 @@ mapToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> Identity v)
86108mapWithFunctorToDMap :: Map k (f v) -> DMap (Const2 k v) f
87109mapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> v) . Map.toAscList
88110
111+-- | Convert a regular 'IntMap', where the values are already wrapped in a
112+-- functor, to a 'DMap'
113+intMapWithFunctorToDMap :: IntMap (f v) -> DMap (Const2 IntMap.Key v) f
114+intMapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> v) . IntMap.toAscList
115+
116+-- | Convert a 'DMap' to a regular 'Map' by forgetting the types associated with
117+-- the keys, using a function to remove the wrapping 'Functor'
118+weakenDMapWith :: (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
120+
89121--------------------------------------------------------------------------------
90122-- WrapArg
91123--------------------------------------------------------------------------------
@@ -96,6 +128,11 @@ mapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> v
96128data WrapArg :: (k -> *) -> (k -> *) -> * -> * where
97129 WrapArg :: f a -> WrapArg g f (g a)
98130
131+deriving instance Eq (f a) => Eq (WrapArg g f (g' a))
132+deriving instance Ord (f a) => Ord (WrapArg g f (g' a))
133+deriving instance Show (f a) => Show (WrapArg g f (g' a))
134+deriving instance Read (f a) => Read (WrapArg g f (g a))
135+
99136instance GEq f => GEq (WrapArg g f) where
100137 geq (WrapArg a) (WrapArg b) = (\Refl -> Refl) <$> geq a b
101138
@@ -133,38 +170,62 @@ combineDMapsWithKey f mg mh = DMap.fromList $ go (DMap.toList mg) (DMap.toList m
133170 GEQ -> (gk :=> f gk (These gv hv)) : go gs' hs'
134171 GGT -> (hk :=> f hk (That hv)) : go gs hs'
135172
173+-- | Extract the values of a 'DMap' of 'EitherTag's.
174+dmapToThese :: DMap (EitherTag a b) Identity -> Maybe (These a b)
175+dmapToThese m = case (DMap.lookup LeftTag m, DMap.lookup RightTag m) of
176+ (Nothing, Nothing) -> Nothing
177+ (Just (Identity a), Nothing) -> Just $ This a
178+ (Nothing, Just (Identity b)) -> Just $ That b
179+ (Just (Identity a), Just (Identity b)) -> Just $ These a b
180+
181+-- | Tag type for 'Either' to use it as a 'DSum'.
182+data EitherTag l r a where
183+ LeftTag :: EitherTag l r l
184+ RightTag :: EitherTag l r r
185+ deriving (Typeable)
186+
187+deriving instance Show (EitherTag l r a)
188+deriving instance Eq (EitherTag l r a)
189+deriving instance Ord (EitherTag l r a)
190+
191+instance GEq (EitherTag l r) where
192+ geq a b = case (a, b) of
193+ (LeftTag, LeftTag) -> Just Refl
194+ (RightTag, RightTag) -> Just Refl
195+ _ -> Nothing
196+
197+instance GCompare (EitherTag l r) where
198+ gcompare a b = case (a, b) of
199+ (LeftTag, LeftTag) -> GEQ
200+ (LeftTag, RightTag) -> GLT
201+ (RightTag, LeftTag) -> GGT
202+ (RightTag, RightTag) -> GEQ
203+
204+instance GShow (EitherTag l r) where
205+ gshowsPrec _ a = case a of
206+ LeftTag -> showString "LeftTag"
207+ RightTag -> showString "RightTag"
208+
209+-- | Convert 'Either' to a 'DSum'. Inverse of 'dsumToEither'.
210+eitherToDSum :: Either a b -> DSum (EitherTag a b) Identity
211+eitherToDSum = \case
212+ Left a -> (LeftTag :=> Identity a)
213+ Right b -> (RightTag :=> Identity b)
214+
215+-- | Convert 'DSum' to 'Either'. Inverse of 'eitherToDSum'.
216+dsumToEither :: DSum (EitherTag a b) Identity -> Either a b
217+dsumToEither = \case
218+ (LeftTag :=> Identity a) -> Left a
219+ (RightTag :=> Identity b) -> Right b
220+
136221--------------------------------------------------------------------------------
137−-- Deprecated functions
222+-- ComposeMaybe
138223--------------------------------------------------------------------------------
139224
140−{-# INLINE sequenceDmap #-}
141−{-# DEPRECATED sequenceDmap "Use 'Data.Dependent.Map.traverseWithKey (\\_ t -> fmap Identity t)' instead" #-}
142−-- | Run the actions contained in the 'DMap'
143−sequenceDmap :: Applicative t => DMap f t -> t (DMap f Identity)
144−sequenceDmap = DMap.traverseWithKey $ \_ t -> Identity <$> t
145−
146−{-# DEPRECATED wrapDMap "Use 'Data.Dependent.Map.map (f . runIdentity)' instead" #-}
147−-- | Replace the 'Identity' functor for a 'DMap''s values with a different functor
148−wrapDMap :: (forall a. a -> f a) -> DMap k Identity -> DMap k f
149−wrapDMap f = DMap.map $ f . runIdentity
150−
151−{-# DEPRECATED rewrapDMap "Use 'Data.Dependent.Map.map' instead" #-}
152−-- | Replace one functor for a 'DMap''s values with a different functor
153−rewrapDMap :: (forall (a :: *). f a -> g a) -> DMap k f -> DMap k g
154−rewrapDMap = DMap.map
155−
156−{-# DEPRECATED unwrapDMap "Use 'Data.Dependent.Map.map (Identity . f)' instead" #-}
157−-- | Replace one functor for a 'DMap''s values with the 'Identity' functor
158−unwrapDMap :: (forall a. f a -> a) -> DMap k f -> DMap k Identity
159−unwrapDMap f = DMap.map $ Identity . f
160−
161−{-# DEPRECATED unwrapDMapMaybe "Use 'Data.Dependent.Map.mapMaybeWithKey (\\_ a -> fmap Identity $ f a)' instead" #-}
162−-- | Like 'unwrapDMap', but possibly delete some values from the DMap
163−unwrapDMapMaybe :: GCompare k => (forall a. f a -> Maybe a) -> DMap k f -> DMap k Identity
164−unwrapDMapMaybe f = DMap.mapMaybeWithKey $ \_ a -> Identity <$> f a
165−
166−{-# DEPRECATED extractFunctorDMap "Use 'mapKeyValuePairsMonotonic (\\(Const2 k :=> Identity v) -> Const2 k :=> v)' instead" #-}
167−-- | Eliminate the 'Identity' functor in a 'DMap' and replace it with the
168−-- underlying functor
169−extractFunctorDMap :: DMap (Const2 k (f v)) Identity -> DMap (Const2 k v) f
170−extractFunctorDMap = mapKeyValuePairsMonotonic $ \(Const2 k :=> Identity v) -> Const2 k :=> v
225+-- | We can't use @Compose Maybe@ instead of 'ComposeMaybe', because that would
226+-- make the 'f' parameter have a nominal type role. We need f to be
227+-- representational so that we can use safe 'coerce'.
228+newtype ComposeMaybe f a =
229+ ComposeMaybe { getComposeMaybe :: Maybe (f a) } deriving (Show, Eq, Ord)
230+
231+deriving instance Functor f => Functor (ComposeMaybe f)
src/Data/Monoid/DecidablyEmpty.hsnew file+115
@@ -0,0 +1,115 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DefaultSignatures #-}
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE StandaloneDeriving #-}
5+{-# LANGUAGE TypeOperators #-}
6+
7+-- TODO upstream somwhere else?
8+module Data.Monoid.DecidablyEmpty where
9+
10+import Data.Functor.Identity
11+import Data.Functor.Const
12+import Data.Monoid
13+import Data.Maybe (isNothing)
14+#if MIN_VERSION_base(4,11,0)
15+import Data.Ord
16+#endif
17+import Data.Proxy
18+import Data.Semigroup hiding (First, Last)
19+#if MIN_VERSION_base(4,12,0)
20+import GHC.Generics
21+#endif
22+
23+import qualified Data.IntSet as IntSet
24+import qualified Data.IntMap as IntMap
25+import qualified Data.Map as Map
26+import qualified Data.Sequence as Seq
27+import qualified Data.Set as Set
28+
29+import Data.GADT.Compare
30+import qualified Data.Dependent.Map as DMap
31+
32+-- | A 'DecidablyEmpty' is one where it can be computed whether or not an
33+-- arbitrary value is 'mempty'.
34+--
35+-- By using this class rather than 'Eq', we avoid unnecessary constraining the
36+-- contents of 'Functor's. This makes it possible to efficiently combine and/or
37+-- nest patch maps with 'Eq'-lacking values (e.g. functions) at the leaves.
38+class Monoid a => DecidablyEmpty a where
39+ isEmpty :: a -> Bool
40+ default isEmpty :: Eq a => a -> Bool
41+ isEmpty = (==) mempty
42+
43+-- base
44+
45+instance DecidablyEmpty Ordering
46+instance DecidablyEmpty ()
47+instance DecidablyEmpty Any
48+instance DecidablyEmpty All
49+-- instance DecidablyEmpty Lifetime
50+-- instance DecidablyEmpty Event
51+instance DecidablyEmpty [a] where
52+ isEmpty = null
53+instance
54+#if MIN_VERSION_base(4,11,0)
55+ Semigroup a
56+#else
57+ Monoid a
58+#endif
59+ => DecidablyEmpty (Maybe a) where
60+ isEmpty = isNothing
61+deriving instance (Num a, DecidablyEmpty a) => DecidablyEmpty (Product a)
62+deriving instance (DecidablyEmpty a, Num a) => DecidablyEmpty (Sum a)
63+deriving instance DecidablyEmpty a => DecidablyEmpty (Dual a)
64+instance DecidablyEmpty (First a) where
65+ isEmpty (First a) = isNothing a
66+instance DecidablyEmpty (Last a) where
67+ isEmpty (Last a) = isNothing a
68+deriving instance DecidablyEmpty a => DecidablyEmpty (Identity a)
69+instance Semigroup a => DecidablyEmpty (Option a) where
70+ isEmpty (Option a) = isNothing a
71+deriving instance DecidablyEmpty m => DecidablyEmpty (WrappedMonoid m)
72+instance (Ord a, Bounded a) => DecidablyEmpty (Max a)
73+instance (Ord a, Bounded a) => DecidablyEmpty (Min a)
74+instance DecidablyEmpty (Proxy s)
75+deriving instance DecidablyEmpty a => DecidablyEmpty (Const a b)
76+#if MIN_VERSION_base(4,11,0)
77+deriving instance DecidablyEmpty a => DecidablyEmpty (Down a)
78+#endif
79+#if MIN_VERSION_base(4,12,0)
80+deriving instance DecidablyEmpty p => DecidablyEmpty (Par1 p)
81+instance DecidablyEmpty (U1 p)
82+deriving instance DecidablyEmpty (f p) => DecidablyEmpty (Rec1 f p)
83+deriving instance DecidablyEmpty (f p) => DecidablyEmpty (M1 i c f p)
84+deriving instance DecidablyEmpty c => DecidablyEmpty (K1 i c p)
85+instance (DecidablyEmpty (f p), DecidablyEmpty (g p)) => DecidablyEmpty ((f :*: g) p) where
86+ isEmpty (x :*: y) = isEmpty x && isEmpty y
87+deriving instance DecidablyEmpty (f (g p)) => DecidablyEmpty ((f :.: g) p)
88+#endif
89+
90+instance (DecidablyEmpty a, DecidablyEmpty b) => DecidablyEmpty (a, b) where
91+ isEmpty (a, b) = isEmpty a && isEmpty b
92+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c) => DecidablyEmpty (a, b, c) where
93+ isEmpty (a, b, c) = isEmpty a && isEmpty b && isEmpty c
94+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d) => DecidablyEmpty (a, b, c, d) where
95+ isEmpty (a, b, c, d) = isEmpty a && isEmpty b && isEmpty c && isEmpty d
96+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d, DecidablyEmpty e) => DecidablyEmpty (a, b, c, d, e) where
97+ isEmpty (a, b, c, d, e) = isEmpty a && isEmpty b && isEmpty c && isEmpty d && isEmpty e
98+
99+-- containers
100+
101+instance DecidablyEmpty IntSet.IntSet where
102+ isEmpty = IntSet.null
103+instance DecidablyEmpty (IntMap.IntMap v) where
104+ isEmpty = IntMap.null
105+instance Ord k => DecidablyEmpty (Map.Map k v) where
106+ isEmpty = Map.null
107+instance DecidablyEmpty (Seq.Seq v) where
108+ isEmpty = Seq.null
109+instance Ord k => DecidablyEmpty (Set.Set k) where
110+ isEmpty = Set.null
111+
112+-- dependent-map
113+
114+instance GCompare k => DecidablyEmpty (DMap.DMap k v) where
115+ isEmpty = DMap.null
src/Data/Patch.hsnew file+95
@@ -0,0 +1,95 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE StandaloneDeriving #-}
4+{-# LANGUAGE TypeFamilies #-}
5+{-# LANGUAGE TypeOperators #-}
6+-- |
7+-- Module:
8+-- Data.Patch
9+-- Description:
10+-- This module defines the 'Patch' class.
11+module Data.Patch
12+ ( module Data.Patch
13+ , module X
14+ ) where
15+
16+import Control.Applicative
17+import Data.Functor.Const (Const (..))
18+import Data.Functor.Identity
19+import Data.Map.Monoidal (MonoidalMap)
20+import Data.Proxy
21+#if !MIN_VERSION_base(4,11,0)
22+import Data.Semigroup (Semigroup (..))
23+#endif
24+import GHC.Generics
25+
26+import Data.Semigroup.Additive as X
27+import Data.Patch.Class as X
28+import Data.Patch.DMap as X hiding (getDeletions)
29+import Data.Patch.DMapWithMove as X
30+ ( PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove
31+ , patchDMapWithMoveToPatchMapWithMoveWith
32+ , traversePatchDMapWithMoveWithKey, unPatchDMapWithMove
33+ , unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith
34+ )
35+import Data.Patch.IntMap as X hiding (getDeletions)
36+import Data.Patch.Map as X
37+import Data.Patch.MapWithMove as X
38+ ( PatchMapWithMove, patchMapWithMoveNewElements
39+ , patchMapWithMoveNewElementsMap, unPatchMapWithMove
40+ , unsafePatchMapWithMove
41+ )
42+
43+-- | A 'Group' is a 'Monoid' where every element has an inverse.
44+class (Semigroup q, Monoid q) => Group q where
45+ negateG :: q -> q
46+ (~~) :: q -> q -> q
47+ r ~~ s = r <> negateG s
48+
49+-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
50+newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
51+
52+instance Additive p => Patch (AdditivePatch p) where
53+ type PatchTarget (AdditivePatch p) = p
54+ apply (AdditivePatch p) q = Just $ p <> q
55+
56+instance (Ord k, Group q) => Group (MonoidalMap k q) where
57+ negateG = fmap negateG
58+
59+-- | Trivial group.
60+instance Group () where
61+ negateG _ = ()
62+ _ ~~ _ = ()
63+
64+-- | Product group. A Pair of groups gives rise to a group
65+instance (Group a, Group b) => Group (a, b) where
66+ negateG (a, b) = (negateG a, negateG b)
67+ (a, b) ~~ (c, d) = (a ~~ c, b ~~ d)
68+
69+-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
70+-- Base does not define Monoid (Compose f g a) so this is the best we can
71+-- really do for functor composition.
72+instance Group (f (g a)) => Group ((f :.: g) a) where
73+ negateG (Comp1 xs) = Comp1 (negateG xs)
74+ Comp1 xs ~~ Comp1 ys = Comp1 (xs ~~ ys)
75+
76+-- | Product of groups, Functor style.
77+instance (Group (f a), Group (g a)) => Group ((f :*: g) a) where
78+ negateG (a :*: b) = negateG a :*: negateG b
79+ (a :*: b) ~~ (c :*: d) = (a ~~ c) :*: (b ~~ d)
80+
81+-- | Trivial group, Functor style
82+instance Group (Proxy x) where
83+ negateG _ = Proxy
84+ _ ~~ _ = Proxy
85+
86+-- | Const lifts groups into a functor.
87+deriving instance Group a => Group (Const a x)
88+
89+-- | Identity lifts groups pointwise (at only one point)
90+deriving instance Group a => Group (Identity a)
91+
92+-- | Functions lift groups pointwise.
93+instance Group b => Group (a -> b) where
94+ negateG f = negateG . f
95+ (~~) = liftA2 (~~)
src/Data/Patch/Class.hsnew file+45
@@ -0,0 +1,45 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
3+{-# LANGUAGE TypeFamilies #-}
4+-- | The interface for types which represent changes made to other types
5+module Data.Patch.Class where
6+
7+import Data.Functor.Identity
8+import Data.Kind (Type)
9+import Data.Maybe
10+#if !MIN_VERSION_base(4,11,0)
11+import Data.Semigroup (Semigroup(..))
12+#endif
13+import Data.Proxy
14+
15+-- | A 'Patch' type represents a kind of change made to a datastructure.
16+--
17+-- 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@.
19+class Patch p where
20+ type PatchTarget p :: Type
21+ -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
22+ -- 'Nothing'.
23+ apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
24+
25+-- | Apply a 'Patch'; if it does nothing, return the original value
26+applyAlways :: Patch p => p -> PatchTarget p -> PatchTarget p
27+applyAlways p t = fromMaybe t $ apply p t
28+
29+-- | 'Identity' can be used as a 'Patch' that always fully replaces the value
30+instance Patch (Identity a) where
31+ type PatchTarget (Identity a) = a
32+ apply (Identity a) _ = Just a
33+
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
40+-- functions that return new values. The Semigroup instance for patches must
41+-- apply patches right-to-left, like '(.)'.
42+composePatchFunctions :: (Patch p, Semigroup p) => (PatchTarget p -> p) -> (PatchTarget p -> p) -> PatchTarget p -> p
43+composePatchFunctions g f a =
44+ let fp = f a
45+ in g (applyAlways fp a) <> fp
src/Data/Patch/DMap.hsnew file+93
@@ -0,0 +1,93 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE LambdaCase #-}
4+{-# LANGUAGE PolyKinds #-}
5+{-# LANGUAGE Rank2Types #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE StandaloneDeriving #-}
8+{-# LANGUAGE TypeFamilies #-}
9+
10+-- | 'Patch'es on 'DMap' that consist only of insertions (or overwrites) and deletions.
11+module Data.Patch.DMap where
12+
13+import Data.Patch.Class
14+import Data.Patch.IntMap
15+import Data.Patch.Map
16+
17+import Data.Dependent.Map (DMap)
18+import Data.Dependent.Sum (DSum (..))
19+import Data.GADT.Compare (GCompare (..))
20+import qualified Data.Dependent.Map as DMap
21+import Data.Functor.Constant
22+import Data.Functor.Misc
23+import qualified Data.IntMap as IntMap
24+import qualified Data.Map as Map
25+import Data.Monoid.DecidablyEmpty
26+#if !MIN_VERSION_base(4,11,0)
27+import Data.Semigroup (Semigroup (..))
28+#endif
29+import Data.Some (Some)
30+
31+-- | A set of changes to a 'DMap'. Any element may be inserted/updated or deleted.
32+-- Insertions are represented as @'ComposeMaybe' (Just value)@,
33+-- while deletions are represented as @'ComposeMaybe' Nothing@.
34+newtype PatchDMap k v = PatchDMap { unPatchDMap :: DMap k (ComposeMaybe v) }
35+
36+deriving instance GCompare k => Semigroup (PatchDMap k v)
37+
38+deriving instance GCompare k => Monoid (PatchDMap k v)
39+
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'.
45+instance GCompare k => Patch (PatchDMap k v) where
46+ type PatchTarget (PatchDMap k v) = DMap k v
47+ apply (PatchDMap diff) old = Just $! insertions `DMap.union` (old `DMap.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?
48+ where insertions = DMap.mapMaybeWithKey (const $ getComposeMaybe) diff
49+ deletions = DMap.mapMaybeWithKey (const $ nothingToJust . getComposeMaybe) diff
50+ nothingToJust = \case
51+ Nothing -> Just $ Constant ()
52+ Just _ -> Nothing
53+
54+-- | Map a function @v a -> v' a@ over any inserts/updates in the given
55+-- @'PatchDMap' k v@ to produce a @'PatchDMap' k v'@.
56+mapPatchDMap :: (forall a. v a -> v' a) -> PatchDMap k v -> PatchDMap k v'
57+mapPatchDMap f (PatchDMap p) = PatchDMap $ DMap.map (ComposeMaybe . fmap f . getComposeMaybe) p
58+
59+-- | Map an effectful function @v a -> f (v' a)@ over any inserts/updates in the given
60+-- @'PatchDMap' k v@ to produce a @'PatchDMap' k v'@.
61+traversePatchDMap :: Applicative f => (forall a. v a -> f (v' a)) -> PatchDMap k v -> f (PatchDMap k v')
62+traversePatchDMap f = traversePatchDMapWithKey $ const f
63+
64+-- | Map an effectful function @k a -> v a -> f (v' a)@ over any inserts/updates
65+-- in the given @'PatchDMap' k v@ to produce a @'PatchDMap' k v'@.
66+traversePatchDMapWithKey :: Applicative m => (forall a. k a -> v a -> m (v' a)) -> PatchDMap k v -> m (PatchDMap k v')
67+traversePatchDMapWithKey f (PatchDMap p) = PatchDMap <$> DMap.traverseWithKey (\k (ComposeMaybe v) -> ComposeMaybe <$> traverse (f k) v) p
68+
69+-- | Weaken a @'PatchDMap' k v@ to a @'PatchMap' (Some k) v'@ using a function
70+-- @v a -> v'@ to weaken each value contained in the patch.
71+weakenPatchDMapWith :: (forall a. v a -> v') -> PatchDMap k v -> PatchMap (Some k) v'
72+weakenPatchDMapWith f (PatchDMap p) = PatchMap $ weakenDMapWith (fmap f . getComposeMaybe) p
73+
74+-- | Convert a weak @'PatchDMap' ('Const2' k a) v@ where the @a@ is known by way of
75+-- the @Const2@ into a @'PatchMap' k v'@ using a rank 1 function @v a -> v'@.
76+patchDMapToPatchMapWith :: (v a -> v') -> PatchDMap (Const2 k a) v -> PatchMap k v'
77+patchDMapToPatchMapWith f (PatchDMap p) = PatchMap $ dmapToMapWith (fmap f . getComposeMaybe) p
78+
79+-- | Convert a @'PatchMap' k v@ into a @'PatchDMap' ('Const2' k a) v'@ using a function @v -> v' a@.
80+const2PatchDMapWith :: forall k v v' a. (v -> v' a) -> PatchMap k v -> PatchDMap (Const2 k a) v'
81+const2PatchDMapWith f (PatchMap p) = PatchDMap $ DMap.fromDistinctAscList $ g <$> Map.toAscList p
82+ where g :: (k, Maybe v) -> DSum (Const2 k a) (ComposeMaybe v')
83+ g (k, e) = Const2 k :=> ComposeMaybe (f <$> e)
84+
85+-- | Convert a @'PatchIntMap' v@ into a @'PatchDMap' ('Const2' Int a) v'@ using a function @v -> v' a@.
86+const2IntPatchDMapWith :: forall v f a. (v -> f a) -> PatchIntMap v -> PatchDMap (Const2 IntMap.Key a) f
87+const2IntPatchDMapWith f (PatchIntMap p) = PatchDMap $ DMap.fromDistinctAscList $ g <$> IntMap.toAscList p
88+ where g :: (IntMap.Key, Maybe v) -> DSum (Const2 IntMap.Key a) (ComposeMaybe f)
89+ g (k, e) = Const2 k :=> ComposeMaybe (f <$> e)
90+
91+-- | Get the values that will be replaced or deleted if the given patch is applied to the given 'DMap'.
92+getDeletions :: GCompare k => PatchDMap k v -> DMap k v' -> DMap k v'
93+getDeletions (PatchDMap p) m = DMap.intersectionWithKey (\_ v _ -> v) m p
src/Data/Patch/DMapWithMove.hsnew file+371
@@ -0,0 +1,371 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE PatternGuards #-}
8+{-# LANGUAGE PolyKinds #-}
9+{-# LANGUAGE Rank2Types #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
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
15+-- move values between keys.
16+module Data.Patch.DMapWithMove where
17+
18+import Data.Patch.Class
19+import Data.Patch.MapWithMove (PatchMapWithMove (..))
20+import qualified Data.Patch.MapWithMove as MapWithMove
21+
22+import Data.Constraint.Extras
23+import Data.Dependent.Map (DMap)
24+import Data.Dependent.Sum (DSum (..))
25+import qualified Data.Dependent.Map as DMap
26+import Data.Functor.Constant
27+import Data.Functor.Misc
28+import Data.Functor.Product
29+import Data.GADT.Compare (GEq (..), GCompare (..))
30+import Data.GADT.Show (GShow, gshow)
31+import qualified Data.Map as Map
32+import Data.Maybe
33+import Data.Monoid.DecidablyEmpty
34+#if !MIN_VERSION_base(4,11,0)
35+import Data.Semigroup (Semigroup (..))
36+#endif
37+import Data.Some (Some, mkSome)
38+import Data.These
39+
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
41+-- destinations.
42+--
43+-- Invariants:
44+--
45+-- * A key should not move to itself.
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)@)
47+newtype PatchDMapWithMove k v = PatchDMapWithMove (DMap k (NodeInfo k v))
48+
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
54+-- the current key is moving from, while @_nodeInfo_to@ specifies what key the current key is moving to if involved in a move.
55+data NodeInfo k v a = NodeInfo
56+ { _nodeInfo_from :: !(From k v a)
57+ -- ^Change applying to the current key, be it an insert, move, or delete.
58+ , _nodeInfo_to :: !(To k a)
59+ -- ^Where this key is moving to, if involved in a move. Should only be @ComposeMaybe (Just k)@ when there is a corresponding 'From_Move'.
60+ }
61+ deriving (Show)
62+
63+-- |Structure describing a particular change to a key, be it inserting a new key (@From_Insert@), updating an existing key (@From_Insert@ again), deleting a
64+-- key (@From_Delete@), or moving a key (@From_Move@).
65+data From (k :: a -> *) (v :: a -> *) :: a -> * where
66+ -- |Insert a new or update an existing key with the given value @v a@
67+ From_Insert :: v a -> From k v a
68+ -- |Delete the existing key
69+ From_Delete :: From k v a
70+ -- |Move the value from the given key @k a@ to this key. The source key should also have an entry in the patch giving the current key as @_nodeInfo_to@,
71+ -- usually but not necessarily with @From_Delete@.
72+ From_Move :: !(k a) -> From k v a
73+ deriving (Show, Read, Eq, Ord)
74+
75+-- |Type alias for the "to" part of a 'NodeInfo'. @'ComposeMaybe' ('Just' k)@ means the key is moving to another key, @ComposeMaybe Nothing@ for any other
76+-- operation.
77+type To = ComposeMaybe
78+
79+-- |Test whether a 'PatchDMapWithMove' satisfies its invariants.
80+validPatchDMapWithMove :: forall k v. (GCompare k, GShow k) => DMap k (NodeInfo k v) -> Bool
81+validPatchDMapWithMove = not . null . validationErrorsForPatchDMapWithMove
82+
83+-- |Enumerate what reasons a 'PatchDMapWithMove' doesn't satisfy its invariants, returning @[]@ if it's valid.
84+validationErrorsForPatchDMapWithMove :: forall k v. (GCompare k, GShow k) => DMap k (NodeInfo k v) -> [String]
85+validationErrorsForPatchDMapWithMove m =
86+ noSelfMoves <> movesBalanced
87+ where
88+ noSelfMoves = mapMaybe selfMove . DMap.toAscList $ m
89+ selfMove (dst :=> NodeInfo (From_Move src) _) | Just _ <- dst `geq` src = Just $ "self move of key " <> gshow src <> " at destination side"
90+ selfMove (src :=> NodeInfo _ (ComposeMaybe (Just dst))) | Just _ <- src `geq` dst = Just $ "self move of key " <> gshow dst <> " at source side"
91+ selfMove _ = Nothing
92+ movesBalanced = mapMaybe unbalancedMove . DMap.toAscList $ m
93+ unbalancedMove (dst :=> NodeInfo (From_Move src) _) =
94+ case DMap.lookup src m of
95+ Nothing -> Just $ "unbalanced move at destination key " <> gshow dst <> " supposedly from " <> gshow src <> " but source key is not in the patch"
96+ Just (NodeInfo _ (ComposeMaybe (Just dst'))) ->
97+ if isNothing (dst' `geq` dst)
98+ then Just $ "unbalanced move at destination key " <> gshow dst <> " from " <> gshow src <> " is going to " <> gshow dst' <> " instead"
99+ else Nothing
100+ _ ->
101+ Just $ "unbalanced move at destination key " <> gshow dst <> " supposedly from " <> gshow src <> " but source key has no move to key"
102+ unbalancedMove (src :=> NodeInfo _ (ComposeMaybe (Just dst))) =
103+ case DMap.lookup dst m of
104+ Nothing -> Just $ " unbalanced move at source key " <> gshow src <> " supposedly going to " <> gshow dst <> " but destination key is not in the patch"
105+ Just (NodeInfo (From_Move src') _) ->
106+ if isNothing (src' `geq` src)
107+ then Just $ "unbalanced move at source key " <> gshow src <> " to " <> gshow dst <> " is coming from " <> gshow src' <> " instead"
108+ else Nothing
109+
110+ _ ->
111+ Just $ "unbalanced move at source key " <> gshow src <> " supposedly going to " <> gshow dst <> " but destination key is not moving"
112+ unbalancedMove _ = Nothing
113+
114+-- |Test whether two @'PatchDMapWithMove' k v@ contain the same patch operations.
115+instance (GEq k, Has' Eq k (NodeInfo k v)) => Eq (PatchDMapWithMove k v) where
116+ PatchDMapWithMove a == PatchDMapWithMove b = a == b
117+
118+-- |Higher kinded 2-tuple, identical to @Data.Functor.Product@ from base ≥ 4.9
119+data Pair1 f g a = Pair1 (f a) (g a)
120+
121+-- |Helper data structure used for composing patches using the monoid instance.
122+data Fixup k v a
123+ = Fixup_Delete
124+ | Fixup_Update (These (From k v a) (To k a))
125+
126+-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
127+instance GCompare k => Semigroup (PatchDMapWithMove k v) where
128+ PatchDMapWithMove ma <> PatchDMapWithMove mb = PatchDMapWithMove m
129+ where
130+ connections = DMap.toList $ DMap.intersectionWithKey (\_ a b -> Pair1 (_nodeInfo_to a) (_nodeInfo_from b)) ma mb
131+ h :: DSum k (Pair1 (ComposeMaybe k) (From k v)) -> [DSum k (Fixup k v)]
132+ h (_ :=> Pair1 (ComposeMaybe mToAfter) editBefore) = case (mToAfter, editBefore) of
133+ (Just toAfter, From_Move fromBefore)
134+ | isJust $ fromBefore `geq` toAfter
135+ -> [toAfter :=> Fixup_Delete]
136+ | otherwise
137+ -> [ toAfter :=> Fixup_Update (This editBefore)
138+ , fromBefore :=> Fixup_Update (That (ComposeMaybe mToAfter))
139+ ]
140+ (Nothing, From_Move fromBefore) -> [fromBefore :=> Fixup_Update (That (ComposeMaybe mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
141+ (Just toAfter, _) -> [toAfter :=> Fixup_Update (This editBefore)]
142+ (Nothing, _) -> []
143+ mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
144+ mergeFixups _ (Fixup_Update a) (Fixup_Update b)
145+ | This x <- a, That y <- b
146+ = Fixup_Update $ These x y
147+ | That y <- a, This x <- b
148+ = Fixup_Update $ These x y
149+ mergeFixups _ _ _ = error "PatchDMapWithMove: incompatible fixups"
150+ fixups = DMap.fromListWithKey mergeFixups $ concatMap h connections
151+ combineNodeInfos _ nia nib = NodeInfo
152+ { _nodeInfo_from = _nodeInfo_from nia
153+ , _nodeInfo_to = _nodeInfo_to nib
154+ }
155+ applyFixup _ ni = \case
156+ Fixup_Delete -> Nothing
157+ Fixup_Update u -> Just $ NodeInfo
158+ { _nodeInfo_from = fromMaybe (_nodeInfo_from ni) $ getHere u
159+ , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
160+ }
161+ m = DMap.differenceWithKey applyFixup (DMap.unionWithKey combineNodeInfos ma mb) fixups
162+ getHere :: These a b -> Maybe a
163+ getHere = \case
164+ This a -> Just a
165+ These a _ -> Just a
166+ That _ -> Nothing
167+ getThere :: These a b -> Maybe b
168+ getThere = \case
169+ This _ -> Nothing
170+ These _ b -> Just b
171+ That b -> Just b
172+
173+-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
174+instance GCompare k => Monoid (PatchDMapWithMove k v) where
175+ mempty = PatchDMapWithMove mempty
176+ mappend = (<>)
177+
178+{-
179+mappendPatchDMapWithMoveSlow :: forall k v. (ShowTag k v, GCompare k) => PatchDMapWithMove k v -> PatchDMapWithMove k v -> PatchDMapWithMove k v
180+PatchDMapWithMove dstAfter srcAfter `mappendPatchDMapWithMoveSlow` PatchDMapWithMove dstBefore srcBefore = PatchDMapWithMove dst src
181+ where
182+ getDstAction k m = fromMaybe (From_Move k) $ DMap.lookup k m -- Any key that isn't present is treated as that key moving to itself
183+ removeRedundantDst toKey (From_Move fromKey) | isJust (toKey `geq` fromKey) = Nothing
184+ removeRedundantDst _ a = Just a
185+ f :: forall a. k a -> From k v a -> Maybe (From k v a)
186+ f toKey _ = removeRedundantDst toKey $ case getDstAction toKey dstAfter of
187+ From_Move fromKey -> getDstAction fromKey dstBefore
188+ nonMove -> nonMove
189+ dst = DMap.mapMaybeWithKey f $ DMap.union dstAfter dstBefore
190+ getSrcAction k m = fromMaybe (ComposeMaybe $ Just k) $ DMap.lookup k m
191+ removeRedundantSrc fromKey (ComposeMaybe (Just toKey)) | isJust (fromKey `geq` toKey) = Nothing
192+ removeRedundantSrc _ a = Just a
193+ g :: forall a. k a -> ComposeMaybe k a -> Maybe (ComposeMaybe k a)
194+ g fromKey _ = removeRedundantSrc fromKey $ case getSrcAction fromKey srcBefore of
195+ ComposeMaybe Nothing -> ComposeMaybe Nothing
196+ ComposeMaybe (Just toKeyBefore) -> getSrcAction toKeyBefore srcAfter
197+ src = DMap.mapMaybeWithKey g $ DMap.union srcAfter srcBefore
198+-}
199+
200+-- |Make a @'PatchDMapWithMove' k v@ which has the effect of inserting or updating a value @v a@ to the given key @k a@, like 'DMap.insert'.
201+insertDMapKey :: k a -> v a -> PatchDMapWithMove k v
202+insertDMapKey k v =
203+ PatchDMapWithMove . DMap.singleton k $ NodeInfo (From_Insert v) (ComposeMaybe Nothing)
204+
205+-- |Make a @'PatchDMapWithMove' k v@ which has the effect of moving the value from the first key @k a@ to the second key @k a@, equivalent to:
206+--
207+-- @
208+-- 'DMap.delete' src (maybe dmap ('DMap.insert' dst) (DMap.lookup src dmap))
209+-- @
210+moveDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
211+moveDMapKey src dst = case src `geq` dst of
212+ Nothing -> PatchDMapWithMove $ DMap.fromList
213+ [ dst :=> NodeInfo (From_Move src) (ComposeMaybe Nothing)
214+ , src :=> NodeInfo From_Delete (ComposeMaybe $ Just dst)
215+ ]
216+ Just _ -> mempty
217+
218+-- |Make a @'PatchDMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
219+--
220+-- @
221+-- let aMay = DMap.lookup a dmap
222+-- bMay = DMap.lookup b dmap
223+-- in maybe id (DMap.insert a) (bMay <> aMay)
224+-- . maybe id (DMap.insert b) (aMay <> bMay)
225+-- . DMap.delete a . DMap.delete b $ dmap
226+-- @
227+swapDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
228+swapDMapKey src dst = case src `geq` dst of
229+ Nothing -> PatchDMapWithMove $ DMap.fromList
230+ [ dst :=> NodeInfo (From_Move src) (ComposeMaybe $ Just src)
231+ , src :=> NodeInfo (From_Move dst) (ComposeMaybe $ Just dst)
232+ ]
233+ Just _ -> mempty
234+
235+-- |Make a @'PatchDMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'DMap.delete'.
236+deleteDMapKey :: k a -> PatchDMapWithMove k v
237+deleteDMapKey k = PatchDMapWithMove $ DMap.singleton k $ NodeInfo From_Delete $ ComposeMaybe Nothing
238+
239+{-
240+k1, k2 :: Const2 Int () ()
241+k1 = Const2 1
242+k2 = Const2 2
243+p1, p2 :: PatchDMapWithMove (Const2 Int ()) Identity
244+p1 = moveDMapKey k1 k2
245+p2 = moveDMapKey k2 k1
246+p12 = p1 <> p2
247+p21 = p2 <> p1
248+p12Slow = p1 `mappendPatchDMapWithMoveSlow` p2
249+p21Slow = p2 `mappendPatchDMapWithMoveSlow` p1
250+
251+testPatchDMapWithMove = do
252+ print p1
253+ print p2
254+ print $ p12 == deleteDMapKey k1
255+ print $ p21 == deleteDMapKey k2
256+ print $ p12Slow == deleteDMapKey k1
257+ print $ p21Slow == deleteDMapKey k2
258+
259+dst (PatchDMapWithMove x _) = x
260+src (PatchDMapWithMove _ x) = x
261+-}
262+
263+-- |Extract the 'DMap' representing the patch changes from the 'PatchDMapWithMove'.
264+unPatchDMapWithMove :: PatchDMapWithMove k v -> DMap k (NodeInfo k v)
265+unPatchDMapWithMove (PatchDMapWithMove p) = p
266+
267+-- |Wrap a 'DMap' representing patch changes into a 'PatchDMapWithMove', without checking any invariants.
268+--
269+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchDMapWithMove' are preserved; they will not be checked.
270+unsafePatchDMapWithMove :: DMap k (NodeInfo k v) -> PatchDMapWithMove k v
271+unsafePatchDMapWithMove = PatchDMapWithMove
272+
273+-- |Wrap a 'DMap' representing patch changes into a 'PatchDMapWithMove' while checking invariants. If the invariants are satisfied, @Right p@ is returned
274+-- otherwise @Left errors@.
275+patchDMapWithMove :: (GCompare k, GShow k) => DMap k (NodeInfo k v) -> Either [String] (PatchDMapWithMove k v)
276+patchDMapWithMove dm =
277+ case validationErrorsForPatchDMapWithMove dm of
278+ [] -> Right $ unsafePatchDMapWithMove dm
279+ errs -> Left errs
280+
281+-- |Map a natural transform @v -> v'@ over the given patch, transforming @'PatchDMapWithMove' k v@ into @'PatchDMapWithMove' k v'@.
282+mapPatchDMapWithMove :: forall k v v'. (forall a. v a -> v' a) -> PatchDMapWithMove k v -> PatchDMapWithMove k v'
283+mapPatchDMapWithMove f (PatchDMapWithMove p) = PatchDMapWithMove $
284+ DMap.map (\ni -> ni { _nodeInfo_from = g $ _nodeInfo_from ni }) p
285+ where g :: forall a. From k v a -> From k v' a
286+ g = \case
287+ From_Insert v -> From_Insert $ f v
288+ From_Delete -> From_Delete
289+ From_Move k -> From_Move k
290+
291+-- |Traverse an effectful function @forall a. v a -> m (v ' a)@ over the given patch, transforming @'PatchDMapWithMove' k v@ into @m ('PatchDMapWithMove' k v')@.
292+traversePatchDMapWithMove :: forall m k v v'. Applicative m => (forall a. v a -> m (v' a)) -> PatchDMapWithMove k v -> m (PatchDMapWithMove k v')
293+traversePatchDMapWithMove f = traversePatchDMapWithMoveWithKey $ const f
294+
295+-- |Map an effectful function @forall a. k a -> v a -> m (v ' a)@ over the given patch, transforming @'PatchDMapWithMove' k v@ into @m ('PatchDMapWithMove' k v')@.
296+traversePatchDMapWithMoveWithKey :: forall m k v v'. Applicative m => (forall a. k a -> v a -> m (v' a)) -> PatchDMapWithMove k v -> m (PatchDMapWithMove k v')
297+traversePatchDMapWithMoveWithKey f (PatchDMapWithMove p) = PatchDMapWithMove <$> DMap.traverseWithKey (nodeInfoMapFromM . g) p
298+ where g :: forall a. k a -> From k v a -> m (From k v' a)
299+ g k = \case
300+ From_Insert v -> From_Insert <$> f k v
301+ From_Delete -> pure From_Delete
302+ From_Move fromKey -> pure $ From_Move fromKey
303+
304+-- |Map a function which transforms @'From' k v a@ into a @'From' k v' a@ over a @'NodeInfo' k v a@.
305+nodeInfoMapFrom :: (From k v a -> From k v' a) -> NodeInfo k v a -> NodeInfo k v' a
306+nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
307+
308+-- |Map an effectful function which transforms @'From' k v a@ into a @f ('From' k v' a)@ over a @'NodeInfo' k v a@.
309+nodeInfoMapFromM :: Functor f => (From k v a -> f (From k v' a)) -> NodeInfo k v a -> f (NodeInfo k v' a)
310+nodeInfoMapFromM f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
311+
312+-- |Weaken a 'PatchDMapWithMove' to a 'PatchMapWithMove' by weakening the keys from @k a@ to @'Some' k@ and applying a given weakening function @v a -> v'@ to
313+-- values.
314+weakenPatchDMapWithMoveWith :: forall k v v'. (forall a. v a -> v') -> PatchDMapWithMove k v -> PatchMapWithMove (Some k) v'
315+weakenPatchDMapWithMoveWith f (PatchDMapWithMove p) = PatchMapWithMove $ weakenDMapWith g p
316+ where g :: forall a. NodeInfo k v a -> MapWithMove.NodeInfo (Some k) v'
317+ g ni = MapWithMove.NodeInfo
318+ { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
319+ From_Insert v -> MapWithMove.From_Insert $ f v
320+ From_Delete -> MapWithMove.From_Delete
321+ From_Move k -> MapWithMove.From_Move $ mkSome k
322+ , MapWithMove._nodeInfo_to = mkSome <$> getComposeMaybe (_nodeInfo_to ni)
323+ }
324+
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
326+-- dependency in the typing and all points are already @a@, hence the function to map each value to @v'@ is not higher rank.
327+patchDMapWithMoveToPatchMapWithMoveWith :: forall k v v' a. (v a -> v') -> PatchDMapWithMove (Const2 k a) v -> PatchMapWithMove k v'
328+patchDMapWithMoveToPatchMapWithMoveWith f (PatchDMapWithMove p) = PatchMapWithMove $ dmapToMapWith g p
329+ where g :: NodeInfo (Const2 k a) v a -> MapWithMove.NodeInfo k v'
330+ g ni = MapWithMove.NodeInfo
331+ { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
332+ From_Insert v -> MapWithMove.From_Insert $ f v
333+ From_Delete -> MapWithMove.From_Delete
334+ From_Move (Const2 k) -> MapWithMove.From_Move k
335+ , MapWithMove._nodeInfo_to = unConst2 <$> getComposeMaybe (_nodeInfo_to ni)
336+ }
337+
338+-- |"Strengthen" a @'PatchMapWithMove' k v@ into a @'PatchDMapWithMove ('Const2' k a)@; that is, turn a non-dependently-typed patch into a dependently typed
339+-- one but which always has a constant key type represented by 'Const2'. Apply the given function to each @v@ to produce a @v' a@.
340+-- Completemented by 'patchDMapWithMoveToPatchMapWithMoveWith'
341+const2PatchDMapWithMoveWith :: forall k v v' a. (v -> v' a) -> PatchMapWithMove k v -> PatchDMapWithMove (Const2 k a) v'
342+const2PatchDMapWithMoveWith f (PatchMapWithMove p) = PatchDMapWithMove $ DMap.fromDistinctAscList $ g <$> Map.toAscList p
343+ where g :: (k, MapWithMove.NodeInfo k v) -> DSum (Const2 k a) (NodeInfo (Const2 k a) v')
344+ g (k, ni) = Const2 k :=> NodeInfo
345+ { _nodeInfo_from = case MapWithMove._nodeInfo_from ni of
346+ MapWithMove.From_Insert v -> From_Insert $ f v
347+ MapWithMove.From_Delete -> From_Delete
348+ MapWithMove.From_Move fromKey -> From_Move $ Const2 fromKey
349+ , _nodeInfo_to = ComposeMaybe $ Const2 <$> MapWithMove._nodeInfo_to ni
350+ }
351+
352+-- | Apply the insertions, deletions, and moves to a given 'DMap'.
353+instance GCompare k => Patch (PatchDMapWithMove k v) where
354+ type PatchTarget (PatchDMapWithMove k v) = DMap k v
355+ apply (PatchDMapWithMove p) old = Just $! insertions `DMap.union` (old `DMap.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?
356+ where insertions = DMap.mapMaybeWithKey insertFunc p
357+ insertFunc :: forall a. k a -> NodeInfo k v a -> Maybe (v a)
358+ insertFunc _ ni = case _nodeInfo_from ni of
359+ From_Insert v -> Just v
360+ From_Move k -> DMap.lookup k old
361+ From_Delete -> Nothing
362+ deletions = DMap.mapMaybeWithKey deleteFunc p
363+ deleteFunc :: forall a. k a -> NodeInfo k v a -> Maybe (Constant () a)
364+ deleteFunc _ ni = case _nodeInfo_from ni of
365+ From_Delete -> Just $ Constant ()
366+ _ -> Nothing
367+
368+-- | Get the values that will be replaced, deleted, or moved if the given patch is applied to the given 'DMap'.
369+getDeletionsAndMoves :: GCompare k => PatchDMapWithMove k v -> DMap k v' -> DMap k (Product v' (ComposeMaybe k))
370+getDeletionsAndMoves (PatchDMapWithMove p) m = DMap.intersectionWithKey f m p
371+ where f _ v ni = Pair v $ _nodeInfo_to ni
src/Data/Patch/IntMap.hsnew file+76
@@ -0,0 +1,76 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE StandaloneDeriving #-}
7+{-# LANGUAGE TemplateHaskell #-}
8+{-# LANGUAGE TypeFamilies #-}
9+
10+-- | Module containing 'PatchIntMap', a 'Patch' for 'IntMap' which allows for
11+-- insert/update or delete of associations.
12+module Data.Patch.IntMap where
13+
14+import Control.Lens
15+import Data.IntMap.Strict (IntMap)
16+import qualified Data.IntMap.Strict as IntMap
17+import Data.Maybe
18+import Data.Monoid.DecidablyEmpty
19+#if !MIN_VERSION_base(4,11,0)
20+import Data.Semigroup (Semigroup (..))
21+#endif
22+import Data.Patch.Class
23+
24+-- | '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
26+-- and @Nothing@ means delete.
27+newtype PatchIntMap a = PatchIntMap { unPatchIntMap :: IntMap (Maybe a) }
28+ deriving ( Show, Read, Eq, Ord
29+ , Functor, Foldable, Traversable
30+ , Monoid, DecidablyEmpty
31+ )
32+
33+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
34+-- If the same key is modified by both patches, the one on the left will take
35+-- precedence.
36+deriving instance Semigroup (PatchIntMap v)
37+
38+makeWrapped ''PatchIntMap
39+
40+-- | Apply the insertions or deletions to a given 'IntMap'.
41+instance Patch (PatchIntMap a) where
42+ type PatchTarget (PatchIntMap a) = IntMap a
43+ apply (PatchIntMap p) v = if IntMap.null p then Nothing else Just $
44+ let removes = IntMap.filter isNothing p
45+ adds = IntMap.mapMaybe id p
46+ in IntMap.union adds $ v `IntMap.difference` removes
47+
48+instance FunctorWithIndex Int PatchIntMap
49+instance FoldableWithIndex Int PatchIntMap
50+instance TraversableWithIndex Int PatchIntMap where
51+ itraverse = itraversed . Indexed
52+ itraversed = _Wrapped .> itraversed <. traversed
53+
54+-- | 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@.
56+mapIntMapPatchWithKey :: (Int -> a -> b) -> PatchIntMap a -> PatchIntMap b
57+mapIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap $ IntMap.mapWithKey (\ k mv -> f k <$> mv) m
58+
59+-- | 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)@.
61+traverseIntMapPatchWithKey :: Applicative f => (Int -> a -> f b) -> PatchIntMap a -> f (PatchIntMap b)
62+traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (traverse . f) m
63+
64+-- | Extract all @a@s inserted/updated by the given @'PatchIntMap' a@.
65+patchIntMapNewElements :: PatchIntMap a -> [a]
66+patchIntMapNewElements (PatchIntMap m) = catMaybes $ IntMap.elems m
67+
68+-- | Convert the given @'PatchIntMap' a@ into an @'IntMap' a@ with all
69+-- the inserts/updates in the given patch.
70+patchIntMapNewElementsMap :: PatchIntMap a -> IntMap a
71+patchIntMapNewElementsMap (PatchIntMap m) = IntMap.mapMaybe id m
72+
73+-- | Subset the given @'IntMap' a@ to contain only the keys that would be
74+-- deleted by the given @'PatchIntMap' a@.
75+getDeletions :: PatchIntMap v -> IntMap v' -> IntMap v'
76+getDeletions (PatchIntMap m) v = IntMap.intersection v m
src/Data/Patch/Map.hsnew file+72
@@ -0,0 +1,72 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE StandaloneDeriving #-}
8+{-# LANGUAGE TemplateHaskell #-}
9+{-# LANGUAGE TypeFamilies #-}
10+
11+-- | 'Patch'es on 'Map' that consist only of insertions (including overwrites)
12+-- and deletions
13+module Data.Patch.Map where
14+
15+import Data.Patch.Class
16+
17+import Control.Lens
18+import Data.Map (Map)
19+import qualified Data.Map as Map
20+import Data.Maybe
21+import Data.Monoid.DecidablyEmpty
22+import Data.Semigroup (Semigroup (..), stimesIdempotentMonoid)
23+
24+-- | 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
26+-- deletions are represented as 'Nothing's
27+newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
28+ deriving ( Show, Read, Eq, Ord
29+ , Foldable, Traversable
30+ , DecidablyEmpty
31+ )
32+
33+-- | 'fmap'ping a 'PatchMap' will alter all of the values it will insert.
34+-- Deletions are unaffected.
35+deriving instance Functor (PatchMap k)
36+-- | The empty 'PatchMap' contains no insertions or deletions
37+deriving instance Ord k => Monoid (PatchMap k v)
38+
39+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
40+-- If the same key is modified by both patches, the one on the left will take
41+-- precedence.
42+instance Ord k => Semigroup (PatchMap k v) where
43+ PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
44+ -- PatchMap is idempotent, so stimes n is id for every n
45+ stimes = stimesIdempotentMonoid
46+
47+-- | Apply the insertions or deletions to a given 'Map'.
48+instance Ord k => Patch (PatchMap k v) where
49+ type PatchTarget (PatchMap k v) = Map k v
50+ {-# INLINABLE apply #-}
51+ apply (PatchMap 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?
52+ where insertions = Map.mapMaybeWithKey (const id) p
53+ deletions = Map.mapMaybeWithKey (const nothingToJust) p
54+ nothingToJust = \case
55+ Nothing -> Just ()
56+ Just _ -> Nothing
57+
58+instance FunctorWithIndex k (PatchMap k)
59+instance FoldableWithIndex k (PatchMap k)
60+instance TraversableWithIndex k (PatchMap k) where
61+ itraverse = itraversed . Indexed
62+ itraversed = _Wrapped .> itraversed <. traversed
63+
64+-- | Returns all the new elements that will be added to the 'Map'
65+patchMapNewElements :: PatchMap k v -> [v]
66+patchMapNewElements (PatchMap p) = catMaybes $ Map.elems p
67+
68+-- | Returns all the new elements that will be added to the 'Map'
69+patchMapNewElementsMap :: PatchMap k v -> Map k v
70+patchMapNewElementsMap (PatchMap p) = Map.mapMaybe id p
71+
72+makeWrapped ''PatchMap
src/Data/Patch/MapWithMove.hsnew file+312
@@ -0,0 +1,312 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6+{-# LANGUAGE LambdaCase #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE PatternGuards #-}
9+{-# LANGUAGE PatternSynonyms #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE StandaloneDeriving #-}
12+{-# LANGUAGE TemplateHaskell #-}
13+{-# LANGUAGE TypeApplications #-}
14+{-# LANGUAGE TypeFamilies #-}
15+{-# LANGUAGE ViewPatterns #-}
16+
17+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
18+-- another
19+module Data.Patch.MapWithMove
20+ ( PatchMapWithMove
21+ ( PatchMapWithMove
22+ , unPatchMapWithMove
23+ , ..
24+ )
25+ , patchMapWithMove
26+ , patchMapWithMoveInsertAll
27+ , insertMapKey
28+ , moveMapKey
29+ , swapMapKey
30+ , deleteMapKey
31+ , unsafePatchMapWithMove
32+ , patchMapWithMoveNewElements
33+ , patchMapWithMoveNewElementsMap
34+ , patchThatSortsMapWith
35+ , patchThatChangesAndSortsMapWith
36+ , patchThatChangesMap
37+
38+ -- * Node Info
39+ , NodeInfo
40+ ( NodeInfo
41+ , _nodeInfo_to
42+ , _nodeInfo_from
43+ , ..
44+ )
45+ , bitraverseNodeInfo
46+ , nodeInfoMapFrom
47+ , nodeInfoMapMFrom
48+ , nodeInfoSetTo
49+
50+ -- * From
51+ , From
52+ ( From_Insert
53+ , From_Delete
54+ , From_Move
55+ , ..
56+ )
57+ , bitraverseFrom
58+
59+ -- * To
60+ , To
61+ ) where
62+
63+import Data.Coerce
64+import Data.Kind (Type)
65+import Data.Patch.Class
66+import Data.Patch.MapWithPatchingMove (PatchMapWithPatchingMove(..), To)
67+import qualified Data.Patch.MapWithPatchingMove as PM -- already a transparent synonym
68+
69+import Control.Lens
70+import Data.List
71+import Data.Map (Map)
72+import qualified Data.Map as Map
73+import Data.Proxy
74+#if !MIN_VERSION_base(4,11,0)
75+import Data.Semigroup (Semigroup (..))
76+#endif
77+import Data.Traversable (foldMapDefault)
78+
79+-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
80+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
81+-- and vice versa. There should never be any unpaired From/To keys.
82+newtype PatchMapWithMove k (v :: Type) = PatchMapWithMove'
83+ { -- | Extract the underlying 'PatchMapWithPatchingMove k (Proxy v)'
84+ unPatchMapWithMove' :: PatchMapWithPatchingMove k (Proxy v)
85+ }
86+ deriving ( Show, Read, Eq, Ord
87+-- Haddock cannot handle documentation here before GHC 8.6
88+ ,
89+#if __GLASGOW_HASKELL__ >= 806
90+ -- | Compose patches having the same effect as applying the
91+ -- patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p .
92+ -- 'applyAlways' q@
93+#endif
94+ Semigroup
95+ , Monoid
96+ )
97+
98+pattern Coerce :: Coercible a b => a -> b
99+pattern Coerce x <- (coerce -> x)
100+ where Coerce x = coerce x
101+
102+{-# COMPLETE PatchMapWithMove #-}
103+pattern PatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
104+-- | Extract the representation of the 'PatchMapWithMove' as a map of
105+-- 'NodeInfo'.
106+unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
107+pattern PatchMapWithMove { unPatchMapWithMove } = PatchMapWithMove' (PatchMapWithPatchingMove (Coerce unPatchMapWithMove))
108+
109+_PatchMapWithMove
110+ :: Iso
111+ (PatchMapWithMove k0 v0)
112+ (PatchMapWithMove k1 v1)
113+ (Map k0 (NodeInfo k0 v0))
114+ (Map k1 (NodeInfo k1 v1))
115+_PatchMapWithMove = iso unPatchMapWithMove PatchMapWithMove
116+
117+instance Functor (PatchMapWithMove k) where
118+ fmap f = runIdentity . traverse (Identity . f)
119+
120+instance Foldable (PatchMapWithMove k) where
121+ foldMap = foldMapDefault
122+
123+instance Traversable (PatchMapWithMove k) where
124+ traverse =
125+ _PatchMapWithMove .
126+ traverse .
127+ traverse
128+
129+instance FunctorWithIndex k (PatchMapWithMove k)
130+instance FoldableWithIndex k (PatchMapWithMove k)
131+instance TraversableWithIndex k (PatchMapWithMove k) where
132+ itraverse = itraversed . Indexed
133+ itraversed =
134+ _PatchMapWithMove .>
135+ itraversed <.
136+ traverse
137+
138+-- | Create a 'PatchMapWithMove', validating it
139+patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
140+patchMapWithMove = fmap PatchMapWithMove' . PM.patchMapWithPatchingMove . coerce
141+
142+-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
143+patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
144+patchMapWithMoveInsertAll = PatchMapWithMove' . PM.patchMapWithPatchingMoveInsertAll
145+
146+-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
147+insertMapKey :: k -> v -> PatchMapWithMove k v
148+insertMapKey k v = PatchMapWithMove' $ PM.insertMapKey k v
149+
150+-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
151+--
152+-- @
153+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
154+-- @
155+moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
156+moveMapKey src dst = PatchMapWithMove' $ PM.moveMapKey src dst
157+
158+-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
159+--
160+-- @
161+-- let aMay = Map.lookup a map
162+-- bMay = Map.lookup b map
163+-- in maybe id (Map.insert a) (bMay <> aMay)
164+-- . maybe id (Map.insert b) (aMay <> bMay)
165+-- . Map.delete a . Map.delete b $ map
166+-- @
167+swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
168+swapMapKey src dst = PatchMapWithMove' $ PM.swapMapKey src dst
169+
170+-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
171+deleteMapKey :: k -> PatchMapWithMove k v
172+deleteMapKey = PatchMapWithMove' . PM.deleteMapKey
173+
174+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
175+--
176+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
177+unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
178+unsafePatchMapWithMove = coerce PM.unsafePatchMapWithPatchingMove
179+
180+-- | Apply the insertions, deletions, and moves to a given 'Map'
181+instance Ord k => Patch (PatchMapWithMove k v) where
182+ type PatchTarget (PatchMapWithMove k v) = Map k v
183+ apply (PatchMapWithMove' p) = apply p
184+
185+-- | Returns all the new elements that will be added to the 'Map'.
186+patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
187+patchMapWithMoveNewElements = PM.patchMapWithPatchingMoveNewElements . unPatchMapWithMove'
188+
189+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
190+patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
191+patchMapWithMoveNewElementsMap = PM.patchMapWithPatchingMoveNewElementsMap . unPatchMapWithMove'
192+
193+-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
194+-- its values using the given ordering function. The set keys of the 'Map' is
195+-- not changed.
196+patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
197+patchThatSortsMapWith cmp = PatchMapWithMove' . PM.patchThatSortsMapWith cmp
198+
199+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
200+-- will produce a 'Map' with the same values as the second 'Map' but with the
201+-- values sorted with the given ordering function.
202+patchThatChangesAndSortsMapWith :: (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
203+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
204+ where newList = Map.toList newByIndexUnsorted
205+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
206+
207+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
208+-- will produce the second 'Map'.
209+patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
210+patchThatChangesMap oldByIndex newByIndex = PatchMapWithMove' $
211+ PM.patchThatChangesMap oldByIndex newByIndex
212+
213+--
214+-- NodeInfo
215+--
216+
217+-- | Holds the information about each key: where its new value should come from,
218+-- and where its old value should go to
219+newtype NodeInfo k (v :: Type) = NodeInfo' { unNodeInfo' :: PM.NodeInfo k (Proxy v) }
220+
221+deriving instance (Show k, Show p) => Show (NodeInfo k p)
222+deriving instance (Read k, Read p) => Read (NodeInfo k p)
223+deriving instance (Eq k, Eq p) => Eq (NodeInfo k p)
224+deriving instance (Ord k, Ord p) => Ord (NodeInfo k p)
225+
226+{-# COMPLETE NodeInfo #-}
227+pattern NodeInfo :: To k -> From k v -> NodeInfo k v
228+_nodeInfo_to :: NodeInfo k v -> To k
229+_nodeInfo_from :: NodeInfo k v -> From k v
230+pattern NodeInfo { _nodeInfo_to, _nodeInfo_from } = NodeInfo'
231+ PM.NodeInfo
232+ { PM._nodeInfo_to = _nodeInfo_to
233+ , PM._nodeInfo_from = Coerce _nodeInfo_from
234+ }
235+
236+_NodeInfo
237+ :: Iso
238+ (NodeInfo k0 v0)
239+ (NodeInfo k1 v1)
240+ (PM.NodeInfo k0 (Proxy v0))
241+ (PM.NodeInfo k1 (Proxy v1))
242+_NodeInfo = iso unNodeInfo' NodeInfo'
243+
244+instance Functor (NodeInfo k) where
245+ fmap f = runIdentity . traverse (Identity . f)
246+
247+instance Foldable (NodeInfo k) where
248+ foldMap = foldMapDefault
249+
250+instance Traversable (NodeInfo k) where
251+ traverse = bitraverseNodeInfo pure
252+
253+bitraverseNodeInfo
254+ :: Applicative f
255+ => (k0 -> f k1)
256+ -> (v0 -> f v1)
257+ -> NodeInfo k0 v0 -> f (NodeInfo k1 v1)
258+bitraverseNodeInfo fk fv = fmap NodeInfo'
259+ . PM.bitraverseNodeInfo fk (\ ~Proxy -> pure Proxy) fv
260+ . coerce
261+
262+-- | Change the 'From' value of a 'NodeInfo'
263+nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
264+nodeInfoMapFrom f = coerce $ PM.nodeInfoMapFrom (unFrom' . f . From')
265+
266+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
267+-- 'Applicative', 'Monad', etc.) action to get the new value
268+nodeInfoMapMFrom
269+ :: Functor f
270+ => (From k v -> f (From k v))
271+ -> NodeInfo k v -> f (NodeInfo k v)
272+nodeInfoMapMFrom f = fmap NodeInfo'
273+ . PM.nodeInfoMapMFrom (fmap unFrom' . f . From')
274+ . coerce
275+
276+-- | Set the 'To' field of a 'NodeInfo'
277+nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
278+nodeInfoSetTo = coerce . PM.nodeInfoSetTo
279+
280+--
281+-- From
282+--
283+
284+-- | Describe how a key's new value should be produced
285+newtype From k (v :: Type) = From' { unFrom' :: PM.From k (Proxy v) }
286+
287+{-# COMPLETE From_Insert, From_Delete, From_Move #-}
288+
289+-- | Insert the given value here
290+pattern From_Insert :: v -> From k v
291+pattern From_Insert v = From' (PM.From_Insert v)
292+
293+-- | Delete the existing value, if any, from here
294+pattern From_Delete :: From k v
295+pattern From_Delete = From' PM.From_Delete
296+
297+-- | Move the value here from the given key
298+pattern From_Move :: k -> From k v
299+pattern From_Move k = From' (PM.From_Move k Proxy)
300+
301+bitraverseFrom
302+ :: Applicative f
303+ => (k0 -> f k1)
304+ -> (v0 -> f v1)
305+ -> From k0 v0 -> f (From k1 v1)
306+bitraverseFrom fk fv = fmap From'
307+ . PM.bitraverseFrom fk (\ ~Proxy -> pure Proxy) fv
308+ . coerce
309+
310+makeWrapped ''PatchMapWithMove
311+makeWrapped ''NodeInfo
312+makeWrapped ''From
src/Data/Patch/MapWithPatchingMove.hsnew file+432
@@ -0,0 +1,432 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE PatternGuards #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE StandaloneDeriving #-}
10+{-# LANGUAGE TemplateHaskell #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+
14+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15+-- another
16+module Data.Patch.MapWithPatchingMove
17+ ( PatchMapWithPatchingMove (..)
18+ , patchMapWithPatchingMove
19+ , patchMapWithPatchingMoveInsertAll
20+ , insertMapKey
21+ , moveMapKey
22+ , swapMapKey
23+ , deleteMapKey
24+ , unsafePatchMapWithPatchingMove
25+ , patchMapWithPatchingMoveNewElements
26+ , patchMapWithPatchingMoveNewElementsMap
27+ , patchThatSortsMapWith
28+ , patchThatChangesAndSortsMapWith
29+ , patchThatChangesMap
30+
31+ -- * Node Info
32+ , NodeInfo (..)
33+ , bitraverseNodeInfo
34+ , nodeInfoMapFrom
35+ , nodeInfoMapMFrom
36+ , nodeInfoSetTo
37+
38+ -- * From
39+ , From(..)
40+ , bitraverseFrom
41+
42+ -- * To
43+ , To
44+
45+ -- TODO internals module
46+ , Fixup (..)
47+ ) where
48+
49+import Data.Patch.Class
50+
51+import Control.Lens hiding (from, to)
52+import Control.Lens.TH (makeWrapped)
53+import Data.Align (align)
54+import Data.Foldable (toList)
55+import Data.Function
56+import Data.List
57+import Data.Map (Map)
58+import qualified Data.Map as Map
59+import Data.Maybe
60+#if !MIN_VERSION_base(4,11,0)
61+import Data.Semigroup (Semigroup (..))
62+#endif
63+import Data.Monoid.DecidablyEmpty
64+import Data.Set (Set)
65+import qualified Data.Set as Set
66+import Data.These (These (..))
67+
68+-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
69+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
70+-- and vice versa. There should never be any unpaired From/To keys.
71+newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
72+ { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
73+ unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
74+ }
75+
76+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
77+deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
78+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
79+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
80+
81+deriving instance ( Ord k
82+#if !MIN_VERSION_base(4,11,0)
83+ , Semigroup p
84+#endif
85+ , DecidablyEmpty p
86+ , Patch p
87+ ) => DecidablyEmpty (PatchMapWithPatchingMove k p)
88+
89+-- | Create a 'PatchMapWithPatchingMove', validating it
90+patchMapWithPatchingMove
91+ :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
92+patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
93+ where valid = forwardLinks == backwardLinks
94+ forwardLinks = Map.mapMaybe _nodeInfo_to m
95+ backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
96+ case _nodeInfo_from p of
97+ From_Move from _ -> Just (from, to)
98+ _ -> Nothing
99+
100+-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
101+patchMapWithPatchingMoveInsertAll
102+ :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
103+patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
104+ { _nodeInfo_from = From_Insert v
105+ , _nodeInfo_to = Nothing
106+ }
107+
108+-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
109+insertMapKey
110+ :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
111+insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
112+
113+-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
114+--
115+-- @
116+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
117+-- @
118+moveMapKey
119+ :: ( DecidablyEmpty p
120+#if !MIN_VERSION_base(4,11,0)
121+ , Semigroup p
122+#endif
123+ , Patch p
124+ )
125+ => Ord k => k -> k -> PatchMapWithPatchingMove k p
126+moveMapKey src dst
127+ | src == dst = mempty
128+ | otherwise =
129+ PatchMapWithPatchingMove $ Map.fromList
130+ [ (dst, NodeInfo (From_Move src mempty) Nothing)
131+ , (src, NodeInfo From_Delete (Just dst))
132+ ]
133+
134+-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
135+--
136+-- @
137+-- let aMay = Map.lookup a map
138+-- bMay = Map.lookup b map
139+-- in maybe id (Map.insert a) (bMay <> aMay)
140+-- . maybe id (Map.insert b) (aMay <> bMay)
141+-- . Map.delete a . Map.delete b $ map
142+-- @
143+swapMapKey
144+ :: ( DecidablyEmpty p
145+#if !MIN_VERSION_base(4,11,0)
146+ , Semigroup p
147+#endif
148+ , Patch p
149+ )
150+ => Ord k => k -> k -> PatchMapWithPatchingMove k p
151+swapMapKey src dst
152+ | src == dst = mempty
153+ | otherwise =
154+ PatchMapWithPatchingMove $ Map.fromList
155+ [ (dst, NodeInfo (From_Move src mempty) (Just src))
156+ , (src, NodeInfo (From_Move dst mempty) (Just dst))
157+ ]
158+
159+-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160+-- the mapping, equivalent to 'Map.delete'.
161+deleteMapKey
162+ :: k -> PatchMapWithPatchingMove k v
163+deleteMapKey k = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo From_Delete Nothing
164+
165+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithPatchingMove' k v@, without checking any invariants.
166+--
167+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithPatchingMove' are preserved; they will not be checked.
168+unsafePatchMapWithPatchingMove
169+ :: Map k (NodeInfo k p) -> PatchMapWithPatchingMove k p
170+unsafePatchMapWithPatchingMove = PatchMapWithPatchingMove
171+
172+-- | Apply the insertions, deletions, and moves to a given 'Map'
173+instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
174+ type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
175+ -- TODO: return Nothing sometimes
176+ -- Note: the strict application here is critical to ensuring that incremental
177+ -- merges don't hold onto all their prerequisite events forever; can we make
178+ -- this more robust?
179+ apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
180+ where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
181+ From_Insert v -> Just v
182+ From_Move k p -> applyAlways p <$> Map.lookup k old
183+ From_Delete -> Nothing
184+ deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
185+ From_Delete -> Just ()
186+ _ -> Nothing
187+
188+-- | Returns all the new elements that will be added to the 'Map'
189+patchMapWithPatchingMoveNewElements
190+ :: PatchMapWithPatchingMove k p -> [PatchTarget p]
191+patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
192+
193+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
194+patchMapWithPatchingMoveNewElementsMap
195+ :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
196+patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
197+ where f ni = case _nodeInfo_from ni of
198+ From_Insert v -> Just v
199+ From_Move _ _ -> Nothing
200+ From_Delete -> Nothing
201+
202+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
203+-- its values using the given ordering function. The set keys of the 'Map' is
204+-- not changed.
205+patchThatSortsMapWith
206+ :: (Ord k, Monoid p)
207+ => (PatchTarget p -> PatchTarget p -> Ordering)
208+ -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
209+patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
210+ where unsorted = Map.toList m
211+ sorted = sortBy (cmp `on` snd) unsorted
212+ f (to, _) (from, _) = if to == from then Nothing else
213+ Just (from, to)
214+ reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
215+ g (to, _) (from, _) = if to == from then Nothing else
216+ let Just movingTo = Map.lookup from reverseMapping
217+ in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
218+
219+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
220+-- will produce a 'Map' with the same values as the second 'Map' but with the
221+-- values sorted with the given ordering function.
222+patchThatChangesAndSortsMapWith
223+ :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
224+ => (PatchTarget p -> PatchTarget p -> Ordering)
225+ -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
226+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
227+ where newList = Map.toList newByIndexUnsorted
228+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
229+
230+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
231+-- will produce the second 'Map'.
232+-- Note: this will never produce a patch on a value.
233+patchThatChangesMap
234+ :: forall k p
235+ . (Ord k, Ord (PatchTarget p), Monoid p)
236+ => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
237+patchThatChangesMap oldByIndex newByIndex = patch
238+ where invert :: Map k (PatchTarget p) -> Map (PatchTarget p) (Set k)
239+ invert = Map.fromListWith (<>) . fmap (\(k, v) -> (v, Set.singleton k)) . Map.toList
240+ -- In the places where we use unionDistinct, a non-distinct key indicates a bug in this function
241+ unionDistinct :: forall k' v'. Ord k' => Map k' v' -> Map k' v' -> Map k' v'
242+ unionDistinct = Map.unionWith (error "patchThatChangesMap: non-distinct keys")
243+ unionPairDistinct :: (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k))
244+ unionPairDistinct (oldFroms, oldTos) (newFroms, newTos) = (unionDistinct oldFroms newFroms, unionDistinct oldTos newTos)
245+ -- Generate patch info for a single value
246+ -- Keys that are found in both the old and new sets will not be patched
247+ -- Keys that are found in only the old set will be moved to a new position if any are available; otherwise they will be deleted
248+ -- Keys that are found in only the new set will be populated by moving an old key if any are available; otherwise they will be inserted
249+ patchSingleValue :: PatchTarget p -> Set k -> Set k -> (Map k (From k p), Map k (To k))
250+ patchSingleValue v oldKeys newKeys = foldl' unionPairDistinct mempty $ align (toList $ oldKeys `Set.difference` newKeys) (toList $ newKeys `Set.difference` oldKeys) <&> \case
251+ This oldK -> (mempty, Map.singleton oldK Nothing) -- There's nowhere for this value to go, so we know we are deleting it
252+ That newK -> (Map.singleton newK $ From_Insert v, mempty) -- There's nowhere fo this value to come from, so we know we are inserting it
253+ These oldK newK -> (Map.singleton newK $ From_Move oldK mempty, Map.singleton oldK $ Just newK)
254+ -- Run patchSingleValue on a These. Missing old or new sets are considered empty
255+ patchSingleValueThese :: PatchTarget p -> These (Set k) (Set k) -> (Map k (From k p), Map k (To k))
256+ patchSingleValueThese v = \case
257+ This oldKeys -> patchSingleValue v oldKeys mempty
258+ That newKeys -> patchSingleValue v mempty newKeys
259+ These oldKeys newKeys -> patchSingleValue v oldKeys newKeys
260+ -- Generate froms and tos for all values, then merge them together
261+ (froms, tos) = foldl' unionPairDistinct mempty $ Map.mapWithKey patchSingleValueThese $ align (invert oldByIndex) (invert newByIndex)
262+ patch = unsafePatchMapWithPatchingMove $ align froms tos <&> \case
263+ This from -> NodeInfo from Nothing -- Since we don't have a 'to' record for this key, that must mean it isn't being moved anywhere, so it should be deleted.
264+ That to -> NodeInfo From_Delete to -- Since we don't have a 'from' record for this key, it must be getting deleted
265+ These from to -> NodeInfo from to
266+
267+--
268+-- NodeInfo
269+--
270+
271+-- | Holds the information about each key: where its new value should come from,
272+-- and where its old value should go to
273+data NodeInfo k p = NodeInfo
274+ { _nodeInfo_from :: !(From k p)
275+ -- ^ Where do we get the new value for this key?
276+ , _nodeInfo_to :: !(To k)
277+ -- ^ If the old value is being kept (i.e. moved rather than deleted or
278+ -- replaced), where is it going?
279+ }
280+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
281+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
282+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
283+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
284+
285+-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
286+-- the type families here, this doesn't it any bi- or tri-traversal class.
287+bitraverseNodeInfo
288+ :: Applicative f
289+ => (k0 -> f k1)
290+ -> (p0 -> f p1)
291+ -> (PatchTarget p0 -> f (PatchTarget p1))
292+ -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
293+bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
294+ <$> bitraverseFrom fk fp fpt from
295+ <*> traverse fk to
296+
297+-- | Change the 'From' value of a 'NodeInfo'
298+nodeInfoMapFrom
299+ :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
300+nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
301+
302+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
303+-- 'Applicative', 'Monad', etc.) action to get the new value
304+nodeInfoMapMFrom
305+ :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
306+nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
307+
308+-- | Set the 'To' field of a 'NodeInfo'
309+nodeInfoSetTo
310+ :: To k -> NodeInfo k v -> NodeInfo k v
311+nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
312+
313+--
314+-- From
315+--
316+
317+-- | Describe how a key's new value should be produced
318+data From k p
319+ = From_Insert (PatchTarget p) -- ^ Insert the given value here
320+ | From_Delete -- ^ Delete the existing value, if any, from here
321+ | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
322+
323+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
324+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
325+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
326+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
327+
328+-- | Traverse the 'From' over the key, patch, and patch target. Because of
329+-- the type families here, this doesn't it any bi- or tri-traversal class.
330+bitraverseFrom
331+ :: Applicative f
332+ => (k0 -> f k1)
333+ -> (p0 -> f p1)
334+ -> (PatchTarget p0 -> f (PatchTarget p1))
335+ -> From k0 p0 -> f (From k1 p1)
336+bitraverseFrom fk fp fpt = \case
337+ From_Insert pt -> From_Insert <$> fpt pt
338+ From_Delete -> pure From_Delete
339+ From_Move k p -> From_Move <$> fk k <*> fp p
340+
341+--
342+-- To
343+--
344+
345+-- | Describe where a key's old value will go. If this is 'Just', that means
346+-- the key's old value will be moved to the given other key; if it is 'Nothing',
347+-- that means it will be deleted.
348+type To = Maybe
349+
350+--
351+-- Fixup
352+--
353+
354+-- | Helper data structure used for composing patches using the monoid instance.
355+data Fixup k v
356+ = Fixup_Delete
357+ | Fixup_Update (These (From k v) (To k))
358+
359+-- | Compose patches having the same effect as applying the patches in turn:
360+-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
361+instance ( Ord k
362+#if !MIN_VERSION_base(4,11,0)
363+ , Semigroup p
364+#endif
365+ , DecidablyEmpty p
366+ , Patch p
367+ ) => Semigroup (PatchMapWithPatchingMove k p) where
368+ PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
369+ where
370+ connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
371+ h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
372+ h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
373+ (Just toAfter, From_Move fromBefore p)
374+ | fromBefore == toAfter && isEmpty p
375+ -> [(toAfter, Fixup_Delete)]
376+ | otherwise
377+ -> [ (toAfter, Fixup_Update (This editBefore))
378+ , (fromBefore, Fixup_Update (That mToAfter))
379+ ]
380+ (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
381+ (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
382+ (Nothing, _) -> []
383+ mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
384+ mergeFixups _ (Fixup_Update a) (Fixup_Update b)
385+ | This x <- a, That y <- b
386+ = Fixup_Update $ These x y
387+ | That y <- a, This x <- b
388+ = Fixup_Update $ These x y
389+ mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
390+ fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
391+ combineNodeInfos _ nia nib = NodeInfo
392+ { _nodeInfo_from = _nodeInfo_from nia
393+ , _nodeInfo_to = _nodeInfo_to nib
394+ }
395+ applyFixup _ ni = \case
396+ Fixup_Delete -> Nothing
397+ Fixup_Update u -> Just $ NodeInfo
398+ { _nodeInfo_from = case _nodeInfo_from ni of
399+ f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
400+ Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
401+ Just (From_Insert v) -> From_Insert $ applyAlways p' v
402+ Just From_Delete -> From_Delete
403+ Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
404+ _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
405+ , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
406+ }
407+ m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
408+ getHere :: These a b -> Maybe a
409+ getHere = \case
410+ This a -> Just a
411+ These a _ -> Just a
412+ That _ -> Nothing
413+ getThere :: These a b -> Maybe b
414+ getThere = \case
415+ This _ -> Nothing
416+ These _ b -> Just b
417+ That b -> Just b
418+
419+--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
420+-- | Compose patches having the same effect as applying the patches in turn:
421+-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
422+instance ( Ord k
423+#if !MIN_VERSION_base(4,11,0)
424+ , Semigroup p
425+#endif
426+ , DecidablyEmpty p
427+ , Patch p
428+ ) => Monoid (PatchMapWithPatchingMove k p) where
429+ mempty = PatchMapWithPatchingMove mempty
430+ mappend = (<>)
431+
432+makeWrapped ''PatchMapWithPatchingMove
src/Data/Semigroup/Additive.hsnew file+54
@@ -0,0 +1,54 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE TypeOperators #-}
3+{-# LANGUAGE TypeFamilies #-}
4+-- |
5+-- Module:
6+-- Data.Semigroup.Additive
7+-- Description:
8+-- This module defines a class for commutative semigroups, until it is moved
9+-- to another library.
10+module Data.Semigroup.Additive
11+ ( Additive
12+ ) where
13+
14+import Data.Functor.Const (Const (..))
15+import Data.Functor.Identity
16+import Data.Proxy
17+#if !MIN_VERSION_base(4,12,0)
18+-- for :*: and :.: semigroup instances
19+import Data.Orphans ()
20+#endif
21+#if !MIN_VERSION_base(4,11,0)
22+import Data.Semigroup (Semigroup (..))
23+#endif
24+import GHC.Generics
25+
26+-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
27+class Semigroup q => Additive q where
28+
29+-- | Trivial additive semigroup.
30+instance Additive ()
31+
32+-- | Product additive semigroup.
33+-- A Pair of additive semigroups gives rise to a additive semigroup
34+instance (Additive a, Additive b) => Additive (a, b)
35+
36+-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
37+-- Base does not define Monoid (Compose f g a) so this is the best we can
38+-- really do for functor composition.
39+instance Additive (f (g a)) => Additive ((f :.: g) a)
40+
41+-- | Product of additive semigroups, Functor style.
42+instance (Additive (f a), Additive (g a)) => Additive ((f :*: g) a)
43+
44+-- | Trivial additive semigroup, Functor style
45+instance Additive (Proxy x)
46+
47+-- | Const lifts additive semigroups into a functor.
48+instance Additive a => Additive (Const a x)
49+
50+-- | Identity lifts additive semigroups pointwise (at only one point)
51+instance Additive a => Additive (Identity a)
52+
53+-- | Functions lift additive semigroups pointwise.
54+instance Additive b => Additive (a -> b)
src/Data/WeakBag.hsdeleted−117
@@ -1,117 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−-- | This module defines the 'WeakBag' type, which represents a mutable
4−-- collection of items that does not cause the items to be retained in memory.
5−-- This is useful for situations where a value needs to be inspected or modified
6−-- if it is still alive, but can be ignored if it is dead.
7−module Data.WeakBag
8− ( WeakBag
9− , WeakBagTicket
10− , empty
11− , singleton
12− , insert
13− , traverse
14− , remove
15− ) where
16−
17−import Control.Exception
18−import Control.Monad hiding (forM_, mapM_)
19−import Control.Monad.IO.Class
20−import Data.Foldable (forM_, mapM_)
21−import Data.IntMap.Strict (IntMap)
22−import qualified Data.IntMap.Strict as IntMap
23−import Data.IORef
24−import System.Mem.Weak
25−
26−import Prelude hiding (mapM_, traverse)
27−
28−-- | A @WeakBag a@ holds a set of values of type @a@, but does not retain them -
29−-- that is, they can still be garbage-collected. As long as the @a@s remain
30−-- alive, the 'WeakBag' will continue to refer to them.
31−data WeakBag a = WeakBag
32− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
33− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a)))
34− }
35−
36−-- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned. If
37−-- the caller retains the ticket, the item is guranteed to stay in memory (and
38−-- thus in the 'WeakBag'). The ticket can also be used to remove the item from
39−-- the 'WeakBag' prematurely (i.e. while it is still alive), using 'remove'.
40−data WeakBagTicket = forall a. WeakBagTicket
41− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
42− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
43− }
44−
45−-- | Insert an item into a 'WeakBag'.
46−{-# INLINE insert #-}
47−insert :: a -- ^ The item
48− -> WeakBag a -- ^ The 'WeakBag' to insert into
49− -> IORef (Weak b) -- ^ An arbitrary value to be used in the following
50− -- callback
51− -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed
52− -- (whether automatically by the item being garbage
53− -- collected or manually via 'remove')
54− -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item
55− -- is retained and allows the item to be removed.
56−insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do
57− a' <- evaluate a
58− wbRef' <- evaluate wbRef
59− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
60− let cleanup = do
61− wb <- readIORef wbRef'
62− mb <- deRefWeak wb
63− forM_ mb $ \b -> do
64− csWithoutMe <- atomicModifyIORef children $ \cs ->
65− let !csWithoutMe = IntMap.delete myId cs
66− in (csWithoutMe, csWithoutMe)
67− when (IntMap.null csWithoutMe) $ finalizer b
68− return ()
69− return ()
70− wa <- mkWeakPtr a' $ Just cleanup
71− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
72− return $ WeakBagTicket
73− { _weakBagTicket_weakItem = wa
74− , _weakBagTicket_item = a'
75− }
76−
77−-- | Create an empty 'WeakBag'.
78−{-# INLINE empty #-}
79−empty :: IO (WeakBag a)
80−empty = {-# SCC "empty" #-} do
81− nextId <- newIORef 1
82− children <- newIORef IntMap.empty
83− let bag = WeakBag
84− { _weakBag_nextId = nextId
85− , _weakBag_children = children
86− }
87− return bag
88−
89−-- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with
90−-- 'empty', then using 'insert'.
91−{-# INLINE singleton #-}
92−singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
93−singleton a wbRef finalizer = {-# SCC "singleton" #-} do
94− bag <- empty
95− ticket <- insert a bag wbRef finalizer
96− return (bag, ticket)
97−
98−{-# INLINE traverse #-}
99−-- | Visit every node in the given list. If new nodes are appended during the
100−-- traversal, they will not be visited. Every live node that was in the list
101−-- when the traversal began will be visited exactly once; however, no guarantee
102−-- is made about the order of the traversal.
103−traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
104−traverse (WeakBag _ children) f = {-# SCC "traverse" #-} do
105− cs <- liftIO $ readIORef children
106− forM_ cs $ \c -> do
107− ma <- liftIO $ deRefWeak c
108− mapM_ f ma
109−
110−-- | Remove an item from the 'WeakBag'; does nothing if invoked multiple times
111−-- on the same 'WeakBagTicket'.
112−{-# INLINE remove #-}
113−remove :: WeakBagTicket -> IO ()
114−remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w
115−--TODO: Should 'remove' also drop the reference to the item?
116−
117−--TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hsdeleted−12
@@ -1,12 +0,0 @@
1−-- | This module exports all of the commonly-used functionality of Reflex; if
2−-- you are just getting started with Reflex, this is probably what you want.
3−module Reflex (module X) where
4−
5−import Reflex.Class as X
6−import Reflex.Dynamic as X
7−import Reflex.Dynamic.TH as X
8−import Reflex.Dynamic.Uniq as X
9−import Reflex.DynamicWriter as X
10−import Reflex.PerformEvent.Class as X
11−import Reflex.PostBuild.Class as X
12−import Reflex.Spider as X
src/Reflex/Class.hsdeleted−891
@@ -1,891 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE LambdaCase #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE NoMonomorphismRestriction #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE RecursiveDo #-}
12−{-# LANGUAGE ScopedTypeVariables #-}
13−{-# LANGUAGE StandaloneDeriving #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE TypeOperators #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−
18−-- | This module contains the Reflex interface, as well as a variety of
19−-- convenience functions for working with 'Event's, 'Behavior's, and other
20−-- signals.
21−module Reflex.Class
22− ( -- * Primitives
23− Reflex (..)
24− , coerceBehavior
25− , coerceEvent
26− , coerceDynamic
27− , MonadSample (..)
28− , MonadHold (..)
29− -- ** 'fan'-related types
30− , EventSelector (..)
31− -- ** 'Incremental'-related types
32− , Patch (..)
33− , PatchDMap (..)
34− , ComposeMaybe (..)
35− , PatchMap (..)
36− -- * Convenience functions
37− , constDyn
38− , pushAlways
39− -- ** Combining 'Event's
40− , leftmost
41− , mergeMap
42− , mergeList
43− , mergeWith
44− -- ** Breaking up 'Event's
45− , splitE
46− , fanEither
47− , fanThese
48− , fanMap
49− , dmapToThese
50− , EitherTag (..)
51− , eitherToDSum
52− , dsumToEither
53− -- ** Switching between 'Event's
54− , switchPromptly
55− -- ** Using 'Event's to sample 'Behavior's
56− , tag
57− , attach
58− , attachWith
59− , attachWithMaybe
60− -- ** Blocking an 'Event' based on a 'Behavior'
61− , gate
62− -- ** Combining 'Dynamic's
63− , distributeDMapOverDynPure
64− , distributeListOverDyn
65− , distributeListOverDynWith
66− , zipDyn
67− , zipDynWith
68− -- ** Accumulating state
69− , Accumulator (..)
70− , mapAccum_
71− , mapAccumM_
72− , mapAccumMaybe_
73− , mapAccumMaybeM_
74− , zipListWithEvent
75− , headE
76− , tailE
77− , headTailE
78− , switcher
79− -- * Debugging functions
80− , traceEvent
81− , traceEventWith
82− -- * Unsafe functions
83− , unsafeDynamic
84− -- * 'FunctorMaybe'
85− , FunctorMaybe (..)
86− , fforMaybe
87− , ffilter
88− -- * Miscellaneous convenience functions
89− , ffor
90− , MonadAdjust (..)
91− -- * Deprecated functions
92− , appendEvents
93− , onceE
94− , sequenceThese
95− ) where
96−
97−import Control.Applicative
98−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
99−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
100−import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
101−import Control.Monad.Trans.Cont (ContT ())
102−import Control.Monad.Trans.Except (ExceptT ())
103−import Control.Monad.Trans.RWS (RWST ())
104−import Control.Monad.Trans.Writer (WriterT ())
105−import Data.Align
106−import Data.Bifunctor
107−import Data.Coerce
108−import Data.Dependent.Map (DMap, DSum (..), GCompare (..), GOrdering (..))
109−import qualified Data.Dependent.Map as DMap
110−import Data.Dependent.Sum (ShowTag (..))
111−import Data.Either
112−import Data.Foldable
113−import Data.Functor.Bind hiding (join)
114−import qualified Data.Functor.Bind as Bind
115−import Data.Functor.Constant
116−import Data.Functor.Misc
117−import Data.Functor.Plus
118−import Data.GADT.Compare ((:~:) (..), GEq (..))
119−import Data.GADT.Show (GShow (..))
120−import Data.List.NonEmpty (NonEmpty (..))
121−import Data.Map (Map)
122−import qualified Data.Map as Map
123−import Data.Maybe
124−import Data.Monoid hiding (Alt, (<>))
125−import Data.Semigroup (Semigroup, sconcat, stimes, stimesIdempotentMonoid, (<>))
126−import Data.String
127−import Data.These
128−import Data.Traversable
129−import Data.Type.Coercion
130−
131−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
132−import Prelude hiding (foldl, mapM, mapM_, sequence, sequence_)
133−
134−import Debug.Trace (trace)
135−
136−-- | The 'Reflex' class contains all the primitive functionality needed for
137−-- Functional Reactive Programming (FRP). The @t@ type parameter indicates
138−-- which "timeline" is in use. Timelines are fully-independent FRP contexts,
139−-- and the type of the timeline determines the FRP engine to be used. For most
140−-- purposes, the 'Reflex.Spider' implementation is recommended.
141−class ( MonadHold t (PushM t)
142− , MonadSample t (PullM t)
143− , MonadFix (PushM t)
144− , Functor (Event t)
145− , Functor (Behavior t)
146− , Functor (Dynamic t)
147− , Applicative (Dynamic t) -- Necessary for GHC <= 7.8
148− , Monad (Dynamic t)
149− ) => Reflex t where
150− -- | A container for a value that can change over time. 'Behavior's can be
151− -- sampled at will, but it is not possible to be notified when they change
152− data Behavior t :: * -> *
153− -- | A stream of occurrences. During any given frame, an 'Event' is either
154− -- occurring or not occurring; if it is occurring, it will contain a value of
155− -- the given type (its "occurrence type")
156− data Event t :: * -> *
157− -- | A container for a value that can change over time and allows
158− -- notifications on changes. Basically a combination of a 'Behavior' and an
159− -- 'Event', with a rule that the 'Behavior' will change if and only if the
160− -- 'Event' fires.
161− data Dynamic t :: * -> *
162− -- | A container for a value that can change over time and allows
163− -- notifications on changes. Basically a combination of a 'Behavior' and an
164− -- 'Event', with a rule that the 'Behavior' will change if and only if the
165− -- 'Event' fires.
166− data Incremental t :: * -> *
167− -- | An 'Event' with no occurrences
168− never :: Event t a
169− -- | Create a 'Behavior' that always has the given value
170− 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
171− -- | Create an 'Event' from another 'Event'; the provided function can sample
172− -- 'Behavior's and hold 'Event's, and use the results to produce a occurring
173− -- (Just) or non-occurring (Nothing) result
174− push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
175− -- | A monad for doing complex push-based calculations efficiently
176− type PushM t :: * -> *
177− -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be
178− -- recomputed whenever any of the read 'Behavior's changes
179− pull :: PullM t a -> Behavior t a
180− -- | A monad for doing complex pull-based calculations efficiently
181− type PullM t :: * -> *
182− -- | Merge a collection of events; the resulting 'Event' will only occur if at
183− -- least one input event is occuring, and will contain all of the input keys
184− -- that are occurring simultaneously
185− merge :: GCompare k => DMap k (Event t) -> Event t (DMap k Identity) --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
186− -- | Efficiently fan-out an event to many destinations. This function should
187− -- be partially applied, and then the result applied repeatedly to create
188− -- child events
189− fan :: GCompare k => Event t (DMap k Identity) -> EventSelector t k --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
190− -- | Create an 'Event' that will occur whenever the currently-selected input
191− -- 'Event' occurs
192− switch :: Behavior t (Event t a) -> Event t a
193− -- | Create an 'Event' that will occur whenever the input event is occurring
194− -- and its occurrence value, another 'Event', is also occurring
195− coincidence :: Event t (Event t a) -> Event t a
196− -- | Extract the 'Behavior' of a 'Dynamic'.
197− current :: Dynamic t a -> Behavior t a
198− -- | Extract the 'Event' of the 'Dynamic'.
199− updated :: Dynamic t a -> Event t a
200− -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
201− -- recent firing of the given 'Event', if any.
202− unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
203− -- | Create a new 'Incremental'. The given 'PullM''s value must always change
204− -- in the same way that the accumulated application of patches would change
205− -- that value.
206− unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
207− -- | Create a merge whose parents can change over time
208− mergeIncremental :: GCompare k => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
209− -- | Extract the 'Behavior' component of an 'Incremental'
210− currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
211− -- | Extract the 'Event' component of an 'Incremental'
212− updatedIncremental :: Patch p => Incremental t p -> Event t p
213− -- | Convert an 'Incremental' to a 'Dynamic'
214− incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
215− -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
216− -- occurrence type
217− behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
218− -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
219− -- occurrence type
220− eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
221− -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
222− -- occurrence type
223− dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
224−
225−-- | Coerce a 'Behavior' between representationally-equivalent value types
226−coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
227−coerceBehavior = coerceWith $ behaviorCoercion Coercion
228−
229−-- | Coerce an 'Event' between representationally-equivalent occurrence types
230−coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
231−coerceEvent = coerceWith $ eventCoercion Coercion
232−
233−-- | Coerce a 'Dynamic' between representationally-equivalent value types
234−coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
235−coerceDynamic = coerceWith $ dynamicCoercion Coercion
236−
237−-- | A 'Patch' type represents a kind of change made to a datastructure.
238−class Patch p where
239− type PatchTarget p :: *
240− -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
241− -- 'Nothing'.
242− apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
243−
244−-- | We can't use @Compose Maybe@ instead of 'ComposeMaybe', because that would
245−-- make the 'f' parameter have a nominal type role. We need f to be
246−-- representational so that we can use safe 'coerce'.
247−newtype ComposeMaybe f a = ComposeMaybe { getComposeMaybe :: Maybe (f a) }
248−
249−deriving instance Functor f => Functor (ComposeMaybe f)
250−
251−instance Patch (Identity a) where
252− type PatchTarget (Identity a) = a
253− apply (Identity a) _ = Just a
254−
255−-- | A set of changes to a 'DMap'. Only DMap types are allowed for @a@.
256−newtype PatchDMap k v = PatchDMap (DMap k (ComposeMaybe v))
257−
258−instance GCompare k => Semigroup (PatchDMap k v) where
259− PatchDMap a <> PatchDMap b = PatchDMap $ a `mappend` b --TODO: Add a semigroup instance for DMap
260− -- PatchDMap is idempotent, so stimes n is id for every n
261−#if MIN_VERSION_semigroups(0,17,0)
262− stimes = stimesIdempotentMonoid
263−#else
264− times1p n x = case compare n 0 of
265− LT -> error "stimesIdempotentMonoid: negative multiplier"
266− EQ -> mempty
267− GT -> x
268−#endif
269−
270−instance GCompare k => Monoid (PatchDMap k v) where
271− mempty = PatchDMap mempty
272− mappend = (<>)
273−
274−instance GCompare k => Patch (PatchDMap k v) where
275− type PatchTarget (PatchDMap k v) = DMap k v
276− apply (PatchDMap diff) old = Just $! insertions `DMap.union` (old `DMap.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?
277− where insertions = DMap.mapMaybeWithKey (const $ getComposeMaybe) diff
278− deletions = DMap.mapMaybeWithKey (const $ nothingToJust . getComposeMaybe) diff
279− nothingToJust = \case
280− Nothing -> Just $ Constant ()
281− Just _ -> Nothing
282−
283−newtype PatchMap k v = PatchMap (Map k (Maybe v))
284−
285−instance Ord k => Patch (PatchMap k v) where
286− type PatchTarget (PatchMap k v) = Map k v
287− apply (PatchMap 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?
288− where insertions = Map.mapMaybeWithKey (const id) p
289− deletions = Map.mapMaybeWithKey (const nothingToJust) p
290− nothingToJust = \case
291− Nothing -> Just ()
292− Just _ -> Nothing
293−
294−instance Ord k => Semigroup (PatchMap k v) where
295− PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
296− -- PatchMap is idempotent, so stimes n is id for every n
297−#if MIN_VERSION_semigroups(0,17,0)
298− stimes = stimesIdempotentMonoid
299−#else
300− times1p n x = case compare n 0 of
301− LT -> error "stimesIdempotentMonoid: negative multiplier"
302− EQ -> mempty
303− GT -> x
304−#endif
305−
306−instance Ord k => Monoid (PatchMap k v) where
307− mempty = PatchMap mempty
308− mappend = (<>)
309−
310−-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
311−-- _must_ change when and only when the 'Event' fires, such that the
312−-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
313−-- if this is not the case, the resulting 'Dynamic' will behave
314−-- nondeterministically.
315−unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
316−unsafeDynamic = unsafeBuildDynamic . sample
317−
318−-- | Construct a 'Dynamic' value that never changes
319−constDyn :: Reflex t => a -> Dynamic t a
320−constDyn = pure
321−
322−-- | 'MonadSample' designates monads that can read the current value of a
323−-- 'Behavior'. This includes both 'PullM' and 'PushM'.
324−class (Applicative m, Monad m) => MonadSample t m | m -> t where
325− -- | Get the current value in the 'Behavior'
326− sample :: Behavior t a -> m a
327−
328−-- | 'MonadHold' designates monads that can create new 'Behavior's based on
329−-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
330−-- is required to create any stateful computations with Reflex.
331−class MonadSample t m => MonadHold t m where
332− -- | Create a new 'Behavior' whose value will initially be equal to the given
333− -- value and will be updated whenever the given 'Event' occurs. The update
334− -- takes effect immediately after the 'Event' occurs; if the occurrence that
335− -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
336− -- the 'Behavior', it will see the _old_ value of the 'Behavior', not the new
337− -- one.
338− hold :: a -> Event t a -> m (Behavior t a)
339− -- | Create a 'Dynamic' value using the given initial value that changes every
340− -- time the 'Event' occurs.
341− holdDyn :: a -> Event t a -> m (Dynamic t a)
342− -- | Create an 'Incremental' value using the given initial value that changes
343− -- every time the 'Event' occurs.
344− holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
345−
346−-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
347−-- key. This is much more efficient than filtering for each key with
348−-- 'fmapMaybe'.
349−newtype EventSelector t k = EventSelector
350− { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
351− -- determined by the type of the key, so this can be used to fan-out
352− -- 'Event's whose sub-'Event's have different types.
353− --
354− -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
355− -- (but equivalent to) using 'fmapMaybe' to select only the relevant
356− -- occurrences of an 'Event'.
357− select :: forall a. k a -> Event t a
358− }
359−
360−--------------------------------------------------------------------------------
361−-- Instances
362−--------------------------------------------------------------------------------
363−
364−instance MonadSample t m => MonadSample t (ReaderT r m) where
365− sample = lift . sample
366−
367−instance MonadHold t m => MonadHold t (ReaderT r m) where
368− hold a0 = lift . hold a0
369− holdDyn a0 = lift . holdDyn a0
370− holdIncremental a0 = lift . holdIncremental a0
371−
372−instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
373− sample = lift . sample
374−
375−instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
376− hold a0 = lift . hold a0
377− holdDyn a0 = lift . holdDyn a0
378− holdIncremental a0 = lift . holdIncremental a0
379−
380−instance MonadSample t m => MonadSample t (StateT s m) where
381− sample = lift . sample
382−
383−instance MonadHold t m => MonadHold t (StateT s m) where
384− hold a0 = lift . hold a0
385− holdDyn a0 = lift . holdDyn a0
386− holdIncremental a0 = lift . holdIncremental a0
387−
388−instance MonadSample t m => MonadSample t (ExceptT e m) where
389− sample = lift . sample
390−
391−instance MonadHold t m => MonadHold t (ExceptT e m) where
392− hold a0 = lift . hold a0
393− holdDyn a0 = lift . holdDyn a0
394− holdIncremental a0 = lift . holdIncremental a0
395−
396−instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
397− sample = lift . sample
398−
399−instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
400− hold a0 = lift . hold a0
401− holdDyn a0 = lift . holdDyn a0
402− holdIncremental a0 = lift . holdIncremental a0
403−
404−instance MonadSample t m => MonadSample t (ContT r m) where
405− sample = lift . sample
406−
407−instance MonadHold t m => MonadHold t (ContT r m) where
408− hold a0 = lift . hold a0
409− holdDyn a0 = lift . holdDyn a0
410− holdIncremental a0 = lift . holdIncremental a0
411−
412−--------------------------------------------------------------------------------
413−-- Convenience functions
414−--------------------------------------------------------------------------------
415−
416−-- | Create an 'Event' from another 'Event'. The provided function can sample
417−-- 'Behavior's and hold 'Event's.
418−pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
419−pushAlways f = push (fmap Just . f)
420−
421−-- | Flipped version of 'fmap'.
422−ffor :: Functor f => f a -> (a -> b) -> f b
423−ffor = flip fmap
424−
425−instance Reflex t => Applicative (Behavior t) where
426− pure = constant
427− f <*> x = pull $ sample f `ap` sample x
428− _ *> b = b
429− a <* _ = a
430−
431−instance Reflex t => Apply (Behavior t) where
432− (<.>) = (<*>)
433−
434−instance Reflex t => Bind (Behavior t) where
435− (>>-) = (>>=)
436−
437−instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
438− (/) = liftA2 (/)
439− fromRational = pure . fromRational
440− recip = fmap recip
441−
442−instance Reflex t => Functor (Behavior t) where
443− fmap f = pull . fmap f . sample
444−
445−instance (Reflex t, IsString a) => IsString (Behavior t a) where
446− fromString = pure . fromString
447−
448−instance Reflex t => Monad (Behavior t) where
449− a >>= f = pull $ sample a >>= sample . f
450− -- 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.
451− return = constant
452− fail = error "Monad (Behavior t) does not support fail"
453−
454−instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
455− mempty = constant mempty
456− mappend a b = pull $ liftM2 mappend (sample a) (sample b)
457− mconcat = pull . fmap mconcat . mapM sample
458−
459−instance (Reflex t, Num a) => Num (Behavior t a) where
460− (+) = liftA2 (+)
461− (-) = liftA2 (-)
462− (*) = liftA2 (*)
463− abs = fmap abs
464− fromInteger = pure . fromInteger
465− negate = fmap negate
466− signum = fmap signum
467−
468−instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
469− a <> b = pull $ liftM2 (<>) (sample a) (sample b)
470− sconcat = pull . fmap sconcat . mapM sample
471−#if MIN_VERSION_semigroups(0,17,0)
472− stimes n = fmap $ stimes n
473−#else
474− times1p n = fmap $ times1p n
475−#endif
476−
477−--TODO: See if there's a better class in the standard libraries already
478−-- | A class for values that combines filtering and mapping using 'Maybe'.
479−class FunctorMaybe f where
480− -- | Combined mapping and filtering function.
481− fmapMaybe :: (a -> Maybe b) -> f a -> f b
482−
483−instance FunctorMaybe [] where
484− fmapMaybe f = catMaybes . fmap f
485−
486−-- | Flipped version of 'fmapMaybe'.
487−fforMaybe :: FunctorMaybe f => f a -> (a -> Maybe b) -> f b
488−fforMaybe = flip fmapMaybe
489−
490−-- | Filter 'f a' using the provided predicate.
491−-- Relies on 'fforMaybe'.
492−ffilter :: FunctorMaybe f => (a -> Bool) -> f a -> f a
493−ffilter f = fmapMaybe $ \x -> if f x then Just x else Nothing
494−
495−-- | Left-biased event union (prefers left event on simultaneous
496−-- occurrence).
497−instance Reflex t => Alt (Event t) where
498− ev1 <!> ev2 = leftmost [ev1, ev2]
499−
500−-- | 'Event' intersection (convenient interface to 'coincidence').
501−instance Reflex t => Apply (Event t) where
502− evf <.> evx = coincidence (fmap (<$> evx) evf)
503−
504−-- | 'Event' intersection (convenient interface to 'coincidence').
505−instance Reflex t => Bind (Event t) where
506− evx >>- f = coincidence (f <$> evx)
507− join = coincidence
508−
509−instance Reflex t => Functor (Event t) where
510− fmap f = fmapMaybe $ Just . f
511−
512−instance Reflex t => FunctorMaybe (Event t) where
513− fmapMaybe f = push $ return . f
514−
515−-- | Never: @'zero' = 'never'@.
516−instance Reflex t => Plus (Event t) where
517− zero = never
518−
519−-- | Replace each occurrence value of the 'Event' with the value of the
520−-- 'Behavior' at the time of that occurrence.
521−tag :: Reflex t => Behavior t b -> Event t a -> Event t b
522−tag b = pushAlways $ \_ -> sample b
523−
524−-- | Create a new 'Event' that combines occurences of supplied 'Event' with the
525−-- current value of the 'Behavior'.
526−attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
527−attach = attachWith (,)
528−
529−-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
530−-- combining it with the current value of the 'Behavior'.
531−attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
532−attachWith f = attachWithMaybe $ \a b -> Just $ f a b
533−
534−-- | Create a new 'Event' by combining each occurence with the current value of
535−-- the 'Behavior'. The occurrence is discarded if the combining function returns
536−-- Nothing
537−attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
538−attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
539−
540−-- | Create a new 'Event' that only occurs only once, on the first occurence of
541−-- the supplied 'Event'.
542−headE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
543−headE e = do
544− rec be <- hold e $ fmap (const never) e'
545− let e' = switch be
546− return e'
547−
548−-- | Create a new 'Event' that occurs on all but the first occurence of the
549−-- supplied 'Event'.
550−tailE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
551−tailE e = snd <$> headTailE e
552−
553−-- | Create a tuple of two 'Event's with the first one occuring only the first
554−-- time the supplied 'Event' occurs and the second occuring on all but the first
555−-- occurence.
556−headTailE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a, Event t a)
557−headTailE e = do
558− eHead <- headE e
559− be <- hold never $ fmap (const e) eHead
560− return (eHead, switch be)
561−
562−-- | Split the supplied 'Event' into two individual 'Event's occuring at the
563−-- same time with the respective values from the tuple.
564−splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
565−splitE e = (fmap fst e, fmap snd e)
566−
567−-- | Print the supplied 'String' and the value of the 'Event' on each
568−-- occurence. This should /only/ be used for debugging.
569−--
570−-- Note: As with Debug.Trace.trace, the message will only be printed if the
571−-- 'Event' is actually used.
572−traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
573−traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
574−
575−-- | Print the output of the supplied function on each occurence of the
576−-- 'Event'. This should /only/ be used for debugging.
577−--
578−-- Note: As with Debug.Trace.trace, the message will only be printed if the
579−-- 'Event' is actually used.
580−traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
581−traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
582−
583−-- | Tag type for 'Either' to use it as a 'DSum'.
584−data EitherTag l r a where
585− LeftTag :: EitherTag l r l
586− RightTag :: EitherTag l r r
587−
588−instance GEq (EitherTag l r) where
589− geq a b = case (a, b) of
590− (LeftTag, LeftTag) -> Just Refl
591− (RightTag, RightTag) -> Just Refl
592− _ -> Nothing
593−
594−instance GCompare (EitherTag l r) where
595− gcompare a b = case (a, b) of
596− (LeftTag, LeftTag) -> GEQ
597− (LeftTag, RightTag) -> GLT
598− (RightTag, LeftTag) -> GGT
599− (RightTag, RightTag) -> GEQ
600−
601−instance GShow (EitherTag l r) where
602− gshowsPrec _ a = case a of
603− LeftTag -> showString "LeftTag"
604− RightTag -> showString "RightTag"
605−
606−instance (Show l, Show r) => ShowTag (EitherTag l r) Identity where
607− showTaggedPrec t n (Identity a) = case t of
608− LeftTag -> showsPrec n a
609− RightTag -> showsPrec n a
610−
611−-- | Convert 'Either' to a 'DSum'. Inverse of 'dsumToEither'.
612−eitherToDSum :: Either a b -> DSum (EitherTag a b) Identity
613−eitherToDSum = \case
614− Left a -> (LeftTag :=> Identity a)
615− Right b -> (RightTag :=> Identity b)
616−
617−-- | Convert 'DSum' to 'Either'. Inverse of 'eitherToDSum'.
618−dsumToEither :: DSum (EitherTag a b) Identity -> Either a b
619−dsumToEither = \case
620− (LeftTag :=> Identity a) -> Left a
621− (RightTag :=> Identity b) -> Right b
622−
623−-- | Extract the values of a 'DMap' of 'EitherTag's.
624−dmapToThese :: DMap (EitherTag a b) Identity -> Maybe (These a b)
625−dmapToThese m = case (DMap.lookup LeftTag m, DMap.lookup RightTag m) of
626− (Nothing, Nothing) -> Nothing
627− (Just (Identity a), Nothing) -> Just $ This a
628− (Nothing, Just (Identity b)) -> Just $ That b
629− (Just (Identity a), Just (Identity b)) -> Just $ These a b
630−
631−instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
632− (<>) = alignWith (mergeThese (<>))
633− sconcat = fmap sconcat . mergeList . toList
634−#if MIN_VERSION_semigroups(0,17,0)
635− stimes n = fmap $ stimes n
636−#else
637− times1p n = fmap $ times1p n
638−#endif
639−
640−instance (Semigroup a, Reflex t) => Monoid (Event t a) where
641− mempty = never
642− mappend = (<>)
643− mconcat = fmap sconcat . mergeList
644−
645−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
646−-- list occurs. If multiple occur at the same time they are folded from the left
647−-- with the given function.
648−mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
649−mergeWith f es = fmap (Prelude.foldl1 f . map (\(Const2 _ :=> Identity v) -> v) . DMap.toList)
650− . merge
651− . DMap.fromDistinctAscList
652− . map (\(k, v) -> Const2 k :=> v)
653− $ zip [0 :: Int ..] es
654−
655−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
656−-- list occurs. If multiple occur at the same time the value is the value of the
657−-- leftmost event.
658−leftmost :: Reflex t => [Event t a] -> Event t a
659−leftmost = mergeWith const
660−
661−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
662−-- list occurs and has a list of the values of all 'Event's occuring at that
663−-- time.
664−mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
665−mergeList [] = never
666−mergeList es = mergeWith (<>) $ map (fmap (:|[])) es
667−
668−-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
669−-- occurs if at least one of them occurs and has a map of values of all 'Event's
670−-- occuring at that time.
671−mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
672−mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
673−
674−-- | Split the event into separate events for 'Left' and 'Right' values.
675−fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
676−fanEither e =
677− let justLeft = either Just (const Nothing)
678− justRight = either (const Nothing) Just
679− in (fmapMaybe justLeft e, fmapMaybe justRight e)
680−
681−-- | Split the event into separate events for 'This' and 'That' values,
682−-- allowing them to fire simultaneously when the input value is 'These'.
683−fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
684−fanThese e =
685− let this (This x) = Just x
686− this (These x _) = Just x
687− this _ = Nothing
688− that (That y) = Just y
689− that (These _ y) = Just y
690− that _ = Nothing
691− in (fmapMaybe this e, fmapMaybe that e)
692−
693−-- | Split the event into an 'EventSelector' that allows efficient selection of
694−-- the individual 'Event's.
695−fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
696−fanMap = fan . fmap mapToDMap
697−
698−-- | Switches to the new event whenever it receives one; the new event is used
699−-- immediately, on the same frame that it is switched to
700−switchPromptly :: forall t m a. (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
701−switchPromptly ea0 eea = do
702− bea <- hold ea0 eea
703− let eLag = switch bea
704− eCoincidences = coincidence eea
705− return $ leftmost [eCoincidences, eLag]
706−
707−instance Reflex t => Align (Event t) where
708− nil = never
709− align ea eb = fmapMaybe dmapToThese $ merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
710−
711−-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
712−-- the 'Behavior' is true at the time of occurence.
713−gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
714−gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
715−
716−-- | Create a new behavior given a starting behavior and switch to a the behvior
717−-- carried by the event when it fires.
718−switcher :: (Reflex t, MonadHold t m)
719− => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
720−switcher b eb = pull . (sample <=< sample) <$> hold b eb
721−
722−-- | Combine two 'Dynamic's. The result will change whenever either (or both)
723−-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
724−zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
725−zipDyn = zipDynWith (,)
726−
727−-- | Combine two 'Dynamic's with a combining function. The result will change
728−-- whenever either (or both) input 'Dynamic' changes.
729−zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
730−zipDynWith f da db =
731− let eab = align (updated da) (updated db)
732− ec = flip push eab $ \o -> do
733− (a, b) <- case o of
734− This a -> do
735− b <- sample $ current db
736− return (a, b)
737− That b -> do
738− a <- sample $ current da
739− return (a, b)
740− These a b -> return (a, b)
741− return $ Just $ f a b
742− in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
743−
744−instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
745− mconcat = distributeListOverDynWith mconcat
746− mempty = constDyn mempty
747− mappend = zipDynWith mappend
748−
749−-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
750−-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
751−-- through the use of multiple uses of 'zipWithDyn' or 'Applicative' operators.
752−distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
753−distributeDMapOverDynPure dm = case DMap.toList dm of
754− [] -> constDyn DMap.empty
755− [k :=> v] -> fmap (DMap.singleton k . Identity) v
756− _ ->
757− let getInitial = DMap.traverseWithKey (\_ -> fmap Identity . sample . current) dm
758− edmPre = merge $ DMap.map updated dm
759− result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
760− olds <- sample $ current result
761− return $ DMap.unionWithKey (\_ _ new -> new) olds news
762− in result
763−
764−-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
765−distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
766−distributeListOverDyn = distributeListOverDynWith id
767−
768−-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
769−distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
770−distributeListOverDynWith f = fmap (f . map (\(Const2 _ :=> Identity v) -> v) . DMap.toList) . distributeDMapOverDynPure . DMap.fromList . map (\(k, v) -> Const2 k :=> v) . zip [0 :: Int ..]
771−
772−
773−--------------------------------------------------------------------------------
774−-- Accumulator
775−--------------------------------------------------------------------------------
776−
777−-- | An 'Accumulator' type can be built by accumulating occurrences of an
778−-- 'Event'.
779−class Reflex t => Accumulator t f | f -> t where
780− accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
781− accum f = accumMaybe $ \v o -> Just $ f v o
782− accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
783− accumM f = accumMaybeM $ \v o -> Just <$> f v o
784− accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
785− accumMaybe f = accumMaybeM $ \v o -> return $ f v o
786− accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
787− mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
788− mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
789− mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
790− mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
791− mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
792− mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
793− mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
794−
795−-- | Accumulate occurrences of an 'Event', producing an output occurrence each
796−-- time. Discard the underlying 'Accumulator'.
797−mapAccum_ :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (Event t c)
798−mapAccum_ f z e = do
799− (_ :: Behavior t a, result) <- mapAccum f z e
800− return result
801−
802−-- | Accumulate occurrences of an 'Event', possibly producing an output
803−-- occurrence each time. Discard the underlying 'Accumulator'.
804−mapAccumMaybe_ :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (Event t c)
805−mapAccumMaybe_ f z e = do
806− (_ :: Behavior t a, result) <- mapAccumMaybe f z e
807− return result
808−
809−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
810−-- an output occurrence each time. Discard the underlying 'Accumulator'.
811−mapAccumM_ :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (Event t c)
812−mapAccumM_ f z e = do
813− (_ :: Behavior t a, result) <- mapAccumM f z e
814− return result
815−
816−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
817−-- producing an output occurrence each time. Discard the underlying
818−-- 'Accumulator'.
819−mapAccumMaybeM_ :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (Event t c)
820−mapAccumMaybeM_ f z e = do
821− (_ :: Behavior t a, result) <- mapAccumMaybeM f z e
822− return result
823−
824−instance Reflex t => Accumulator t (Dynamic t) where
825− accumMaybeM f z e = do
826− rec let e' = flip push e $ \o -> do
827− v <- sample $ current d'
828− f v o
829− d' <- holdDyn z e'
830− return d'
831− mapAccumMaybeM f z e = do
832− rec let e' = flip push e $ \o -> do
833− v <- sample $ current d'
834− result <- f v o
835− return $ case result of
836− (Nothing, Nothing) -> Nothing
837− _ -> Just result
838− d' <- holdDyn z $ fmapMaybe fst e'
839− return (d', fmapMaybe snd e')
840−
841−instance Reflex t => Accumulator t (Behavior t) where
842− accumMaybeM f z e = current <$> accumMaybeM f z e
843− mapAccumMaybeM f z e = first current <$> mapAccumMaybeM f z e
844−
845−instance Reflex t => Accumulator t (Event t) where
846− accumMaybeM f z e = updated <$> accumMaybeM f z e
847− mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
848−
849−-- | Create a new 'Event' by combining each occurence with the next value of the
850−-- list using the supplied function. If the list runs out of items, all
851−-- subsequent 'Event' occurrences will be ignored.
852−zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
853−zipListWithEvent f l e = do
854− let f' a b = case a of
855− h:t -> (Just t, Just $ f h b)
856− _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
857− mapAccumMaybe_ f' l e
858−
859−class (Reflex t, Monad m) => MonadAdjust t m | m -> t where
860− sequenceDMapWithAdjust :: GCompare k => DMap k m -> Event t (PatchDMap k m) -> m (DMap k Identity, Event t (PatchDMap k Identity))
861−
862−instance (Reflex t, MonadAdjust t m) => MonadAdjust t (ReaderT r m) where
863− sequenceDMapWithAdjust dm0 dm' = do
864− r <- ask
865− let loweredDm0 = DMap.map (`runReaderT` r) dm0
866− loweredDm' = ffor dm' $ \(PatchDMap p) -> PatchDMap $
867− DMap.map (\(ComposeMaybe mv) -> ComposeMaybe $ fmap (`runReaderT` r) mv) p
868− lift $ sequenceDMapWithAdjust loweredDm0 loweredDm'
869−
870−--------------------------------------------------------------------------------
871−-- Deprecated functions
872−--------------------------------------------------------------------------------
873−
874−-- | Create a new 'Event' that occurs if at least one of the supplied 'Event's
875−-- occurs. If both occur at the same time they are combined using 'mappend'.
876−{-# DEPRECATED appendEvents "If a 'Semigroup a' instance is available, use 'mappend'; otherwise, use 'alignWith (mergeThese mappend)' instead" #-}
877−appendEvents :: (Reflex t, Monoid a) => Event t a -> Event t a -> Event t a
878−appendEvents = alignWith $ mergeThese mappend
879−
880−-- | Alias for 'headE'
881−{-# DEPRECATED onceE "Use 'headE' instead" #-}
882−onceE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
883−onceE = headE
884−
885−{-# DEPRECATED sequenceThese "Use bisequenceA or bisequence from the bifunctors package instead" #-}
886−{-# ANN sequenceThese "HLint: ignore Use fmap" #-}
887−sequenceThese :: Monad m => These (m a) (m b) -> m (These a b)
888−sequenceThese t = case t of
889− This ma -> liftM This ma
890− These ma mb -> liftM2 These ma mb
891− That mb -> liftM That mb
src/Reflex/Dynamic.hsdeleted−561
@@ -1,561 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoMonomorphismRestriction #-}
9−{-# LANGUAGE PolyKinds #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−-- | This module contains various functions for working with 'Dynamic' values.
16−-- 'Dynamic' and its primitives have been moved to the 'Reflex' class.
17−module Reflex.Dynamic
18− ( -- * Basics
19− Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update
20− , current
21− , updated
22− , holdDyn
23− , constDyn
24− , uniqDyn
25− , uniqDynBy
26− , count
27− , toggle
28− , switchPromptlyDyn
29− , tagPromptlyDyn
30− , attachPromptlyDyn
31− , attachPromptlyDynWith
32− , attachPromptlyDynWithMaybe
33− , foldDyn
34− , foldDynM
35− , foldDynMaybe
36− , foldDynMaybeM
37− , joinDynThroughMap
38− , traceDyn
39− , traceDynWith
40− , splitDynPure
41− , distributeDMapOverDynPure
42− , Demux
43− , demux
44− , demuxed
45− -- Things that probably aren't very useful:
46− , HList (..)
47− , FHList (..)
48− , collectDynPure
49− , distributeFHListOverDynPure
50− -- Unsafe
51− , unsafeDynamic
52− -- * Deprecated functions
53− , apDyn
54− , attachDyn
55− , attachDynWith
56− , attachDynWithMaybe
57− , collectDyn
58− , combineDyn
59− , distributeDMapOverDyn
60− , distributeFHListOverDyn
61− , forDyn
62− , forDynM
63− , getDemuxed
64− , joinDyn
65− , mapDyn
66− , mapDynM
67− , mconcatDyn
68− , nubDyn
69− , splitDyn
70− , tagDyn
71− ) where
72−
73−import Prelude hiding (mapM, mapM_)
74−
75−import Data.Functor.Misc
76−import Reflex.Class
77−
78−import Control.Applicative ((<*>))
79−import Control.Monad hiding (forM, forM_, mapM, mapM_)
80−import Control.Monad.Fix
81−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
82−import Data.Align
83−import Data.Dependent.Map (DMap)
84−import qualified Data.Dependent.Map as DMap
85−import Data.Dependent.Sum (DSum (..))
86−import Data.GADT.Compare ((:~:) (..), GCompare (..), GEq (..), GOrdering (..))
87−import Data.Map (Map)
88−import Data.Monoid
89−import Data.These
90−
91−import Debug.Trace
92−
93−-- | Create a new 'Dynamic' that only signals changes if the values actually
94−-- changed.
95−uniqDyn :: (Reflex t, Eq a) => Dynamic t a -> Dynamic t a
96−uniqDyn = uniqDynBy (==)
97−
98−-- | Create a new 'Dynamic' that changes only when the underlying 'Dynamic'
99−-- changes and the given function returns 'False' when given both the old and
100−-- the new values.
101−uniqDynBy :: Reflex t => (a -> a -> Bool) -> Dynamic t a -> Dynamic t a
102−uniqDynBy eq d =
103− let e' = attachWithMaybe (\x x' -> if x' `eq` x then Nothing else Just x') (current d) (updated d)
104− in unsafeDynamic (current d) e'
105−
106−-- | Create a 'Dynamic' using the initial value and change it each time the
107−-- 'Event' occurs using a folding function on the previous value and the value
108−-- of the 'Event'.
109−foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b)
110−foldDyn = accum . flip
111−
112−-- | Like 'foldDyn', but the combining function is a 'PushM' action, so it
113−-- can 'sample' existing 'Behaviors' and 'hold' new ones.
114−foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b)
115−foldDynM = accumM . flip
116−
117−-- | Create a 'Dynamic' using the provided initial value and change it each time
118−-- the provided 'Event' occurs, using a function to combine the old value with
119−-- the 'Event''s value. If the function returns 'Nothing', the value is not
120−-- changed; this is distinct from returning 'Just' the old value, since the
121−-- 'Dynamic''s 'updated' 'Event' will fire in the 'Just' case, and will not fire
122−-- in the 'Nothing' case.
123−foldDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> Maybe b) -> b -> Event t a -> m (Dynamic t b)
124−foldDynMaybe = accumMaybe . flip
125−
126−-- | Like 'foldDynMaybe', but the combining function is a 'PushM' action, so it
127−-- can 'sample' existing 'Behaviors' and 'hold' new ones.
128−foldDynMaybeM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe b)) -> b -> Event t a -> m (Dynamic t b)
129−foldDynMaybeM = accumMaybeM . flip
130−
131−-- | Create a new 'Dynamic' that counts the occurences of the 'Event'.
132−count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)
133−count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e
134−
135−-- | Create a new 'Dynamic' using the initial value that flips its
136−-- value every time the 'Event' occurs.
137−toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool)
138−toggle = foldDyn (const not)
139−
140−-- | Switches to the new 'Event' whenever it receives one. Switching occurs
141−-- *before* the inner 'Event' fires - so if the 'Dynamic' changes and both the
142−-- old and new inner Events fire simultaneously, the output will fire with the
143−-- value of the *new* 'Event'.
144−switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
145−switchPromptlyDyn de =
146− let eLag = switch $ current de
147− eCoincidences = coincidence $ updated de
148− in leftmost [eCoincidences, eLag]
149−
150−-- | Split a 'Dynamic' pair into a pair of 'Dynamic's
151−splitDynPure :: Reflex t => Dynamic t (a, b) -> (Dynamic t a, Dynamic t b)
152−splitDynPure d = (fmap fst d, fmap snd d)
153−
154−-- | Create a 'Dynamic' with a 'DMap' of values out of a 'DMap' of 'Dynamic'
155−-- values. The resulting 'Dynamic' will change whenever one of the input
156−-- 'Dynamic's changes.
157−--
158−-- This function's implementation is more efficient than simply using
159−-- 'zipDynWith' or applicative syntax to achieve the same result, especially for
160−-- maps with many elements.
161−distributeMapOverDynPure :: (Reflex t, Ord k) => Map k (Dynamic t v) -> Dynamic t (Map k v)
162−distributeMapOverDynPure = fmap dmapToMap . distributeDMapOverDynPure . mapWithFunctorToDMap
163−
164−--TODO: Generalize this to functors other than Maps
165−-- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic'
166−-- with the current values of the 'Dynamic's in a map.
167−joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)
168−joinDynThroughMap = joinDyn . fmap distributeMapOverDynPure
169−
170−-- | Print the value of the 'Dynamic' on each change and prefix it
171−-- with the provided string. This should /only/ be used for debugging.
172−--
173−-- Note: Just like Debug.Trace.trace, the value will only be shown if something
174−-- else in the system is depending on it.
175−traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a
176−traceDyn s = traceDynWith $ \x -> s <> ": " <> show x
177−
178−-- | Print the result of applying the provided function to the value
179−-- of the 'Dynamic' on each change. This should /only/ be used for
180−-- debugging.
181−--
182−-- Note: Just like Debug.Trace.trace, the value will only be shown if something
183−-- else in the system is depending on it.
184−traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a
185−traceDynWith f d =
186− let e' = traceEventWith f $ updated d
187− getV0 = do
188− x <- sample $ current d
189− trace (f x) $ return x
190− in unsafeBuildDynamic getV0 e'
191−
192−-- | Replace the value of the 'Event' with the current value of the 'Dynamic'
193−-- each time the 'Event' occurs.
194−--
195−-- Note: `tagPromptlyDyn d e` differs from `tag (current d) e` in the case that `e` is firing
196−-- at the same time that `d` is changing. With `tagPromptlyDyn d e`, the *new* value of `d`
197−-- will replace the value of `e`, whereas with `tag (current d) e`, the *old* value
198−-- will be used, since the 'Behavior' won't be updated until the end of the frame.
199−-- Additionally, this means that the output 'Event' may not be used to directly change
200−-- the input 'Dynamic', because that would mean its value depends on itself. When creating
201−-- cyclic data flows, generally `tag (current d) e` is preferred.
202−tagPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
203−tagPromptlyDyn = attachPromptlyDynWith const
204−
205−-- | Attach the current value of the 'Dynamic' to the value of the
206−-- 'Event' each time it occurs.
207−--
208−-- Note: `attachPromptlyDyn d` is not the same as `attach (current d)`. See 'tagPromptlyDyn' for details.
209−attachPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
210−attachPromptlyDyn = attachPromptlyDynWith (,)
211−
212−-- | Combine the current value of the 'Dynamic' with the value of the
213−-- 'Event' each time it occurs.
214−--
215−-- Note: `attachPromptlyDynWith f d` is not the same as `attachWith f (current d)`. See 'tagPromptlyDyn' for details.
216−attachPromptlyDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
217−attachPromptlyDynWith f = attachPromptlyDynWithMaybe $ \a b -> Just $ f a b
218−
219−-- | Create a new 'Event' by combining the value at each occurence with the
220−-- current value of the 'Dynamic' value and possibly filtering if the combining
221−-- function returns 'Nothing'.
222−--
223−-- Note: `attachPromptlyDynWithMaybe f d` is not the same as `attachWithMaybe f
224−-- (current d)`. See 'tagPromptlyDyn' for details.
225−attachPromptlyDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
226−attachPromptlyDynWithMaybe f d e =
227− let e' = attach (current d) e
228− in fforMaybe (align e' $ updated d) $ \case
229− This (a, b) -> f a b -- Only the tagging event is firing, so use that
230− These (_, b) a -> f a b -- Both events are firing, so use the newer value
231− That _ -> Nothing -- The tagging event isn't firing, so don't fire
232−
233−--------------------------------------------------------------------------------
234−-- Demux
235−--------------------------------------------------------------------------------
236−
237−-- | Represents a time changing value together with an 'EventSelector' that can
238−-- efficiently detect when the underlying 'Dynamic' has a particular value.
239−-- This is useful for representing data like the current selection of a long
240−-- list.
241−--
242−-- Semantically,
243−--
244−-- > demuxed (demux d) k === fmap (== k) d
245−--
246−-- However, the when getDemuxed is used multiple times, the complexity is only
247−-- /O(log(n))/, rather than /O(n)/ for fmap.
248−data Demux t k = Demux { demuxValue :: Behavior t k
249− , demuxSelector :: EventSelector t (Const2 k Bool)
250− }
251−
252−-- | Demultiplex an input value to a 'Demux' with many outputs. At any given
253−-- time, whichever output is indicated by the given 'Dynamic' will be 'True'.
254−demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k
255−demux k = Demux (current k)
256− (fan $ attachWith (\k0 k1 -> if k0 == k1
257− then DMap.empty
258− else DMap.fromList [Const2 k0 :=> Identity False,
259− Const2 k1 :=> Identity True])
260− (current k) (updated k))
261−
262−-- | Select a particular output of the 'Demux'; this is equivalent to (but much
263−-- faster than) mapping over the original 'Dynamic' and checking whether it is
264−-- equal to the given key.
265−demuxed :: (Reflex t, Eq k) => Demux t k -> k -> Dynamic t Bool
266−demuxed d k =
267− let e = select (demuxSelector d) (Const2 k)
268− in unsafeBuildDynamic (fmap (==k) $ sample $ demuxValue d) e
269−
270−--------------------------------------------------------------------------------
271−-- collectDyn
272−--------------------------------------------------------------------------------
273−
274−--TODO: This whole section is badly in need of cleanup
275−
276−-- | A heterogeneous list whose type and length are fixed statically. This is
277−-- reproduced from the 'HList' package due to integration issues, and because
278−-- very little other functionality from that library is needed.
279−data HList (l::[*]) where
280− HNil :: HList '[]
281− HCons :: e -> HList l -> HList (e ': l)
282−
283−infixr 2 `HCons`
284−
285−type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
286−type instance HRevApp '[] l = l
287−type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
288−
289−hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
290−hRevApp HNil l = l
291−hRevApp (HCons x l) l' = hRevApp l (HCons x l')
292−
293−hReverse :: HList l -> HList (HRevApp l '[])
294−hReverse l = hRevApp l HNil
295−
296−hBuild :: (HBuild' '[] r) => r
297−hBuild = hBuild' HNil
298−
299−class HBuild' l r where
300− hBuild' :: HList l -> r
301−
302−instance (l' ~ HRevApp l '[])
303− => HBuild' l (HList l') where
304− hBuild' = hReverse
305−
306−instance HBuild' (a ': l) r
307− => HBuild' l (a->r) where
308− hBuild' l x = hBuild' (HCons x l)
309−
310−-- | Like 'HList', but with a functor wrapping each element.
311−data FHList f l where
312− FHNil :: FHList f '[]
313− FHCons :: f e -> FHList f l -> FHList f (e ': l)
314−
315−instance GEq (HListPtr l) where
316− HHeadPtr `geq` HHeadPtr = Just Refl
317− HHeadPtr `geq` HTailPtr _ = Nothing
318− HTailPtr _ `geq` HHeadPtr = Nothing
319− HTailPtr a `geq` HTailPtr b = a `geq` b
320−
321−instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dmapTo*HList will break
322− HHeadPtr `gcompare` HHeadPtr = GEQ
323− HHeadPtr `gcompare` HTailPtr _ = GLT
324− HTailPtr _ `gcompare` HHeadPtr = GGT
325− HTailPtr a `gcompare` HTailPtr b = a `gcompare` b
326−
327−data HListPtr l a where
328− HHeadPtr :: HListPtr (h ': t) h
329− HTailPtr :: HListPtr t a -> HListPtr (h ': t) a
330−
331−fhlistToDMap :: forall (f :: * -> *) l. FHList f l -> DMap (HListPtr l) f
332−fhlistToDMap = DMap.fromList . go
333− where go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]
334− go = \case
335− FHNil -> []
336− FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)
337−
338−class RebuildSortedHList l where
339− rebuildSortedFHList :: [DSum (HListPtr l) f] -> FHList f l
340− rebuildSortedHList :: [DSum (HListPtr l) Identity] -> HList l
341−
342−instance RebuildSortedHList '[] where
343− rebuildSortedFHList l = case l of
344− [] -> FHNil
345− _ : _ -> error "rebuildSortedFHList{'[]}: empty list expected"
346− rebuildSortedHList l = case l of
347− [] -> HNil
348− _ : _ -> error "rebuildSortedHList{'[]}: empty list expected"
349−
350−instance RebuildSortedHList t => RebuildSortedHList (h ': t) where
351− rebuildSortedFHList l = case l of
352− ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
353− _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected"
354− rebuildSortedHList l = case l of
355− ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
356− _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected"
357−
358−dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) Identity -> HList l
359−dmapToHList = rebuildSortedHList . DMap.toList
360−
361−-- | Collect a hetereogeneous list whose elements are all 'Dynamic's into a
362−-- single 'Dynamic' whose value represents the current values of all of the
363−-- input 'Dynamic's.
364−distributeFHListOverDynPure :: (Reflex t, RebuildSortedHList l) => FHList (Dynamic t) l -> Dynamic t (HList l)
365−distributeFHListOverDynPure l = fmap dmapToHList $ distributeDMapOverDynPure $ fhlistToDMap l
366−
367−class AllAreFunctors (f :: a -> *) (l :: [a]) where
368− type FunctorList f l :: [*]
369− toFHList :: HList (FunctorList f l) -> FHList f l
370− fromFHList :: FHList f l -> HList (FunctorList f l)
371−
372−instance AllAreFunctors f '[] where
373− type FunctorList f '[] = '[]
374− toFHList l = case l of
375− HNil -> FHNil
376−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
377− _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
378−#endif
379− fromFHList FHNil = HNil
380−
381−instance AllAreFunctors f t => AllAreFunctors f (h ': t) where
382− type FunctorList f (h ': t) = f h ': FunctorList f t
383− toFHList l = case l of
384− a `HCons` b -> a `FHCons` toFHList b
385−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
386− _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
387−#endif
388− fromFHList (a `FHCons` b) = a `HCons` fromFHList b
389−
390−-- | Convert a datastructure whose constituent parts are all 'Dynamic's into a
391−-- single 'Dynamic' whose value represents all the current values of the input's
392−-- consitutent 'Dynamic's.
393−collectDynPure :: ( RebuildSortedHList (HListElems b)
394− , IsHList a, IsHList b
395− , AllAreFunctors (Dynamic t) (HListElems b)
396− , Reflex t
397− , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
398− ) => a -> Dynamic t b
399−collectDynPure ds = fmap fromHList $ distributeFHListOverDynPure $ toFHList $ toHList ds
400−
401−-- Poor man's Generic
402−class IsHList a where
403− type HListElems a :: [*]
404− toHList :: a -> HList (HListElems a)
405− fromHList :: HList (HListElems a) -> a
406−
407−instance IsHList (a, b) where
408− type HListElems (a, b) = [a, b]
409− toHList (a, b) = hBuild a b
410− fromHList l = case l of
411− a `HCons` b `HCons` HNil -> (a, b)
412−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
413− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
414−#endif
415−
416−instance IsHList (a, b, c, d) where
417− type HListElems (a, b, c, d) = [a, b, c, d]
418− toHList (a, b, c, d) = hBuild a b c d
419− fromHList l = case l of
420− a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d)
421−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
422− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
423−#endif
424−
425−instance IsHList (a, b, c, d, e, f) where
426− type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]
427− toHList (a, b, c, d, e, f) = hBuild a b c d e f
428− fromHList l = case l of
429− a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f)
430−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
431− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
432−#endif
433−
434−--------------------------------------------------------------------------------
435−-- Deprecated functions
436−--------------------------------------------------------------------------------
437−
438−-- | Map a function over a 'Dynamic'.
439−{-# DEPRECATED mapDyn "Use 'return . fmap f' instead of 'mapDyn f'; consider eliminating monadic style" #-}
440−mapDyn :: (Reflex t, Monad m) => (a -> b) -> Dynamic t a -> m (Dynamic t b)
441−mapDyn f = return . fmap f
442−
443−-- | Map a sampling function over a 'Dynamic'. The sampling function will use the input 'Dynamic''s 'current' 'Behavior' until the first time its 'updated' 'Event' fires, at which point it will be invoked only once each time the 'Event' fires.
444−{-# DEPRECATED mapDynM "Consider using the Monad instance for Dynamic instead." #-}
445−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)
446−mapDynM f d = do
447− let e' = push (fmap Just . f :: a -> PushM t (Maybe b)) $ updated d
448− eb' = fmap constant e'
449− v0 = pull $ f =<< sample (current d)
450− bb' :: Behavior t (Behavior t b) <- hold v0 eb'
451− let b' = pull $ sample =<< sample bb'
452− return $ unsafeDynamic b' e'
453−
454−-- | Flipped version of 'mapDyn'.
455−{-# DEPRECATED forDyn "Use 'return . ffor a' instead of 'forDyn a'; consider eliminating monadic style" #-}
456−forDyn :: (Reflex t, Monad m) => Dynamic t a -> (a -> b) -> m (Dynamic t b)
457−forDyn a = return . ffor a
458−
459−-- | Flipped version of 'mapDynM'
460−{-# DEPRECATED forDynM "Consider using the Monad instance for Dynamic instead." #-}
461−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)
462−forDynM d f = mapDynM f d
463−
464−-- | Split the 'Dynamic' into two 'Dynamic's, each taking the respective value
465−-- of the tuple.
466−{-# DEPRECATED splitDyn "Use 'return . splitDynPure' instead; consider eliminating monadic style" #-}
467−splitDyn :: (Reflex t, Monad m) => Dynamic t (a, b) -> m (Dynamic t a, Dynamic t b)
468−splitDyn = return . splitDynPure
469−
470−-- | Merge the 'Dynamic' values using their 'Monoid' instance.
471−{-# DEPRECATED mconcatDyn "Use 'return . mconcat' instead; consider eliminating monadic style" #-}
472−mconcatDyn :: forall t m a. (Reflex t, Monad m, Monoid a) => [Dynamic t a] -> m (Dynamic t a)
473−mconcatDyn = return . mconcat
474−
475−-- | This function no longer needs to be monadic; see 'distributeMapOverDynPure'.
476−{-# DEPRECATED distributeDMapOverDyn "Use 'return . distributeDMapOverDynPure' instead; consider eliminating monadic style" #-}
477−distributeDMapOverDyn :: (Reflex t, Monad m, GCompare k) => DMap k (Dynamic t) -> m (Dynamic t (DMap k Identity))
478−distributeDMapOverDyn = return . distributeDMapOverDynPure
479−
480−-- | Merge two 'Dynamic's into a new one using the provided function. The new
481−-- 'Dynamic' changes its value each time one of the original 'Dynamic's changes
482−-- its value.
483−{-# DEPRECATED combineDyn "Use 'return (zipDynWith f a b)' instead of 'combineDyn f a b'; consider eliminating monadic style" #-}
484−combineDyn :: forall t m a b c. (Reflex t, Monad m) => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> m (Dynamic t c)
485−combineDyn f a b = return $ zipDynWith f a b
486−
487−-- | A psuedo applicative version of ap for 'Dynamic'. Example useage:
488−--
489−-- > do
490−-- > person <- Person `mapDyn` dynFirstName
491−-- > `apDyn` dynListName
492−-- > `apDyn` dynAge
493−-- > `apDyn` dynAddress
494−{-# DEPRECATED apDyn "Use 'ffor m (<*> a)' instead of 'apDyn m a'; consider eliminating monadic style, since Dynamics are now Applicative and can be used with applicative style directly" #-}
495−{-# ANN apDyn "HLint: ignore Use fmap" #-}
496−apDyn :: forall t m a b. (Reflex t, Monad m)
497− => m (Dynamic t (a -> b))
498− -> Dynamic t a
499− -> m (Dynamic t b)
500−apDyn m a = liftM (<*> a) m
501−
502−--TODO: The pattern of using hold (sample b0) can be reused in various places as a safe way of building certain kinds of Dynamics; see if we can factor this out
503−-- | This function no longer needs to be monadic, so it has been replaced by
504−-- 'demuxed', which is pure.
505−{-# DEPRECATED getDemuxed "Use 'return . demuxed d' instead of 'getDemuxed d'; consider eliminating monadic style" #-}
506−getDemuxed :: (Reflex t, Monad m, Eq k) => Demux t k -> k -> m (Dynamic t Bool)
507−getDemuxed d = return . demuxed d
508−
509−-- | This function no longer needs to be monadic, so it has been replaced by
510−-- 'distributeFHListOverDynPure', which is pure.
511−{-# DEPRECATED distributeFHListOverDyn "Use 'return . distributeFHListOverDynPure' instead; consider eliminating monadic style" #-}
512−distributeFHListOverDyn :: forall t m l. (Reflex t, Monad m, RebuildSortedHList l) => FHList (Dynamic t) l -> m (Dynamic t (HList l))
513−distributeFHListOverDyn = return . distributeFHListOverDynPure
514−
515−-- | This function no longer needs to be monadic, so it has been replaced by
516−-- 'collectDynPure', which is pure.
517−{-# DEPRECATED collectDyn "Use 'return . collectDynPure' instead; consider eliminating monadic style" #-}
518−collectDyn :: ( RebuildSortedHList (HListElems b)
519− , IsHList a, IsHList b
520− , AllAreFunctors (Dynamic t) (HListElems b)
521− , Reflex t, Monad m
522− , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
523− ) => a -> m (Dynamic t b)
524−collectDyn = return . collectDynPure
525−
526−-- | This function has been renamed to 'tagPromptlyDyn' to clarify its
527−-- semantics.
528−{-# DEPRECATED tagDyn "Use 'tagPromptlyDyn' instead" #-}
529−tagDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
530−tagDyn = tagPromptlyDyn
531−
532−-- | This function has been renamed to 'attachPromptlyDyn' to clarify its
533−-- semantics.
534−{-# DEPRECATED attachDyn "Use 'attachPromptlyDyn' instead" #-}
535−attachDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
536−attachDyn = attachPromptlyDyn
537−
538−-- | This function has been renamed to 'attachPromptlyDynWith' to clarify its
539−-- semantics.
540−{-# DEPRECATED attachDynWith "Use 'attachPromptlyDynWith' instead" #-}
541−attachDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
542−attachDynWith = attachPromptlyDynWith
543−
544−-- | This function has been renamed to 'attachPromptlyDynWithMaybe' to clarify
545−-- its semantics.
546−{-# DEPRECATED attachDynWithMaybe "Use 'attachPromptlyDynWithMaybe' instead" #-}
547−attachDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
548−attachDynWithMaybe = attachPromptlyDynWithMaybe
549−
550−-- | Combine an inner and outer 'Dynamic' such that the resulting 'Dynamic''s
551−-- current value will always be equal to the current value's current value, and
552−-- will change whenever either the inner or the outer (or both) values change.
553−{-# DEPRECATED joinDyn "Use 'join' instead" #-}
554−joinDyn :: Reflex t => Dynamic t (Dynamic t a) -> Dynamic t a
555−joinDyn = join
556−
557−-- | 'nubDyn''s behavior is not quite analogous to 'nub''s behavior, so it has
558−-- been renamed to 'uniqDyn'
559−{-# DEPRECATED nubDyn "Use 'uniqDyn' instead" #-}
560−nubDyn :: (Reflex t, Eq a) => Dynamic t a -> Dynamic t a
561−nubDyn = uniqDyn
src/Reflex/Dynamic/TH.hsdeleted−88
@@ -1,88 +0,0 @@
1−{-# LANGUAGE EmptyDataDecls #-}
2−{-# LANGUAGE GADTs #-}
3−{-# LANGUAGE PatternGuards #-}
4−{-# LANGUAGE ScopedTypeVariables #-}
5−{-# LANGUAGE TemplateHaskell #-}
6−{-# LANGUAGE TypeOperators #-}
7−-- | Template Haskell helper functions for building complex 'Dynamic' values.
8−module Reflex.Dynamic.TH (qDyn, unqDyn, mkDyn) where
9−
10−import Reflex.Dynamic
11−
12−import Control.Monad.State
13−import Data.Data
14−import Data.Generics
15−import Data.Monoid
16−import qualified Language.Haskell.Exts as Hs
17−import qualified Language.Haskell.Meta.Syntax.Translate as Hs
18−import Language.Haskell.TH
19−import Language.Haskell.TH.Quote
20−import qualified Language.Haskell.TH.Syntax as TH
21−
22−-- | Quote a 'Dynamic' expression. Within the quoted expression, you can use
23−-- @$(unqDyn [| x |])@ to refer to any expression @x@ of type @Dynamic t a@; the
24−-- unquoted result will be of type @a@
25−qDyn :: Q Exp -> Q Exp
26−qDyn qe = do
27− e <- qe
28− let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d
29− f d = case eqT of
30− Just (Refl :: d :~: Exp)
31− | AppE (VarE m) eInner <- d
32− , m == 'unqMarker
33− -> do n <- lift $ newName "dynamicQuotedExpressionVariable"
34− modify ((n, eInner):)
35− return $ VarE n
36− _ -> gmapM f d
37− (e', exprsReversed) <- runStateT (gmapM f e) []
38− let exprs = reverse exprsReversed
39− arg = foldr (\a b -> ConE 'FHCons `AppE` a `AppE` b) (ConE 'FHNil) $ map snd exprs
40− param = foldr (\a b -> ConP 'HCons [VarP a, b]) (ConP 'HNil []) $ map fst exprs
41− [| return $ $(return $ LamE [param] e') <$> distributeFHListOverDynPure $(return arg) |]
42−
43−-- | Antiquote a 'Dynamic' expression. This can /only/ be used inside of a
44−-- 'qDyn' quotation.
45−unqDyn :: Q Exp -> Q Exp
46−unqDyn e = [| unqMarker $e |]
47−
48−-- | This type represents an occurrence of unqDyn before it has been processed
49−-- by qDyn. If you see it in a type error, it probably means that unqDyn has
50−-- been used outside of a qDyn context.
51−data UnqDyn
52−
53−-- unqMarker must not be exported; it is used only as a way of smuggling data
54−-- from unqDyn to qDyn
55−
56−--TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery
57−unqMarker :: a -> UnqDyn
58−unqMarker = error "An unqDyn expression was used outside of a qDyn expression"
59−
60−-- | Create a 'Dynamic' value using other 'Dynamic's as inputs. The result is
61−-- sometimes more concise and readable than the equivalent 'Applicative'-based
62−-- expression. For example:
63−--
64−-- > [mkDyn| $x + $v * $t + 1/2 * $a * $t ^ 2 |]
65−--
66−-- would have a very cumbersome 'Applicative' encoding.
67−mkDyn :: QuasiQuoter
68−mkDyn = QuasiQuoter
69− { quoteExp = mkDynExp
70− , quotePat = error "mkDyn: pattern splices are not supported"
71− , quoteType = error "mkDyn: type splices are not supported"
72− , quoteDec = error "mkDyn: declaration splices are not supported"
73− }
74−
75−mkDynExp :: String -> Q Exp
76−mkDynExp s = case Hs.parseExpWithMode (Hs.defaultParseMode { Hs.extensions = [ Hs.EnableExtension Hs.TemplateHaskell ] }) s of
77− Hs.ParseFailed (Hs.SrcLoc _ l c) err -> fail $ "mkDyn:" <> show l <> ":" <> show c <> ": " <> err
78− Hs.ParseOk e -> qDyn $ return $ everywhere (id `extT` reinstateUnqDyn) $ Hs.toExp $ everywhere (id `extT` antiE) e
79− where TH.Name (TH.OccName occName) (TH.NameG _ _ (TH.ModName modName)) = 'unqMarker
80− antiE x = case x of
81− Hs.SpliceExp se ->
82− Hs.App (Hs.Var $ Hs.Qual (Hs.ModuleName modName) (Hs.Ident occName)) $ case se of
83− Hs.IdSplice v -> Hs.Var $ Hs.UnQual $ Hs.Ident v
84− Hs.ParenSplice ps -> ps
85− _ -> x
86− reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName')))
87− | modName == modName' && occName == occName' = 'unqMarker
88− reinstateUnqDyn x = x
src/Reflex/Dynamic/Uniq.hsdeleted−101
@@ -1,101 +0,0 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE MagicHash #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−-- | This module provides a variation of 'Dynamic' values that uses cheap
5−-- pointer equality checks to reduce the amount of signal propagation needed.
6−module Reflex.Dynamic.Uniq
7− ( UniqDynamic
8− , uniqDynamic
9− , fromUniqDynamic
10− , alreadyUniqDynamic
11− ) where
12−
13−import Control.Applicative (Applicative (..))
14−import GHC.Exts
15−import Reflex.Class
16−import Reflex.Dynamic
17−
18−-- | A 'Dynamic' whose 'updated' 'Event' will never fire with the same value as
19−-- the 'current' 'Behavior''s contents. In order to maintain this constraint,
20−-- the value inside a 'UniqDynamic' is always evaluated to
21−-- <https://wiki.haskell.org/Weak_head_normal_form weak head normal form>.
22−--
23−-- Internally, 'UniqDynamic' uses pointer equality as a heuristic to avoid
24−-- unnecessary update propagation; this is much more efficient than performing
25−-- full comparisons. However, when the 'UniqDynamic' is converted back into a
26−-- regular 'Dynamic', a full comparison is performed.
27−newtype UniqDynamic t a = UniqDynamic { unUniqDynamic :: Dynamic t a }
28−
29−-- | Construct a 'UniqDynamic' by eliminating redundant updates from a 'Dynamic'.
30−uniqDynamic :: Reflex t => Dynamic t a -> UniqDynamic t a
31−uniqDynamic d = UniqDynamic $ unsafeBuildDynamic (sample $ current d) $ flip push (updated d) $ \new -> do --TODO: It would be very nice if we had an uncached push here
32− old <- sample $ current d --TODO: Is it better to sample ourselves here?
33− return $ unsafeJustChanged old new
34−
35−-- | Retrieve a normal 'Dynamic' from a 'UniqDynamic'. This will perform a
36−-- final check using the output type's 'Eq' instance to ensure deterministic
37−-- behavior.
38−--
39−-- WARNING: If used with a type whose 'Eq' instance is not law-abiding -
40−-- specifically, if there are cases where @x /= x@, 'fromUniqDynamic' may
41−-- eliminate more 'updated' occurrences than it should. For example, NaN values
42−-- of 'Double' and 'Float' are considered unequal to themselves by the 'Eq'
43−-- instance, but can be equal by pointer equality. This may cause 'UniqDynamic'
44−-- to lose changes from NaN to NaN.
45−fromUniqDynamic :: (Reflex t, Eq a) => UniqDynamic t a -> Dynamic t a
46−fromUniqDynamic (UniqDynamic d) = uniqDynBy superEq d
47− where
48− -- Only consider values different if they fail both pointer equality /and/
49− -- 'Eq' equality. This is to make things a bit more deterministic in the
50− -- case of unlawful 'Eq' instances. However, it is still possible to
51− -- achieve nondeterminism by constructing elements that are identical in
52− -- value, unequal according to 'Eq', and nondeterministically equal or
53− -- nonequal by pointer quality. I suspect that it is impossible to make the
54− -- behavior deterministic in this case.
55− superEq a b = a `unsafePtrEq` b || a == b
56−
57−-- | Create a UniqDynamic without uniqing it on creation. This will be slightly
58−-- faster than uniqDynamic when used with a Dynamic whose values are always (or
59−-- nearly always) different from its previous values; if used with a Dynamic
60−-- whose values do not change frequently, it may be much slower than uniqDynamic
61−alreadyUniqDynamic :: Dynamic t a -> UniqDynamic t a
62−alreadyUniqDynamic = UniqDynamic
63−
64−unsafePtrEq :: a -> a -> Bool
65−unsafePtrEq a b = case a `seq` b `seq` reallyUnsafePtrEquality# a b of
66− 0# -> False
67− _ -> True
68−
69−unsafeJustChanged :: a -> a -> Maybe a
70−unsafeJustChanged old new =
71− if old `unsafePtrEq` new
72− then Nothing
73− else Just new
74−
75−instance Reflex t => Accumulator t (UniqDynamic t) where
76− accumMaybeM f z e = do
77− let f' old change = do
78− mNew <- f old change
79− return $ unsafeJustChanged old =<< mNew
80− d <- accumMaybeM f' z e
81− return $ UniqDynamic d
82− mapAccumMaybeM f z e = do
83− let f' old change = do
84− (mNew, output) <- f old change
85− return (unsafeJustChanged old =<< mNew, output)
86− (d, out) <- mapAccumMaybeM f' z e
87− return (UniqDynamic d, out)
88−
89−instance Reflex t => Functor (UniqDynamic t) where
90− fmap f (UniqDynamic d) = uniqDynamic $ fmap f d
91−
92−instance Reflex t => Applicative (UniqDynamic t) where
93− pure = UniqDynamic . constDyn
94− UniqDynamic a <*> UniqDynamic b = uniqDynamic $ a <*> b
95− _ *> b = b
96− a <* _ = a
97−
98−instance Reflex t => Monad (UniqDynamic t) where
99− UniqDynamic x >>= f = uniqDynamic $ x >>= unUniqDynamic . f
100− _ >> b = b
101− return = pure
src/Reflex/DynamicWriter.hsdeleted−194
@@ -1,194 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RecursiveDo #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−module Reflex.DynamicWriter where
13−
14−import Control.Monad.Exception
15−import Control.Monad.Identity
16−import Control.Monad.IO.Class
17−import Control.Monad.Reader
18−import Control.Monad.Ref
19−import Control.Monad.State.Strict
20−import Data.Dependent.Map (DMap, DSum (..))
21−import Data.Functor.Misc
22−import Data.Map (Map)
23−import qualified Data.Map as Map
24−import Data.Semigroup
25−import Data.Some (Some)
26−import qualified Data.Some as Some
27−import Reflex.Class
28−import Reflex.Dynamic
29−import Reflex.PerformEvent.Class
30−import Reflex.PostBuild.Class
31−import Reflex.Host.Class
32−
33−instance MonadTrans (DynamicWriterT t w) where
34− lift = DynamicWriterT . lift
35−
36−mconcatIncremental :: (Reflex t, MonadHold t m, MonadFix m, Monoid v, Ord k) => Map k v -> Event t (PatchMap k v) -> m (Dynamic t v)
37−mconcatIncremental m0 e = do
38− d <- foldDynMaybe apply m0 e
39− return $ fmap (mconcat . Map.elems) d
40−
41−mapIncrementalMapValuesWithKey :: (Reflex t, Ord k) => (k -> v -> v') -> Incremental t (PatchMap k v) -> Incremental t (PatchMap k v')
42−mapIncrementalMapValuesWithKey f = unsafeMapIncremental (Map.mapWithKey f) $ \(PatchMap m) -> PatchMap $ Map.mapWithKey (\k mv -> fmap (f k) mv) m
43−
44−mapIncrementalMapValues :: (Reflex t, Ord k) => (v -> v') -> Incremental t (PatchMap k v) -> Incremental t (PatchMap k v')
45−mapIncrementalMapValues f = mapIncrementalMapValuesWithKey $ const f
46−
47−unsafeMapIncremental :: (Reflex t, Patch p, Patch p') => (PatchTarget p -> PatchTarget p') -> (p -> p') -> Incremental t p -> Incremental t p'
48−unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
49−
50−incrementalExtractFunctorDMap :: (Reflex t, Ord k) => Incremental t (PatchMap k (f v)) -> Incremental t (PatchDMap (Const2 k v) f)
51−incrementalExtractFunctorDMap = unsafeMapIncremental mapWithFunctorToDMap $ \(PatchMap m) -> PatchDMap $ mapWithFunctorToDMap $ fmap ComposeMaybe m
52−
53−mergeIncrementalMap :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t v)) -> Event t (Map k v)
54−mergeIncrementalMap = fmap dmapToMap . mergeIncremental . incrementalExtractFunctorDMap
55−
56−holdIncrementalReplaceableMap :: forall t k v m. (MonadFix m, MonadHold t m, Reflex t, Ord k) => Map k (Replaceable t v) -> Event t (PatchMap k (Replaceable t v)) -> m (Incremental t (PatchMap k v))
57−holdIncrementalReplaceableMap m0 m' = do
58− rec vals <- holdIncremental m0 $ m' <> valChanges
59− let valChanges = fmap PatchMap $ mergeIncrementalMap $ mapIncrementalMapValues _replaceable_modify vals
60− return $ mapIncrementalMapValues _replaceable_value vals
61−
62−mergeDynIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Dynamic t v)) -> Incremental t (PatchMap k v)
63−mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
64− where changedValues = fmap (PatchMap . fmap Just) $ mergeIncrementalMap $ mapIncrementalMapValues updated a
65− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m
66−
67−data Replaceable t w = Replaceable
68− { _replaceable_value :: w
69− , _replaceable_modify :: Event t (Maybe (Replaceable t w)) -- "Please delete" is represented with an event of Nothing; all subsequent events will be ignored
70− }
71−
72−type DynamicWriterAccumulator t w = [Dynamic t w]
73−
74−newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT (DynamicWriterAccumulator t w) m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadHold t, MonadSample t, MonadAsyncException, MonadException) -- The list is kept in reverse order
75−
76−instance MonadRef m => MonadRef (DynamicWriterT t w m) where
77− type Ref (DynamicWriterT t w m) = Ref m
78− newRef = lift . newRef
79− readRef = lift . readRef
80− writeRef r = lift . writeRef r
81−
82−instance MonadAtomicRef m => MonadAtomicRef (DynamicWriterT t w m) where
83− atomicModifyRef r = lift . atomicModifyRef r
84−
85−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DynamicWriterT t w m) where
86− newEventWithTrigger = lift . newEventWithTrigger
87− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
88−
89−runDynamicWriterTInternal :: DynamicWriterT t w m a -> m (a, DynamicWriterAccumulator t w)
90−runDynamicWriterTInternal (DynamicWriterT a) = runStateT a []
91−
92−mconcatIncrementalReplaceableDynMap :: forall m t k v.
93− (MonadFix m, MonadHold t m, Reflex t, Monoid v, Ord k)
94− => Map k (Replaceable t (Dynamic t v))
95− -> Event t (PatchMap k (Replaceable t (Dynamic t v)))
96− -> Event t ()
97− -> m (Replaceable t (Dynamic t v))
98−mconcatIncrementalReplaceableDynMap m0 m' additionsCeased = do
99− rec vals <- holdIncremental m0 $ m' <> valChanges
100− let valChanges = fmap PatchMap $ mergeIncrementalMap $ mapIncrementalMapValues _replaceable_modify vals
101− let i = mapIncrementalMapValues _replaceable_value vals
102− noMoreAdditions <- holdDyn False $ True <$ additionsCeased
103− let replaceSelf nma x = do
104− guard nma
105− case Map.toList x of
106− [] -> return Nothing -- Delete self
107− [(_, n)] -> return $ Just n --TODO: What if this one is also replacing itself simultaneously?
108− _ -> mzero
109− result = fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeDynIncremental i
110− return $ Replaceable result $ fmapMaybe id $ updated $ zipDynWith replaceSelf noMoreAdditions $ incrementalToDynamic vals
111−
112−runDynamicWriterT :: (MonadFix m, Reflex t, Monoid w) => DynamicWriterT t w m a -> m (a, Dynamic t w)
113−runDynamicWriterT (DynamicWriterT a) = do
114− (result, ws) <- runStateT a []
115− return (result, mconcat $ reverse ws)
116−
117−class Monad m => MonadDynamicWriter t w m | m -> t w where
118− tellDyn :: Dynamic t w -> m ()
119−
120−instance (Monad m, Reflex t) => MonadDynamicWriter t w (DynamicWriterT t w m) where
121− tellDyn w = DynamicWriterT $ modify (w :)
122−
123−instance MonadReader r m => MonadReader r (DynamicWriterT t w m) where
124− ask = lift ask
125− local f (DynamicWriterT a) = DynamicWriterT $ mapStateT (local f) a
126− reader = lift . reader
127−
128−liftDynamicWriterTThroughSync :: Monad m' => (m (a, DynamicWriterAccumulator t w) -> m' (b, (a, DynamicWriterAccumulator t w))) -> DynamicWriterT t w m a -> DynamicWriterT t w m' (b, a)
129−liftDynamicWriterTThroughSync f (DynamicWriterT child) = DynamicWriterT $ do
130− s <- get
131− (b, (a, newS)) <- lift $ f $ runStateT child s
132− put newS
133− return (b, a)
134−
135−instance PerformEvent t m => PerformEvent t (DynamicWriterT t w m) where
136− type Performable (DynamicWriterT t w m) = Performable m
137− performEvent_ = lift . performEvent_
138− performEvent = lift . performEvent
139−
140−instance TriggerEvent t m => TriggerEvent t (DynamicWriterT t w m) where
141− newTriggerEvent = lift newTriggerEvent
142− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
143− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
144−
145−instance PostBuild t m => PostBuild t (DynamicWriterT t w m) where
146− getPostBuild = lift getPostBuild
147−
148−instance MonadDynamicWriter t w m => MonadDynamicWriter t w (ReaderT r m) where
149− tellDyn = lift . tellDyn
150−
151−instance MonadState s m => MonadState s (DynamicWriterT t w m) where
152− get = lift get
153− put = lift . put
154−
155−newtype DynamicWriterTLoweredResult t w v = DynamicWriterTLoweredResult { unDynamicWriterTLoweredResult :: (v, Dynamic t w) }
156−
157−instance (MonadAdjust t m, MonadFix m, Monoid w, MonadHold t m, Reflex t) => MonadAdjust t (DynamicWriterT t w m) where
158− sequenceDMapWithAdjust (dm0 :: DMap k (DynamicWriterT t w m)) dm' = do
159− let loweredDm0 = mapKeyValuePairsMonotonic (\(k :=> v) -> WrapArg k :=> fmap DynamicWriterTLoweredResult (runDynamicWriterT v)) dm0
160− let loweredDm' = ffor dm' $ \(PatchDMap p) -> PatchDMap $
161− mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mv) -> WrapArg k :=> ComposeMaybe (fmap (fmap DynamicWriterTLoweredResult . runDynamicWriterT) mv)) p
162− (result0, result') <- lift $ sequenceDMapWithAdjust loweredDm0 loweredDm'
163− let getValue (DynamicWriterTLoweredResult (v, _)) = v
164− getWritten (DynamicWriterTLoweredResult (_, w)) = w
165− liftedResult0 = mapKeyValuePairsMonotonic (\(WrapArg k :=> Identity r) -> k :=> Identity (getValue r)) result0
166− liftedResult' = ffor result' $ \(PatchDMap p) -> PatchDMap $
167− mapKeyValuePairsMonotonic (\(WrapArg k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (Identity . getValue . runIdentity) mr)) p
168− liftedWritten0 :: DMap (Const2 (Some k) (Dynamic t w)) Identity
169− liftedWritten0 = mapKeyValuePairsMonotonic (\(WrapArg k :=> Identity r) -> Const2 (Some.This k) :=> Identity (getWritten r)) result0
170− liftedWritten' = ffor result' $ \(PatchDMap p) -> PatchDMap $
171− mapKeyValuePairsMonotonic (\(WrapArg k :=> ComposeMaybe mr) -> Const2 (Some.This k) :=> ComposeMaybe (fmap (Identity . getWritten . runIdentity) mr)) p
172− --TODO: We should be able to improve the performance here in two ways
173− -- 1. Incrementally merging the Dynamics
174− -- 2. Incrementally updating the mconcat of the merged Dynamics
175− i <- holdIncremental liftedWritten0 liftedWritten'
176− tellDyn $ join $ mconcat . Map.elems . dmapToMap <$> incrementalToDynamic i
177− return (liftedResult0, liftedResult')
178−
179−withDynamicWriterT :: (Monoid w, Reflex t, MonadHold t m, MonadFix m)
180− => (w -> w')
181− -> DynamicWriterT t w m a
182− -> DynamicWriterT t w' m a
183−withDynamicWriterT f dw = do
184− (r, d) <- lift $ do
185− (r, d) <- runDynamicWriterT dw
186− let d' = fmap f d
187− return (r, d')
188− tellDyn d
189− return r
190−
191−instance MonadRequest t m => MonadRequest t (DynamicWriterT t w m) where
192− type Request (DynamicWriterT t w m) = Request m
193− type Response (DynamicWriterT t w m) = Response m
194− withRequesting f = DynamicWriterT $ withRequesting $ unDynamicWriterT . f
src/Reflex/Host/Class.hsdeleted−282
@@ -1,282 +0,0 @@
1−{-# LANGUAGE ExistentialQuantification #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE RoleAnnotations #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−-- | This module provides the interface for hosting 'Reflex' engines. This
13−-- should only be necessary if you're writing a binding or some other library
14−-- that provides a core event loop.
15−module Reflex.Host.Class
16− ( ReflexHost (..)
17− , MonadSubscribeEvent (..)
18− , MonadReadEvent (..)
19− , MonadReflexCreateTrigger (..)
20− , MonadReflexHost (..)
21− , fireEvents
22− , newEventWithTriggerRef
23− , fireEventRef
24− , fireEventRefAndRead
25− ) where
26−
27−import Reflex.Class
28−
29−import Control.Applicative
30−import Control.Monad
31−import Control.Monad.Fix
32−import Control.Monad.Identity
33−import Control.Monad.Ref
34−import Control.Monad.Trans
35−import Control.Monad.Trans.Cont (ContT ())
36−import Control.Monad.Trans.Except (ExceptT ())
37−import Control.Monad.Trans.Reader (ReaderT ())
38−import Control.Monad.Trans.RWS (RWST ())
39−import Control.Monad.Trans.State (StateT ())
40−import qualified Control.Monad.Trans.State.Strict as Strict
41−import Control.Monad.Trans.Writer (WriterT ())
42−import Data.Dependent.Sum (DSum (..))
43−import Data.GADT.Compare
44−import Data.Monoid
45−
46−-- Note: this import must come last to silence warnings from AMP
47−import Prelude hiding (foldl, mapM, mapM_, sequence, sequence_)
48−
49−-- | Framework implementation support class for the reflex implementation
50−-- represented by @t@.
51−class ( Reflex t
52− , MonadReflexCreateTrigger t (HostFrame t)
53− , MonadSample t (HostFrame t)
54− , MonadHold t (HostFrame t)
55− , MonadFix (HostFrame t)
56− , MonadSubscribeEvent t (HostFrame t)
57− ) => ReflexHost t where
58− type EventTrigger t :: * -> *
59− type EventHandle t :: * -> *
60− type HostFrame t :: * -> *
61−
62−-- | Monad in which Events can be 'subscribed'. This forces all underlying
63−-- event sources to be initialized, so that the event will fire whenever it
64−-- ought to. Events must be subscribed before they are read using readEvent
65−class (Reflex t, Monad m) => MonadSubscribeEvent t m | m -> t where
66− -- | Subscribe to an event and set it up if needed.
67− --
68− -- This function will create a new 'EventHandle' from an 'Event'. This handle
69− -- may then be used via 'readEvent' in the read callback of
70− -- 'fireEventsAndRead'.
71− --
72− -- If the event wasn't subscribed to before (either manually or through a
73− -- dependent event or behavior) then this function will cause the event and
74− -- all dependencies of this event to be set up. For example, if the event was
75− -- created by 'newEventWithTrigger', then it's callback will be executed.
76− --
77− -- It's safe to call this function multiple times.
78− subscribeEvent :: Event t a -> m (EventHandle t a)
79−
80−-- | Monad that allows to read events' values.
81−class (ReflexHost t, Applicative m, Monad m) => MonadReadEvent t m | m -> t where
82− -- | Read the value of an 'Event' from an 'EventHandle' (created by calling
83− -- 'subscribeEvent').
84− --
85− -- After event propagation is done, all events can be in two states: either
86− -- they are firing with some value or they are not firing. In the former
87− -- case, this function returns @Just act@, where @act@ in an action to read
88− -- the current value of the event. In the latter case, the function returns
89− -- @Nothing@.
90− --
91− -- This function is normally used in the calllback for 'fireEventsAndRead'.
92− readEvent :: EventHandle t a -> m (Maybe (m a))
93−
94−-- | A monad where new events feed from external sources can be created.
95−class (Applicative m, Monad m) => MonadReflexCreateTrigger t m | m -> t where
96− -- | Creates a root 'Event' (one that is not based on any other event).
97− --
98− -- When a subscriber first subscribes to an event (building another event that
99− -- depends on the subscription) the given callback function is run and passed
100− -- a trigger. The callback function can then set up the event source in IO.
101− -- After this is done, the callback function must return an accompanying
102− -- teardown action.
103− --
104− -- Any time between setup and teardown the trigger can be used to fire the
105− -- event, by passing it to 'fireEventsAndRead'.
106− --
107− -- Note: An event may be set up multiple times. So after the teardown action
108− -- is executed, the event may still be set up again in the future.
109− newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)
110− newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k)
111−
112−-- | 'MonadReflexHost' designates monads that can run reflex frames.
113−class ( ReflexHost t
114− , MonadReflexCreateTrigger t m
115− , MonadSubscribeEvent t m
116− , MonadReadEvent t (ReadPhase m)
117− , MonadSample t (ReadPhase m)
118− , MonadHold t (ReadPhase m)
119− ) => MonadReflexHost t m | m -> t where
120− type ReadPhase m :: * -> *
121− -- | Propagate some events firings and read the values of events afterwards.
122− --
123− -- This function will create a new frame to fire the given events. It will
124− -- then update all dependent events and behaviors. After that is done, the
125− -- given callback is executed which allows to read the final values of events
126− -- and check whether they have fired in this frame or not.
127− --
128− -- All events that are given are fired at the same time.
129− --
130− -- This function is typically used in the main loop of a reflex framework
131− -- implementation. The main loop waits for external events to happen (such as
132− -- keyboard input or a mouse click) and then fires the corresponding events
133− -- using this function. The read callback can be used to read output events
134− -- and perform a corresponding response action to the external event.
135− fireEventsAndRead :: [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m a
136−
137− -- | Run a frame without any events firing.
138− --
139− -- This function should be used when you want to use 'sample' and 'hold' when
140− -- no events are currently firing. Using this function in that case can
141− -- improve performance, since the implementation can assume that no events are
142− -- firing when 'sample' or 'hold' are called.
143− --
144− -- This function is commonly used to set up the basic event network when the
145− -- application starts up.
146− runHostFrame :: HostFrame t a -> m a
147−
148−-- | Like 'fireEventsAndRead', but without reading any events.
149−fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t) Identity] -> m ()
150−fireEvents dm = fireEventsAndRead dm $ return ()
151−{-# INLINE fireEvents #-}
152−
153−-- | Create a new event and store its trigger in an 'IORef' while it's active.
154−--
155−-- An event is only active between the set up (when it's first subscribed to)
156−-- and the teardown phases (when noboby is subscribing the event anymore). This
157−-- function returns an Event and an 'IORef'. As long as the event is active, the
158−-- 'IORef' will contain 'Just' the event trigger to trigger this event. When the
159−-- event is not active, the 'IORef' will contain 'Nothing'. This allows event
160−-- sources to be more efficient, since they don't need to produce events when
161−-- nobody is listening.
162−newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
163−newEventWithTriggerRef = do
164− rt <- newRef Nothing
165− e <- newEventWithTrigger $ \t -> do
166− writeRef rt $ Just t
167− return $ writeRef rt Nothing
168− return (e, rt)
169−{-# INLINE newEventWithTriggerRef #-}
170−
171−-- | Fire the given trigger if it is not 'Nothing'.
172−fireEventRef :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> m ()
173−fireEventRef mtRef input = do
174− mt <- readRef mtRef
175− case mt of
176− Nothing -> return ()
177− Just trigger -> fireEvents [trigger :=> Identity input]
178−
179−-- | Fire the given trigger if it is not 'Nothing', and read from the given
180−-- 'EventHandle'.
181−fireEventRefAndRead :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> EventHandle t b -> m (Maybe b)
182−fireEventRefAndRead mtRef input e = do
183− mt <- readRef mtRef
184− case mt of
185− Nothing -> return Nothing -- Since we aren't firing the input, the output can't fire
186− Just trigger -> fireEventsAndRead [trigger :=> Identity input] $ do
187− mGetValue <- readEvent e
188− case mGetValue of
189− Nothing -> return Nothing
190− Just getValue -> fmap Just getValue
191−
192−
193−--------------------------------------------------------------------------------
194−-- Instances
195−--------------------------------------------------------------------------------
196−
197−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ReaderT r m) where
198− newEventWithTrigger = lift . newEventWithTrigger
199− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
200−
201−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ReaderT r m) where
202− subscribeEvent = lift . subscribeEvent
203−
204−instance MonadReflexHost t m => MonadReflexHost t (ReaderT r m) where
205− type ReadPhase (ReaderT r m) = ReadPhase m
206− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
207− runHostFrame = lift . runHostFrame
208−
209−instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (WriterT w m) where
210− newEventWithTrigger = lift . newEventWithTrigger
211− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
212−
213−instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (WriterT w m) where
214− subscribeEvent = lift . subscribeEvent
215−
216−instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (WriterT w m) where
217− type ReadPhase (WriterT w m) = ReadPhase m
218− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
219− runHostFrame = lift . runHostFrame
220−
221−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StateT s m) where
222− newEventWithTrigger = lift . newEventWithTrigger
223− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
224−
225−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (StateT r m) where
226− subscribeEvent = lift . subscribeEvent
227−
228−instance MonadReflexHost t m => MonadReflexHost t (StateT s m) where
229− type ReadPhase (StateT s m) = ReadPhase m
230− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
231− runHostFrame = lift . runHostFrame
232−
233−
234−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where
235− newEventWithTrigger = lift . newEventWithTrigger
236− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
237−
238−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (Strict.StateT r m) where
239− subscribeEvent = lift . subscribeEvent
240−
241−instance MonadReflexHost t m => MonadReflexHost t (Strict.StateT s m) where
242− type ReadPhase (Strict.StateT s m) = ReadPhase m
243− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
244− runHostFrame = lift . runHostFrame
245−
246−
247−
248−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where
249− newEventWithTrigger = lift . newEventWithTrigger
250− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
251−
252−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ContT r m) where
253− subscribeEvent = lift . subscribeEvent
254−
255−instance MonadReflexHost t m => MonadReflexHost t (ContT r m) where
256− type ReadPhase (ContT r m) = ReadPhase m
257− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
258− runHostFrame = lift . runHostFrame
259−
260−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ExceptT e m) where
261− newEventWithTrigger = lift . newEventWithTrigger
262− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
263−
264−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ExceptT r m) where
265− subscribeEvent = lift . subscribeEvent
266−
267−instance MonadReflexHost t m => MonadReflexHost t (ExceptT e m) where
268− type ReadPhase (ExceptT e m) = ReadPhase m
269− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
270− runHostFrame = lift . runHostFrame
271−
272−instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (RWST r w s m) where
273− newEventWithTrigger = lift . newEventWithTrigger
274− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
275−
276−instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (RWST r w s m) where
277− subscribeEvent = lift . subscribeEvent
278−
279−instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (RWST r w s m) where
280− type ReadPhase (RWST r w s m) = ReadPhase m
281− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
282− runHostFrame = lift . runHostFrame
src/Reflex/PerformEvent/Base.hsdeleted−286
@@ -1,286 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE PartialTypeSignatures #-}
7−{-# LANGUAGE PolyKinds #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RecursiveDo #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE StandaloneDeriving #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−module Reflex.PerformEvent.Base where
16−
17−import Reflex.Class
18−import Reflex.Host.Class
19−import Reflex.PostBuild.Class
20−import Reflex.PerformEvent.Class
21−
22−import Control.Lens
23−import Control.Monad.Exception
24−import Control.Monad.Identity
25−import Control.Monad.Primitive
26−import Control.Monad.Ref
27−import Control.Monad.State.Strict
28−import Control.Monad.Reader
29−import Data.Coerce
30−import Data.Dependent.Map (DMap, GCompare (..), Some)
31−import qualified Data.Dependent.Map as DMap
32−import Data.Dependent.Sum
33−import Data.Functor.Misc
34−import Data.Semigroup
35−import qualified Data.Some as Some
36−import Data.These
37−import Data.Tuple
38−import Data.Unique.Tag
39−
40−newtype EventTriggerRef t m a = EventTriggerRef { unEventTriggerRef :: Ref m (Maybe (EventTrigger t a)) }
41−
42−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?
43−
44−newtype PerformEventT t m a = PerformEventT { unPerformEventT :: RequestT t (HostFrame t) Identity (HostFrame t) a }
45−
46−deriving instance ReflexHost t => Functor (PerformEventT t m)
47−deriving instance ReflexHost t => Applicative (PerformEventT t m)
48−deriving instance ReflexHost t => Monad (PerformEventT t m)
49−deriving instance ReflexHost t => MonadFix (PerformEventT t m)
50−deriving instance (ReflexHost t, MonadIO (HostFrame t)) => MonadIO (PerformEventT t m)
51−deriving instance (ReflexHost t, MonadException (HostFrame t)) => MonadException (PerformEventT t m)
52−
53−instance (PrimMonad (HostFrame t), ReflexHost t) => PrimMonad (PerformEventT t m) where
54− type PrimState (PerformEventT t m) = PrimState (HostFrame t)
55− primitive = PerformEventT . lift . primitive
56−
57−instance (ReflexHost t, Ref m ~ Ref IO, PrimMonad (HostFrame t)) => PerformEvent t (PerformEventT t m) where
58− type Performable (PerformEventT t m) = HostFrame t
59− {-# INLINABLE performEvent_ #-}
60− performEvent_ = PerformEventT . requesting_
61− {-# INLINABLE performEvent #-}
62− performEvent = PerformEventT . fmap (fmap runIdentity) . requesting
63−
64−instance (ReflexHost t, PrimMonad (HostFrame t)) => MonadAdjust t (PerformEventT t m) where
65− sequenceDMapWithAdjust (outerDm0 :: DMap k (PerformEventT t m)) outerDm' = PerformEventT $ sequenceDMapWithAdjustRequestTWith f (coerce outerDm0) (coerceEvent outerDm')
66− where f :: DMap k' (HostFrame t) -> Event t (PatchDMap k' (HostFrame t)) -> RequestT t (HostFrame t) Identity (HostFrame t) (DMap k' Identity, Event t (PatchDMap k' Identity))
67− f dm0 dm' = do
68− result0 <- lift $ DMap.traverseWithKey (\_ v -> Identity <$> v) dm0
69− result' <- requesting $ ffor dm' $ \(PatchDMap p) -> do
70− PatchDMap <$> DMap.traverseWithKey (\_ (ComposeMaybe mv) -> ComposeMaybe <$> mapM (fmap Identity) mv) p
71− return (result0, fmap runIdentity result')
72−
73−instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where
74− {-# INLINABLE newEventWithTrigger #-}
75− newEventWithTrigger = PerformEventT . lift . newEventWithTrigger
76− {-# INLINABLE newFanEventWithTrigger #-}
77− newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f
78−
79−{-# INLINABLE hostPerformEventT #-}
80−hostPerformEventT :: forall t m a.
81− ( Monad m
82− , MonadSubscribeEvent t m
83− , MonadReflexHost t m
84− , MonadRef m
85− , Ref m ~ Ref IO
86− )
87− => PerformEventT t m a
88− -> m (a, FireCommand t m)
89−hostPerformEventT a = do
90− (response, responseTrigger) <- newEventWithTriggerRef
91− (result, eventToPerform) <- runHostFrame $ runRequestT (unPerformEventT a) response
92− eventToPerformHandle <- subscribeEvent eventToPerform
93− return $ (,) result $ FireCommand $ \triggers (readPhase :: ReadPhase m a') -> do
94− let go :: [DSum (EventTrigger t) Identity] -> m [a']
95− go ts = do
96− (result', mToPerform) <- fireEventsAndRead ts $ do
97− mToPerform <- sequence =<< readEvent eventToPerformHandle
98− result' <- readPhase
99− return (result', mToPerform)
100− case mToPerform of
101− Nothing -> return [result']
102− Just toPerform -> do
103− responses <- runHostFrame $ DMap.traverseWithKey (\_ v -> Identity <$> v) toPerform
104− mrt <- readRef responseTrigger
105− let followupEventTriggers = case mrt of
106− Just rt -> [rt :=> Identity responses]
107− Nothing -> []
108− (result':) <$> go followupEventTriggers
109− go triggers
110−
111−instance ReflexHost t => MonadSample t (PerformEventT t m) where
112− {-# INLINABLE sample #-}
113− sample = PerformEventT . lift . sample
114−
115−instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where
116− {-# INLINABLE hold #-}
117− hold v0 v' = PerformEventT $ lift $ hold v0 v'
118− {-# INLINABLE holdDyn #-}
119− holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'
120− {-# INLINABLE holdIncremental #-}
121− holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'
122−
123−instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where
124− type Ref (PerformEventT t m) = Ref (HostFrame t)
125− {-# INLINABLE newRef #-}
126− newRef = PerformEventT . lift . newRef
127− {-# INLINABLE readRef #-}
128− readRef = PerformEventT . lift . readRef
129− {-# INLINABLE writeRef #-}
130− writeRef r = PerformEventT . lift . writeRef r
131−
132−instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where
133− {-# INLINABLE atomicModifyRef #-}
134− atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
135−
136−--------------------------------------------------------------------------------
137−-- RequestT
138−--------------------------------------------------------------------------------
139−
140−newtype RequestT t request response m a
141− = RequestT { unRequestT :: StateT [Event t (DMap (Tag (PrimState m)) request)] (ReaderT (EventSelector t (WrapArg response (Tag (PrimState m)))) m) a }
142− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException)
143−
144−instance MonadTrans (RequestT t request response) where
145− lift = RequestT . lift . lift
146−
147−runRequestT :: forall t m a request response.
148− ( Reflex t
149− , Monad m
150− )
151− => RequestT t request response m a
152− -> Event t (DMap (Tag (PrimState m)) response)
153− -> m (a, Event t (DMap (Tag (PrimState m)) request))
154−runRequestT (RequestT a) responses = do
155− (result, requests) <- runReaderT (runStateT a mempty) $ fan $ mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e) <$> responses
156− return (result, mergeWith DMap.union requests)
157−
158−instance (Reflex t, PrimMonad m) => MonadRequest t (RequestT t request response m) where
159− type Request (RequestT t request response m) = request
160− type Response (RequestT t request response m) = response
161− withRequesting a = do
162− t <- lift newTag
163− s <- RequestT ask
164− (req, result) <- a $ select s $ WrapArg t
165− RequestT $ modify $ (:) $ DMap.singleton t <$> req
166− return result
167−
168−data DMapTransform (a :: *) k k' v v' = forall (b :: *). DMapTransform !(k a -> k' b) !(v a -> v' b)
169−
170−mapPatchKeysAndValuesMonotonic :: (forall a. DMapTransform a k k' v v') -> PatchDMap k v -> PatchDMap k' v'
171−mapPatchKeysAndValuesMonotonic x (PatchDMap p) = PatchDMap $ mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mv) -> case x of DMapTransform f g -> f k :=> ComposeMaybe (fmap g mv)) p
172−
173−mapKeysAndValuesMonotonic :: (forall a. DMapTransform a k k' v v') -> DMap k v -> DMap k' v'
174−mapKeysAndValuesMonotonic x = mapKeyValuePairsMonotonic $ \(k :=> v) -> case x of
175− DMapTransform f g -> f k :=> g v
176−
177−instance MonadSample t m => MonadSample t (RequestT t request response m) where
178− sample = lift . sample
179−
180−instance MonadHold t m => MonadHold t (RequestT t request response m) where
181− hold v0 = lift . hold v0
182− holdDyn v0 = lift . holdDyn v0
183− holdIncremental v0 = lift . holdIncremental v0
184−
185−instance (Reflex t, MonadAdjust t m, MonadHold t m) => MonadAdjust t (RequestT t request response m) where
186− sequenceDMapWithAdjust = sequenceDMapWithAdjustRequestTWith $ \dm0 dm' -> lift $ sequenceDMapWithAdjust dm0 dm'
187−
188−sequenceDMapWithAdjustRequestTWith :: (GCompare k, Monad m, Reflex t, MonadHold t m)
189− => (forall k'. GCompare k'
190− => DMap k' m
191− -> Event t (PatchDMap k' m)
192− -> RequestT t request response m (DMap k' Identity, Event t (PatchDMap k' Identity))
193− )
194− -> DMap k (RequestT t request response m)
195− -> Event t (PatchDMap k (RequestT t request response m))
196− -> RequestT t request response m (DMap k Identity, Event t (PatchDMap k Identity))
197−sequenceDMapWithAdjustRequestTWith f (dm0 :: DMap k (RequestT t request response m)) dm' = do
198− response <- RequestT ask
199− let inputTransform :: forall a. DMapTransform a k (WrapArg ((,) [Event t (DMap (Tag (PrimState m)) request)]) k) (RequestT t request response m) m
200− inputTransform = DMapTransform WrapArg (\(RequestT v) -> swap <$> runReaderT (runStateT v mempty) response)
201− (children0, children') <- f (mapKeysAndValuesMonotonic inputTransform dm0) $ mapPatchKeysAndValuesMonotonic inputTransform <$> dm'
202− let result0 = mapKeyValuePairsMonotonic (\(WrapArg k :=> Identity (_, v)) -> k :=> Identity v) children0
203− result' = ffor children' $ \(PatchDMap p) -> PatchDMap $
204− mapKeyValuePairsMonotonic (\(WrapArg k :=> ComposeMaybe mv) -> k :=> ComposeMaybe (fmap (Identity . snd . runIdentity) mv)) p
205− requests0 :: DMap (Const2 (Some k) (DMap (Tag (PrimState m)) request)) (Event t)
206− requests0 = mapKeyValuePairsMonotonic (\(WrapArg k :=> Identity (r, _)) -> Const2 (Some.This k) :=> mergeWith DMap.union r) children0
207− requests' :: Event t (PatchDMap (Const2 (Some k) (DMap (Tag (PrimState m)) request)) (Event t))
208− requests' = ffor children' $ \(PatchDMap p) -> PatchDMap $
209− mapKeyValuePairsMonotonic (\(WrapArg k :=> ComposeMaybe mv) -> Const2 (Some.This k) :=> ComposeMaybe (fmap (mergeWith DMap.union . fst . runIdentity) mv)) p
210− childRequestMap <- holdIncremental requests0 requests'
211− RequestT $ modify $ (:) $ ffor (mergeIncremental childRequestMap) $ \m ->
212− mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m
213−-- RequestT $ modify $ (:) $ coincidence $ ffor requests' $ \(PatchDMap p) -> mergeWith DMap.union $ catMaybes $ ffor (DMap.toList p) $ \(Const2 _ :=> ComposeMaybe me) -> me -- We could make it prompt like this, but this seems to be slower than just delaying the PostBuild event to allow this stuff to settle (which is more similar to the previous behavior anyway)
214− return (result0, result')
215−
216−instance PerformEvent t m => PerformEvent t (RequestT t request response m) where
217− type Performable (RequestT t request response m) = Performable m
218− performEvent_ = lift . performEvent_
219− performEvent = lift . performEvent
220−
221−instance PostBuild t m => PostBuild t (RequestT t request response m) where
222− getPostBuild = lift getPostBuild
223−
224−instance TriggerEvent t m => TriggerEvent t (RequestT t request response m) where
225− newTriggerEvent = lift newTriggerEvent
226− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
227− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
228−
229−instance MonadReader r m => MonadReader r (RequestT t request response m) where
230− ask = lift ask
231− local f (RequestT a) = RequestT $ mapStateT (mapReaderT $ local f) a
232− reader = lift . reader
233−
234−{-
235−withRequestT :: forall t m a (req :: * -> *) (req' :: * -> *).
236− (Reflex t, MonadHold t m, MonadFix m)
237− => (forall x. request x -> request' x)
238− -> (forall x. response' x -> response x)
239− -> RequestT t request response m a
240− -> RequestT t request' response m a
241−withRequestT f g m = RequestT $ hoist (hoist (withDynamicWriterT f')) (unRequestT m)
242− where
243− f' :: Event t [(y, Some request)] -> Event t [(y, Some request')]
244− f' = fmap . fmap . fmap $ \(SomeRequest req) -> SomeRequest $ f req
245−-}
246−
247−instance MonadRef m => MonadRef (RequestT t request response m) where
248− type Ref (RequestT t request response m) = Ref m
249− newRef = lift . newRef
250− readRef = lift . readRef
251− writeRef r = lift . writeRef r
252−
253−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequestT t request response m) where
254− newEventWithTrigger = lift . newEventWithTrigger
255− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
256−
257−
258−--------------------------------------------------------------------------------
259−-- Helpers
260−--------------------------------------------------------------------------------
261−
262−{-# INLINABLE numberWith #-}
263−numberWith :: (Enum n, Traversable t) => (n -> a -> b) -> t a -> n -> (t b, n)
264−numberWith f t n0 = flip runState n0 $ forM t $ \x -> state $ \n -> (f n x, succ n)
265−
266−{-# INLINABLE mergeSelfDeletingEvents #-}
267−mergeSelfDeletingEvents :: forall t m k v. (Ord k, Reflex t, MonadFix m, MonadHold t m)
268− => DMap (Const2 k (These v ())) (Event t)
269− -> Event t (PatchDMap (Const2 k (These v ())) (Event t))
270− -> m (Event t [v])
271−mergeSelfDeletingEvents initial eAddNew = do
272− rec events :: Incremental t (PatchDMap (Const2 k (These v ())) (Event t))
273− <- holdIncremental initial $ eAddNew <> eDelete --TODO: Eliminate empty firings
274− let event = mergeWith DMap.union
275− [ mergeIncremental events
276− , coincidence $ ffor eAddNew $ \(PatchDMap m) -> merge $ DMap.mapMaybeWithKey (const getComposeMaybe) m
277− ]
278− eDelete :: Event t (PatchDMap (Const2 k (These v ())) (Event t))
279− eDelete = fforMaybe event $
280− fmap (PatchDMap . DMap.fromDistinctAscList) .
281− (\l -> if null l then Nothing else Just l) .
282− fmapMaybe (\(Const2 k :=> Identity x) -> (Const2 k :=> ComposeMaybe Nothing) <$ x ^? there) .
283− DMap.toList
284− return $ ffor event $
285− fmapMaybe (\(Const2 _ :=> Identity x) -> x ^? here) .
286− DMap.toList
src/Reflex/PerformEvent/Class.hsdeleted−92
@@ -1,92 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE RankNTypes #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TypeFamilies #-}
8−{-# LANGUAGE TypeOperators #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−module Reflex.PerformEvent.Class where
11−
12−import Reflex.Class
13−
14−import Control.Monad.Identity
15−import Control.Monad.Reader
16−import qualified Control.Monad.State.Lazy as Lazy
17−import Control.Monad.State.Strict
18−
19−class (Reflex t, Monad (Performable m), Monad m) => PerformEvent t m | m -> t where
20− type Performable m :: * -> *
21− performEvent :: Event t (Performable m a) -> m (Event t a)
22− performEvent_ :: Event t (Performable m ()) -> m ()
23−
24−--TODO: Shouldn't have IO hard-coded
25−class Monad m => TriggerEvent t m | m -> t where
26− newTriggerEvent :: m (Event t a, a -> IO ())
27− newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow
28− newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)
29−
30−class (Reflex t, Monad m) => MonadRequest t m | m -> t where
31− type Request m :: * -> *
32− type Response m :: * -> *
33− withRequesting :: (Event t (Response m a) -> m (Event t (Request m a), r)) -> m r
34−
35−{-# INLINABLE performEventAsync #-}
36−performEventAsync :: (TriggerEvent t m, PerformEvent t m) => Event t ((a -> IO ()) -> Performable m ()) -> m (Event t a)
37−performEventAsync e = do
38− (eOut, triggerEOut) <- newTriggerEvent
39− performEvent_ $ fmap ($ triggerEOut) e
40− return eOut
41−
42−instance PerformEvent t m => PerformEvent t (ReaderT r m) where
43− type Performable (ReaderT r m) = ReaderT r (Performable m)
44− performEvent_ e = do
45− r <- ask
46− lift $ performEvent_ $ flip runReaderT r <$> e
47− performEvent e = do
48− r <- ask
49− lift $ performEvent $ flip runReaderT r <$> e
50−
51−instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
52− newTriggerEvent = lift newTriggerEvent
53− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
54− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
55−
56−instance MonadRequest t m => MonadRequest t (ReaderT r m) where
57− type Request (ReaderT r m) = Request m
58− type Response (ReaderT r m) = Response m
59− withRequesting f = do
60− r <- ask
61− lift $ withRequesting $ (`runReaderT` r) . f
62−
63−instance MonadRequest t m => MonadRequest t (StateT s m) where
64− type Request (StateT s m) = Request m
65− type Response (StateT s m) = Response m
66− withRequesting f = do
67− old <- get
68− (result, new) <- lift $ withRequesting $ \x -> do
69− ((request, result), new) <- runStateT (f x) old
70− return (request, (result, new))
71− put new
72− return result
73−
74−instance MonadRequest t m => MonadRequest t (Lazy.StateT s m) where
75− type Request (Lazy.StateT s m) = Request m
76− type Response (Lazy.StateT s m) = Response m
77− withRequesting f = do
78− old <- Lazy.get
79− (result, new) <- lift $ withRequesting $ \x -> do
80− ((request, result), new) <- Lazy.runStateT (f x) old
81− return (request, (result, new))
82− Lazy.put new
83− return result
84−
85−requesting :: MonadRequest t m => Event t (Request m a) -> m (Event t (Response m a))
86−requesting req = withRequesting $ return . (,) req
87−
88−requesting_ :: MonadRequest t m => Event t (Request m a) -> m ()
89−requesting_ req = withRequesting $ \_ -> return (req, ())
90−
91−requestingIdentity :: (MonadRequest t m, Response m ~ Identity) => Event t (Request m a) -> m (Event t a)
92−requestingIdentity = fmap (fmap runIdentity) . requesting
src/Reflex/PostBuild/Class.hsdeleted−103
@@ -1,103 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RecursiveDo #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE TypeOperators #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−module Reflex.PostBuild.Class where
12−
13−import Control.Monad.Exception
14−import Control.Monad.Primitive
15−import Control.Monad.Reader
16−import Control.Monad.Ref
17−import Control.Monad.Trans.Control
18−import qualified Data.Dependent.Map as DMap
19−import Reflex.Class
20−import Reflex.Host.Class
21−import Reflex.PerformEvent.Class
22−
23−class (Reflex t, Monad m) => PostBuild t m | m -> t where
24− getPostBuild :: m (Event t ())
25−
26−newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException)
27−
28−instance PrimMonad m => PrimMonad (PostBuildT x m) where
29− type PrimState (PostBuildT x m) = PrimState m
30− primitive = lift . primitive
31−
32−instance MonadTransControl (PostBuildT t) where
33− type StT (PostBuildT t) a = StT (ReaderT (Event t ())) a
34− {-# INLINABLE liftWith #-}
35− liftWith = defaultLiftWith PostBuildT unPostBuildT
36− {-# INLINABLE restoreT #-}
37− restoreT = defaultRestoreT PostBuildT
38−
39−instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where
40− {-# INLINABLE getPostBuild #-}
41− getPostBuild = PostBuildT ask
42−
43−instance MonadSample t m => MonadSample t (PostBuildT t m) where
44− {-# INLINABLE sample #-}
45− sample = lift . sample
46−
47−instance MonadHold t m => MonadHold t (PostBuildT t m) where
48− {-# INLINABLE hold #-}
49− hold v0 = lift . hold v0
50− {-# INLINABLE holdDyn #-}
51− holdDyn v0 = lift . holdDyn v0
52− {-# INLINABLE holdIncremental #-}
53− holdIncremental v0 = lift . holdIncremental v0
54−
55−instance PerformEvent t m => PerformEvent t (PostBuildT t m) where
56− type Performable (PostBuildT t m) = PostBuildT t (Performable m)
57− {-# INLINABLE performEvent_ #-}
58− performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e
59− {-# INLINABLE performEvent #-}
60− performEvent e = liftWith $ \run -> performEvent $ fmap run e
61−
62−instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where
63− {-# INLINABLE newEventWithTrigger #-}
64− newEventWithTrigger = PostBuildT . lift . newEventWithTrigger
65− {-# INLINABLE newFanEventWithTrigger #-}
66− newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f
67−
68−instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where
69− {-# INLINABLE newTriggerEvent #-}
70− newTriggerEvent = lift newTriggerEvent
71− {-# INLINABLE newTriggerEventWithOnComplete #-}
72− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
73− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
74−
75−instance MonadRef m => MonadRef (PostBuildT t m) where
76− type Ref (PostBuildT t m) = Ref m
77− {-# INLINABLE newRef #-}
78− newRef = lift . newRef
79− {-# INLINABLE readRef #-}
80− readRef = lift . readRef
81− {-# INLINABLE writeRef #-}
82− writeRef r = lift . writeRef r
83−
84−instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where
85− {-# INLINABLE atomicModifyRef #-}
86− atomicModifyRef r = lift . atomicModifyRef r
87−
88−{-# INLINABLE runPostBuildT #-}
89−runPostBuildT :: PostBuildT t m a -> Event t () -> m a
90−runPostBuildT (PostBuildT a) = runReaderT a
91−
92−instance PostBuild t m => PostBuild t (ReaderT r m) where
93− getPostBuild = lift getPostBuild
94−
95−instance (Reflex t, MonadHold t m, MonadFix m, MonadAdjust t m, PerformEvent t m) => MonadAdjust t (PostBuildT t m) where
96− sequenceDMapWithAdjust dm0 dm' = do
97− postBuild <- getPostBuild
98− let loweredDm0 = DMap.map (`runPostBuildT` postBuild) dm0
99− rec (result0, result') <- lift $ sequenceDMapWithAdjust loweredDm0 loweredDm'
100− delayedResult' <- performEvent $ return () <$ result' -- Delaying this result seems to be faster than making RequestT (and thus PerformEvent) more prompt
101− let loweredDm' = ffor dm' $ \(PatchDMap p) -> PatchDMap $
102− DMap.map (ComposeMaybe . fmap (\v -> runPostBuildT v =<< headE (void delayedResult')) . getComposeMaybe) p --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
103− return (result0, result')
src/Reflex/Pure.hsdeleted−171
@@ -1,171 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE EmptyDataDecls #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE InstanceSigs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TypeFamilies #-}
8−
9−-- There are two expected orphan instances in this module:
10−-- * MonadSample (Pure t) ((->) t)
11−-- * MonadHold (Pure t) ((->) t)
12−{-# OPTIONS_GHC -fno-warn-orphans #-}
13−
14−-- | This module provides a pure implementation of Reflex, which is intended to
15−-- serve as a reference for the semantics of the Reflex class. All
16−-- implementations of Reflex should produce the same results as this
17−-- implementation, although performance and laziness/strictness may differ.
18−module Reflex.Pure where
19−
20−#if !MIN_VERSION_base(4,8,0)
21−import Control.Applicative -- Necessary for GHC 7.8
22−#endif
23−
24−import Control.Monad
25−import Data.Dependent.Map (DMap, GCompare)
26−import qualified Data.Dependent.Map as DMap
27−import Data.Functor.Identity
28−import Data.Maybe
29−import Data.MemoTrie
30−import Data.Monoid
31−import Data.Type.Coercion
32−import Reflex.Class
33−
34−data Pure t
35−
36−-- | The Enum instance of t must be dense: for all x :: t, there must not exist
37−-- any y :: t such that pred x < y < x. The HasTrie instance will be used
38−-- exclusively to memoize functions of t, not for any of its other capabilities.
39−instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where
40−
41− newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }
42− newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }
43− newtype Dynamic (Pure t) a = Dynamic { unDynamic :: t -> (a, Maybe a) }
44− newtype Incremental (Pure t) p = Incremental { unIncremental :: t -> (PatchTarget p, Maybe p) }
45−
46− type PushM (Pure t) = (->) t
47− type PullM (Pure t) = (->) t
48−
49− never :: Event (Pure t) a
50− never = Event $ \_ -> Nothing
51−
52− constant :: a -> Behavior (Pure t) a
53− constant x = Behavior $ \_ -> x
54−
55− push :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
56− push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t
57−
58− pull :: PullM (Pure t) a -> Behavior (Pure t) a
59− pull = Behavior . memo
60−
61− -- [UNUSED_CONSTRAINT]: The following type signature for merge will produce a
62− -- warning because the GCompare instance is not used; however, removing the
63− -- GCompare instance produces a different warning, due to that constraint
64− -- being present in the original class definition
65−
66− --merge :: GCompare k => DMap k (Event (Pure t)) -> Event (Pure t) (DMap k Identity)
67− merge events = Event $ memo $ \t ->
68− let currentOccurrences = DMap.mapMaybeWithKey (\_ (Event a) -> Identity <$> a t) events
69− in if DMap.null currentOccurrences
70− then Nothing
71− else Just currentOccurrences
72−
73− fan :: GCompare k => Event (Pure t) (DMap k Identity) -> EventSelector (Pure t) k
74− fan e = EventSelector $ \k -> Event $ \t -> unEvent e t >>= fmap runIdentity . DMap.lookup k
75−
76− switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a
77− switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
78−
79− coincidence :: Event (Pure t) (Event (Pure t) a) -> Event (Pure t) a
80− coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
81−
82− current :: Dynamic (Pure t) a -> Behavior (Pure t) a
83− current d = Behavior $ \t -> fst $ unDynamic d t
84−
85− updated :: Dynamic (Pure t) a -> Event (Pure t) a
86− updated d = Event $ \t -> snd $ unDynamic d t
87−
88− unsafeBuildDynamic :: PullM (Pure t) a -> Event (Pure t) a -> Dynamic (Pure t) a
89− unsafeBuildDynamic readV0 v' = Dynamic $ \t -> (readV0 t, unEvent v' t)
90−
91− -- See UNUSED_CONSTRAINT, above.
92−
93− --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p
94− --a) -> Incremental (Pure t) p a
95− unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)
96−
97− mergeIncremental (Incremental f) = Event $ \t ->
98− let results = DMap.mapMaybeWithKey (\_ (Event e) -> Identity <$> e t) $ fst $ f t
99− in if DMap.null results
100− then Nothing
101− else Just results
102−
103− currentIncremental (Incremental f) = Behavior $ \t -> fst $ f t
104−
105− updatedIncremental (Incremental f) = Event $ \t -> snd $ f t
106−
107− incrementalToDynamic (Incremental f) = Dynamic $ \t ->
108− let (old, mPatch) = f t
109− e = case mPatch of
110− Nothing -> Nothing
111− Just patch -> apply patch old
112− in (old, e)
113− behaviorCoercion Coercion = Coercion
114− eventCoercion Coercion = Coercion
115− dynamicCoercion Coercion = Coercion
116−
117−instance Functor (Dynamic (Pure t)) where
118− fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t
119− in (f cur, fmap f upd)
120−
121−instance Applicative (Dynamic (Pure t)) where
122− pure a = Dynamic $ \_ -> (a, Nothing)
123− (<*>) = ap
124−
125−instance Monad (Dynamic (Pure t)) where
126− return = pure
127− (x :: Dynamic (Pure t) a) >>= (f :: a -> Dynamic (Pure t) b) = Dynamic $ \t ->
128− let (curX :: a, updX :: Maybe a) = unDynamic x t
129− (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t
130− (updInner :: Maybe b, updBoth :: Maybe b) = case updX of
131− Nothing -> (Nothing, Nothing)
132− Just nextX -> let (c, u) = unDynamic (f nextX) t
133− in (Just c, u)
134− in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])
135−
136−instance MonadSample (Pure t) ((->) t) where
137−
138− sample :: Behavior (Pure t) a -> (t -> a)
139− sample = unBehavior
140−
141−instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
142−
143− hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a
144− hold initialValue e initialTime = Behavior f
145− where f = memo $ \sampleTime ->
146− -- Really, the sampleTime should never be prior to the initialTime,
147− -- because that would mean the Behavior is being sampled before
148− -- being created.
149− if sampleTime <= initialTime
150− then initialValue
151− else let lastTime = pred sampleTime
152− in fromMaybe (f lastTime) $ unEvent e lastTime
153−
154− holdDyn :: a -> Event (Pure t) a -> t -> Dynamic (Pure t) a
155− holdDyn initialValue e initialTime =
156− let Behavior f = hold initialValue e initialTime
157− in Dynamic $ \t -> (f t, unEvent e t)
158−
159− holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p
160− holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)
161− where f = memo $ \sampleTime ->
162− -- Really, the sampleTime should never be prior to the initialTime,
163− -- because that would mean the Behavior is being sampled before
164− -- being created.
165− if sampleTime <= initialTime
166− then initialValue
167− else let lastTime = pred sampleTime
168− lastValue = f lastTime
169− in case unEvent e lastTime of
170− Nothing -> lastValue
171− Just x -> fromMaybe lastValue $ apply x lastValue
src/Reflex/Spider.hsdeleted−16
@@ -1,16 +0,0 @@
1−-- | This module exports all of the user-facing functionality of the 'Spider'
2−-- 'Reflex' engine
3−module Reflex.Spider
4− ( Spider
5− , SpiderTimeline
6− , Global
7− , SpiderHost
8− , runSpiderHost
9− , runSpiderHostForTimeline
10− , newSpiderTimeline
11− , withSpiderTimeline
12− -- * Deprecated
13− , SpiderEnv
14− ) where
15−
16−import Reflex.Spider.Internal
src/Reflex/Spider/Internal.hsdeleted−2156
@@ -1,2156 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10−{-# LANGUAGE LambdaCase #-}
11−{-# LANGUAGE MagicHash #-}
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−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
21−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
22−module Reflex.Spider.Internal where
23−
24−import Control.Applicative
25−import Control.Concurrent
26−import Control.Exception
27−import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
28−import Control.Monad.Exception
29−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
30−import Control.Monad.Primitive
31−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
32−import Control.Monad.Ref
33−import Data.Align
34−import Data.Coerce
35−import Data.Dependent.Map (DMap, DSum (..))
36−import qualified Data.Dependent.Map as DMap
37−import Data.Foldable hiding (concat, elem, sequence_)
38−import Data.Function
39−import Data.Functor.Constant
40−import Data.Functor.Product
41−import Data.GADT.Compare
42−import Data.IntMap.Strict (IntMap)
43−import qualified Data.IntMap.Strict as IntMap
44−import Data.IORef
45−import Data.List hiding (foldl')
46−import Data.Maybe
47−import Data.Monoid ((<>))
48−import Data.Proxy
49−import Data.Some (Some)
50−import qualified Data.Some as Some
51−import Data.These
52−import Data.Traversable
53−import Data.Type.Coercion
54−import Data.Word
55−import GHC.Exts
56−import GHC.IORef (IORef (..))
57−import GHC.Stack
58−import System.IO.Unsafe
59−import System.Mem.Weak
60−import Unsafe.Coerce
61−
62−#ifdef DEBUG_CYCLES
63−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
64−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
65−import qualified Data.List.NonEmpty as NonEmpty
66−import Data.Monoid (mempty)
67−import Data.Tree (Forest, Tree (..), drawForest)
68−#endif
69−
70−import Data.WeakBag (WeakBag, WeakBagTicket)
71−import qualified Data.WeakBag as WeakBag
72−import qualified Reflex.Class as R
73−import qualified Reflex.Host.Class as R
74−
75−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
76−import Prelude hiding (any, concat, mapM, mapM_, sequence)
77−
78−debugPropagate :: Bool
79−
80−debugInvalidateHeight :: Bool
81−
82−debugInvalidate :: Bool
83−
84−#ifdef DEBUG
85−
86−#define DEBUG_NODEIDS
87−
88−debugPropagate = True
89−
90−debugInvalidateHeight = False
91−
92−debugInvalidate = True
93−
94−class HasNodeId a where
95− getNodeId :: a -> Int
96−
97−instance HasNodeId (Hold x p a) where
98− getNodeId = holdNodeId
99−
100−instance HasNodeId (PushSubscribed x a b) where
101− getNodeId = pushSubscribedNodeId
102−
103−instance HasNodeId (SwitchSubscribed x a) where
104− getNodeId = switchSubscribedNodeId
105−
106−instance HasNodeId (FanSubscribed x a) where
107− getNodeId = fanSubscribedNodeId
108−
109−instance HasNodeId (CoincidenceSubscribed x a) where
110− getNodeId = coincidenceSubscribedNodeId
111−
112−instance HasNodeId (RootSubscribed x a) where
113− getNodeId = rootSubscribedNodeId
114−
115−instance HasNodeId (Pull x a) where
116− getNodeId = pullNodeId
117−
118−{-# INLINE showNodeId #-}
119−showNodeId :: HasNodeId a => a -> String
120−showNodeId = ("#"<>) . show . getNodeId
121−
122−showSubscriberType :: Subscriber x a -> String
123−showSubscriberType = \case
124− SubscriberPush _ _ -> "SubscriberPush"
125− SubscriberMerge _ _ -> "SubscriberMerge"
126− SubscriberFan _ -> "SubscriberFan"
127− SubscriberMergeChange _ -> "SubscriberMergeChange"
128− SubscriberHold _ -> "SubscriberHold"
129− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
130− SubscriberSwitch _ -> "SubscriberSwitch"
131− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
132− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
133− SubscriberHandle -> "SubscriberHandle"
134−
135−showEventType :: Event x a -> String
136−showEventType = \case
137− EventRoot _ _ -> "EventRoot"
138− EventNever -> "EventNever"
139− EventPush _ -> "EventPush"
140− EventMerge _ -> "EventMerge"
141− EventFan _ _ -> "EventFan"
142− EventSwitch _ -> "EventSwitch"
143− EventCoincidence _ -> "EventCoincidence"
144− EventHold _ -> "EventHold"
145− EventDyn _ -> "EventDyn"
146− EventHoldIdentity _ -> "EventHoldIdentity"
147− EventDynIdentity _ -> "EventDynIdentity"
148−
149−#else
150−
151−debugPropagate = False
152−
153−debugInvalidateHeight = False
154−
155−debugInvalidate = False
156−
157−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
158−{-# INLINE showNodeId #-}
159−showNodeId :: a -> String
160−showNodeId _ = ""
161−
162−#endif
163−
164−#ifdef DEBUG_NODEIDS
165−{-# NOINLINE nextNodeIdRef #-}
166−nextNodeIdRef :: IORef Int
167−nextNodeIdRef = unsafePerformIO $ newIORef 1
168−
169−newNodeId :: IO Int
170−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
171−
172−{-# NOINLINE unsafeNodeId #-}
173−unsafeNodeId :: a -> Int
174−unsafeNodeId a = unsafePerformIO $ do
175− touch a
176− newNodeId
177−#endif
178−
179−--------------------------------------------------------------------------------
180−-- Event
181−--------------------------------------------------------------------------------
182−
183−newtype Event x a = Event { subscribeAndRead :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
184−
185−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
186−-- caching; if the computation function is very cheap, this is (much) more
187−-- efficient than 'push'
188−{-# INLINABLE pushCheap #-}
189−pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
190−pushCheap f e = Event $ \sub -> do
191− (subscription, occ) <- subscribeAndRead e $ sub
192− { subscriberPropagate = \a -> do
193− mb <- runComputeM $ f a
194− mapM_ (subscriberPropagate sub) mb
195− }
196− occ' <- join <$> mapM (runComputeM . f) occ
197− return (subscription, occ')
198−
199−data CacheSubscribed x a
200− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))
201− , _cacheSubscribed_weakSelf :: {-# UNPACK #-} !(IORef (Weak (CacheSubscribed x a)))
202− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
203− , _cacheSubscribed_cached :: {-# UNPACK #-} !(IORef (Maybe (CacheSubscribed x a)))
204− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
205− }
206−
207−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
208−-- repeatedly
209−--
210−--TODO: Try a caching strategy where we subscribe directly to the parent when
211−--there's only one subscriber, and then build our own WeakBag only when a second
212−--subscriber joins
213−{-# INLINABLE cacheEvent #-}
214−cacheEvent :: HasSpiderTimeline x => Event x a -> Event x a
215−cacheEvent e = Event $ \sub -> {-# SCC "cacheEvent" #-} do
216− let !mSubscribedRef = unsafeNewIORef e Nothing
217− mSubscribed <- liftIO $ readIORef mSubscribedRef
218− case mSubscribed of
219− Just subscribed -> liftIO $ do
220− ticket <- WeakBag.insert sub (_cacheSubscribed_subscribers subscribed) (_cacheSubscribed_weakSelf subscribed) cleanupCacheSubscribed
221− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
222− let es = EventSubscribed
223− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
224− , eventSubscribedRetained = toAny subscribed
225− }
226− return (EventSubscription (WeakBag.remove ticket >> touch ticket) es, occ)
227− Nothing -> do
228− weakSelf <- liftIO $ newIORef $ error "cacheEvent: weakSelf not yet intialized"
229− (subscribers, ticket) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCacheSubscribed
230− occRef <- liftIO $ newIORef undefined
231− (parentSub, occ) <- subscribeAndRead e $ Subscriber
232− { subscriberPropagate = \a -> do
233− liftIO $ writeIORef occRef $ Just a
234− scheduleClear occRef
235− propagate a subscribers
236− , subscriberInvalidateHeight = \old -> do
237− WeakBag.traverse subscribers $ invalidateSubscriberHeight old
238− , subscriberRecalculateHeight = \new -> do
239− WeakBag.traverse subscribers $ recalculateSubscriberHeight new
240− }
241− liftIO $ writeIORef occRef occ
242− when (isJust occ) $ scheduleClear occRef
243− let !subscribed = CacheSubscribed
244− { _cacheSubscribed_subscribers = subscribers
245− , _cacheSubscribed_weakSelf = weakSelf
246− , _cacheSubscribed_parent = parentSub
247− , _cacheSubscribed_cached = mSubscribedRef
248− , _cacheSubscribed_occurrence = occRef
249− }
250− liftIO $ writeIORef mSubscribedRef $ Just subscribed
251− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
252− return (EventSubscription (WeakBag.remove ticket >> touch ticket) (EventSubscribed (eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub) (toAny subscribed)), occ)
253−
254−cleanupCacheSubscribed :: CacheSubscribed x a -> IO ()
255−cleanupCacheSubscribed self = do
256− unsubscribe $ _cacheSubscribed_parent self
257− writeIORef (_cacheSubscribed_cached self) Nothing
258−
259−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
260−subscribe e s = fst <$> subscribeAndRead e s
261−
262−{-# INLINE wrap #-}
263−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
264−wrap tag getSpecificSubscribed sub = do
265− (sln, subd, occ) <- getSpecificSubscribed sub
266− let es = tag subd
267− return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
268−
269−eventRoot :: GCompare k => k a -> Root x k -> Event x a
270−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
271−
272−eventNever :: Event x a
273−eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
274−
275−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
276−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
277−
278−eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
279−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
280−
281−eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
282−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
283−
284−eventHold :: HasSpiderTimeline x => Hold x p -> Event x p
285−eventHold !h = Event $ subscribeHoldEvent h
286−
287−eventDyn :: (HasSpiderTimeline x, R.Patch p) => Dyn x p -> Event x p
288−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
289−
290−{-# INLINE subscribeCoincidenceInner #-}
291−subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x)
292−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
293− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
294− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
295− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
296− let height = max innerHeight outerHeight
297− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
298− return (innerOcc, height, innerSubd)
299−
300−--------------------------------------------------------------------------------
301−-- Subscriber
302−--------------------------------------------------------------------------------
303−
304−data Subscriber x a = Subscriber
305− { subscriberPropagate :: !(a -> EventM x ())
306− , subscriberInvalidateHeight :: !(Height -> IO ())
307− , subscriberRecalculateHeight :: !(Height -> IO ())
308− }
309−
310−--TODO: Move this comment to WeakBag
311−-- These function are constructor functions that are marked NOINLINE so they are
312−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
313−-- so any weak references that are attached to the constructors will have their
314−-- finalizer run. Using the opaque constructor, does not see the
315−-- constructor application, so it behaves like an IORef and cannot be fused away.
316−--
317−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
318−-- the weak pointer to it in some cases.
319−
320−newSubscriberHold :: (HasSpiderTimeline x, R.Patch p) => Hold x p -> IO (Subscriber x p)
321−newSubscriberHold h = return $ Subscriber
322− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
323− , subscriberInvalidateHeight = \_ -> return ()
324− , subscriberRecalculateHeight = \_ -> return ()
325− }
326−
327−newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
328−newSubscriberFan subscribed = return $ Subscriber
329− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
330− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
331− tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
332− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
333− scheduleClear $ fanSubscribedOccurrence subscribed
334− let f _ (Pair (Identity v) subsubs) = do
335− propagate v $ _fanSubscribedChildren_list subsubs
336− return $ Constant ()
337− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
338− return ()
339− , subscriberInvalidateHeight = \old -> do
340− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
341− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
342− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
343− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
344− , subscriberRecalculateHeight = \new -> do
345− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
346− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
347− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
348− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
349− }
350−
351−newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
352−newSubscriberSwitch subscribed = return $ Subscriber
353− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
354− tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
355− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
356− scheduleClear $ switchSubscribedOccurrence subscribed
357− propagate a $ switchSubscribedSubscribers subscribed
358− , subscriberInvalidateHeight = \_ -> do
359− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
360− oldHeight <- readIORef $ switchSubscribedHeight subscribed
361− when (oldHeight /= invalidHeight) $ do
362− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
363− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
364− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
365− , subscriberRecalculateHeight = \new -> do
366− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
367− updateSwitchHeight new subscribed
368− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
369− }
370−
371−newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
372−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
373− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
374− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
375− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
376− tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
377− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
378− tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
379− tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
380− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
381− scheduleClear $ coincidenceSubscribedInnerParent subscribed
382− case occ of
383− Nothing -> do
384− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
385− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
386− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
387− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
388− Just o -> do -- Since it's already firing, no need to adjust height
389− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
390− scheduleClear $ coincidenceSubscribedOccurrence subscribed
391− propagate o $ coincidenceSubscribedSubscribers subscribed
392− , subscriberInvalidateHeight = \_ -> do
393− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
394− invalidateCoincidenceHeight subscribed
395− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
396− , subscriberRecalculateHeight = \_ -> do
397− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
398− recalculateCoincidenceHeight subscribed
399− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
400− }
401−
402−newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
403−newSubscriberCoincidenceInner subscribed = return $ Subscriber
404− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
405− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
406− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
407− case occ of
408− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
409− Nothing -> do
410− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
411− scheduleClear $ coincidenceSubscribedOccurrence subscribed
412− propagate a $ coincidenceSubscribedSubscribers subscribed
413− , subscriberInvalidateHeight = \_ -> do
414− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
415− invalidateCoincidenceHeight subscribed
416− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
417− , subscriberRecalculateHeight = \_ -> do
418− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
419− recalculateCoincidenceHeight subscribed
420− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
421− }
422−
423−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
424−invalidateSubscriberHeight = flip subscriberInvalidateHeight
425−
426−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
427−recalculateSubscriberHeight = flip subscriberRecalculateHeight
428−
429−-- | Propagate everything at the current height
430−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
431−propagate a subscribers = withIncreasedDepth $ do
432− -- 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
433− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
434− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
435−
436−--------------------------------------------------------------------------------
437−-- EventSubscribed
438−--------------------------------------------------------------------------------
439−
440−toAny :: a -> Any
441−toAny = unsafeCoerce
442−
443−data EventSubscribed x = EventSubscribed
444− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
445− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
446−#ifdef DEBUG_CYCLES
447− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
448− , eventSubscribedHasOwnHeightRef :: !Bool
449− , eventSubscribedWhoCreated :: !(IO [String])
450−#endif
451− }
452−
453−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
454−eventSubscribedRoot !r = EventSubscribed
455− { eventSubscribedHeightRef = zeroRef
456− , eventSubscribedRetained = toAny r
457−#ifdef DEBUG_CYCLES
458− , eventSubscribedGetParents = return []
459− , eventSubscribedHasOwnHeightRef = False
460− , eventSubscribedWhoCreated = return ["root"]
461−#endif
462− }
463−
464−eventSubscribedNever :: EventSubscribed x
465−eventSubscribedNever = EventSubscribed
466− { eventSubscribedHeightRef = zeroRef
467− , eventSubscribedRetained = toAny ()
468−#ifdef DEBUG_CYCLES
469− , eventSubscribedGetParents = return []
470− , eventSubscribedHasOwnHeightRef = False
471− , eventSubscribedWhoCreated = return ["never"]
472−#endif
473− }
474−
475−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
476−eventSubscribedFan !subscribed = EventSubscribed
477− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
478− , eventSubscribedRetained = toAny subscribed
479−#ifdef DEBUG_CYCLES
480− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
481− , eventSubscribedHasOwnHeightRef = False
482− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
483−#endif
484− }
485−
486−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
487−eventSubscribedSwitch !subscribed = EventSubscribed
488− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
489− , eventSubscribedRetained = toAny subscribed
490−#ifdef DEBUG_CYCLES
491− , eventSubscribedGetParents = do
492− s <- readIORef $ switchSubscribedCurrentParent subscribed
493− return [Some.This $ _eventSubscription_subscribed s]
494− , eventSubscribedHasOwnHeightRef = True
495− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
496−#endif
497− }
498−
499−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
500−eventSubscribedCoincidence !subscribed = EventSubscribed
501− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
502− , eventSubscribedRetained = toAny subscribed
503−#ifdef DEBUG_CYCLES
504− , eventSubscribedGetParents = do
505− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
506− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
507− innerParents = maybeToList $ fmap Some.This innerSubscription
508− return $ outerParent : innerParents
509− , eventSubscribedHasOwnHeightRef = True
510− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
511−#endif
512− }
513−
514−getEventSubscribedHeight :: EventSubscribed x -> IO Height
515−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
516−
517−#ifdef DEBUG_CYCLES
518−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
519−whoCreatedEventSubscribed = eventSubscribedWhoCreated
520−
521−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
522−walkInvalidHeightParents s0 = do
523− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
524− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
525− when (h == invalidHeight) $ do
526− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
527− modify (Some.This s :)
528− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
529− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
530− return subscribers
531−#endif
532−
533−{-# INLINE subscribeHoldEvent #-}
534−subscribeHoldEvent :: CanSubscribe x m => Hold x p -> Subscriber x p -> m (EventSubscription x, Maybe p)
535−subscribeHoldEvent = subscribeAndRead . holdEvent
536−
537−--------------------------------------------------------------------------------
538−-- EventSubscription
539−--------------------------------------------------------------------------------
540−
541−data EventSubscription x = EventSubscription
542− { _eventSubscription_unsubscribe :: !(IO ())
543− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
544− }
545−
546−unsubscribe :: EventSubscription x -> IO ()
547−unsubscribe (EventSubscription u _) = u
548−
549−--------------------------------------------------------------------------------
550−-- Behavior
551−--------------------------------------------------------------------------------
552−
553−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
554−
555−behaviorHold :: Hold x p -> Behavior x (R.PatchTarget p)
556−behaviorHold !h = Behavior $ readHoldTracked h
557−
558−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
559−behaviorHoldIdentity = behaviorHold
560−
561−behaviorConst :: a -> Behavior x a
562−behaviorConst !a = Behavior $ return a
563−
564−behaviorPull :: Pull x a -> Behavior x a
565−behaviorPull !p = Behavior $ do
566− val <- liftIO $ readIORef $ pullValue p
567− case val of
568− Just subscribed -> do
569− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
570− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
571− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
572− return $ pullSubscribedValue subscribed
573− Nothing -> do
574− i <- liftIO $ newInvalidatorPull p
575− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
576− parentsRef <- liftIO $ newIORef []
577− holdInits <- askBehaviorHoldInits
578− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
579− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
580− parents <- liftIO $ readIORef parentsRef
581− let subscribed = PullSubscribed
582− { pullSubscribedValue = a
583− , pullSubscribedInvalidators = invsRef
584− , pullSubscribedOwnInvalidator = i
585− , pullSubscribedParents = parents
586− }
587− liftIO $ writeIORef (pullValue p) $ Just subscribed
588− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
589− return a
590−
591−behaviorDyn :: (HasSpiderTimeline x, R.Patch p) => Dyn x p -> Behavior x (R.PatchTarget p)
592−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
593−
594−{-# INLINE readHoldTracked #-}
595−readHoldTracked :: Hold x p -> BehaviorM x (R.PatchTarget p)
596−readHoldTracked h = do
597− result <- liftIO $ readIORef $ holdValue h
598− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
599− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
600− return result
601−
602−{-# SPECIALIZE readBehaviorUntracked :: HasSpiderTimeline x => Behavior x a -> BehaviorM x a #-}
603−{-# SPECIALIZE readBehaviorUntracked :: HasSpiderTimeline x => Behavior x a -> EventM x a #-}
604−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
605−readBehaviorUntracked b = do
606− holdInits <- getDeferralQueue
607− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
608−
609−--------------------------------------------------------------------------------
610−-- Dynamic
611−--------------------------------------------------------------------------------
612−
613−data Dynamic x p = Dynamic
614− { dynamicCurrent :: !(Behavior x (R.PatchTarget p))
615− , dynamicUpdated :: !(Event x p)
616− }
617−
618−dynamicHold :: HasSpiderTimeline x => Hold x p -> Dynamic x p
619−dynamicHold !h = Dynamic
620− { dynamicCurrent = behaviorHold h
621− , dynamicUpdated = eventHold h
622− }
623−
624−dynamicHoldIdentity :: HasSpiderTimeline x => Hold x (Identity a) -> Dynamic x (Identity a)
625−dynamicHoldIdentity = dynamicHold
626−
627−dynamicConst :: R.PatchTarget p -> Dynamic x p
628−dynamicConst !a = Dynamic
629− { dynamicCurrent = behaviorConst a
630− , dynamicUpdated = eventNever
631− }
632−
633−dynamicDyn :: (HasSpiderTimeline x, R.Patch p) => Dyn x p -> Dynamic x p
634−dynamicDyn !d = Dynamic
635− { dynamicCurrent = behaviorDyn d
636− , dynamicUpdated = eventDyn d
637− }
638−
639−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
640−dynamicDynIdentity = dynamicDyn
641−
642−--------------------------------------------------------------------------------
643−-- Combinators
644−--------------------------------------------------------------------------------
645−
646−--TODO: Figure out why certain things are not 'representational', then make them
647−--representational so we can use coerce
648−
649−--type role Hold representational
650−data Hold x p
651− = Hold { holdValue :: !(IORef (R.PatchTarget p))
652− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
653− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
654− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
655−#ifdef DEBUG_NODEIDS
656− , holdNodeId :: Int
657−#endif
658− }
659−
660−data EventEnv x
661− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
662− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
663− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
664− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
665− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
666− , eventEnvRootClears :: !(IORef [SomeRootClear])
667− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
668− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
669− , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
670− }
671−
672−{-# INLINE runEventM #-}
673−runEventM :: EventM x a -> IO a
674−runEventM = unEventM
675−
676−asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
677−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimeline x)
678−
679−class MonadIO m => Defer a m where
680− getDeferralQueue :: m (IORef [a])
681−
682−{-# INLINE defer #-}
683−defer :: Defer a m => a -> m ()
684−defer a = do
685− q <- getDeferralQueue
686− liftIO $ modifyIORef' q (a:)
687−
688−instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
689− {-# INLINE getDeferralQueue #-}
690− getDeferralQueue = asksEventEnv eventEnvAssignments
691−
692−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
693− {-# INLINE getDeferralQueue #-}
694− getDeferralQueue = asksEventEnv eventEnvHoldInits
695−
696−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (BehaviorM x) where
697− {-# INLINE getDeferralQueue #-}
698− getDeferralQueue = BehaviorM $ asks snd
699−
700−instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
701− {-# INLINE getDeferralQueue #-}
702− getDeferralQueue = asksEventEnv eventEnvMergeUpdates
703−
704−instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
705− {-# INLINE getDeferralQueue #-}
706− getDeferralQueue = asksEventEnv eventEnvMergeInits
707−
708−class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
709− getCurrentHeight :: m Height
710− scheduleMerge :: Height -> EventM x () -> m ()
711−
712−instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
713− {-# INLINE getCurrentHeight #-}
714− getCurrentHeight = do
715− heightRef <- asksEventEnv eventEnvCurrentHeight
716− liftIO $ readIORef heightRef
717− {-# INLINE scheduleMerge #-}
718− scheduleMerge height subscribed = do
719− delayedRef <- asksEventEnv eventEnvDelayedMerges
720− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
721−
722−class HasSpiderTimeline x where
723− -- | Retrieve the current SpiderTimeline
724− spiderTimeline :: SpiderTimeline x
725−
726−instance HasSpiderTimeline Global where
727− spiderTimeline = globalSpiderTimeline
728−
729−putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
730−putCurrentHeight h = do
731− heightRef <- asksEventEnv eventEnvCurrentHeight
732− liftIO $ writeIORef heightRef $! h
733−
734−instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
735− {-# INLINE getDeferralQueue #-}
736− getDeferralQueue = asksEventEnv eventEnvClears
737−
738−{-# INLINE scheduleClear #-}
739−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
740−scheduleClear r = defer $ SomeClear r
741−
742−instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
743− {-# INLINE getDeferralQueue #-}
744− getDeferralQueue = asksEventEnv eventEnvRootClears
745−
746−{-# INLINE scheduleRootClear #-}
747−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
748−scheduleRootClear r = defer $ SomeRootClear r
749−
750−instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
751− {-# INLINE getDeferralQueue #-}
752− getDeferralQueue = asksEventEnv eventEnvResetCoincidences
753−
754−-- Note: hold cannot examine its event until after the phase is over
755−{-# SPECIALIZE hold :: (HasSpiderTimeline x, R.Patch p) => R.PatchTarget p -> Event x p -> EventM x (Hold x p) #-}
756−{- SPECIALIZE hold :: (HasSpiderTimeline x, R.Patch p) => R.PatchTarget p -> Event x p -> ComputeM x (Hold x p) #-}
757−hold :: (R.Patch p, Defer (SomeHoldInit x) m) => R.PatchTarget p -> Event x p -> m (Hold x p)
758−hold v0 e = do
759− valRef <- liftIO $ newIORef v0
760− invsRef <- liftIO $ newIORef []
761− parentRef <- liftIO $ newIORef Nothing
762−#ifdef DEBUG_NODEIDS
763− nodeId <- liftIO newNodeId
764−#endif
765− let h = Hold
766− { holdValue = valRef
767− , holdInvalidators = invsRef
768− , holdEvent = e
769− , holdParent = parentRef
770−#ifdef DEBUG_NODEIDS
771− , holdNodeId = nodeId
772−#endif
773− }
774− defer $ SomeHoldInit h
775− return h
776−
777−{-# INLINE getHoldEventSubscription #-}
778−getHoldEventSubscription :: forall m p x. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer SomeClear m, R.Patch p, HasCurrentHeight x m, Defer (SomeMergeInit x) m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x) => Hold x p -> m (EventSubscription x)
779−getHoldEventSubscription h = do
780− ep <- liftIO $ readIORef $ holdParent h
781− case ep of
782− Just subd -> return subd
783− Nothing -> do
784− let e = holdEvent h
785− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
786− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
787− liftIO $ writeIORef subscriptionRef $! subscription
788− case occ of
789− Nothing -> return ()
790− Just o -> do
791− old <- liftIO $ readIORef $ holdValue h
792− case R.apply o old of
793− Nothing -> return ()
794− Just new -> do
795− -- Need to evaluate these so that we don't retain the Hold itself
796− v <- liftIO $ evaluate $ holdValue h
797− i <- liftIO $ evaluate $ holdInvalidators h
798− defer $ SomeAssignment v i new
799− liftIO $ writeIORef (holdParent h) $ Just subscription
800− return subscription
801−
802−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
803−
804−--type role BehaviorM representational
805−-- BehaviorM can sample behaviors
806−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
807−
808−instance Monad (BehaviorM x) where
809− {-# INLINE (>>=) #-}
810− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
811− {-# INLINE (>>) #-}
812− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
813− {-# INLINE return #-}
814− return x = BehaviorM $ return x
815− {-# INLINE fail #-}
816− fail s = BehaviorM $ fail s
817−
818−data BehaviorSubscribed x a
819− = forall p. BehaviorSubscribedHold (Hold x p)
820− | BehaviorSubscribedPull (PullSubscribed x a)
821−
822−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
823−
824−--type role PullSubscribed representational
825−data PullSubscribed x a
826− = PullSubscribed { pullSubscribedValue :: !a
827− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
828− , pullSubscribedOwnInvalidator :: !(Invalidator x)
829− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
830− }
831−
832−--type role Pull representational
833−data Pull x a
834− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
835− , pullCompute :: !(BehaviorM x a)
836−#ifdef DEBUG_NODEIDS
837− , pullNodeId :: Int
838−#endif
839− }
840−
841−data Invalidator x
842− = forall a. InvalidatorPull (Pull x a)
843− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
844−
845−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
846− { rootSubscribedKey :: !(k a)
847− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
848− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
849− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
850− , rootSubscribedUninit :: IO ()
851− , 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?
852−#ifdef DEBUG_NODEIDS
853− , rootSubscribedNodeId :: Int
854−#endif
855− }
856−
857−data Root x (k :: * -> *)
858− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
859− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
860− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
861− }
862−
863−data SomeHoldInit x = forall p. R.Patch p => SomeHoldInit !(Hold x p)
864−
865−data SomeMergeUpdate x = SomeMergeUpdate
866− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
867− , _someMergeUpdate_invalidateHeight :: !(IO ())
868− , _someMergeUpdate_recalculateHeight :: !(IO ())
869− }
870−
871−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
872−
873−-- EventM can do everything BehaviorM can, plus create holds
874−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
875−
876−newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
877−
878−instance Defer (SomeHoldInit x) (ComputeM x) where
879− getDeferralQueue = ComputeM ask
880−
881−{-# SPECIALIZE runComputeM :: HasSpiderTimeline x => ComputeM x a -> EventM x a #-}
882−runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
883−runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
884−
885−newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
886−
887−data HeightBag = HeightBag
888− { _heightBag_size :: {-# UNPACK #-} !Int
889− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
890− }
891− deriving (Show, Read, Eq, Ord)
892−
893−heightBagEmpty :: HeightBag
894−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
895−
896−heightBagSize :: HeightBag -> Int
897−heightBagSize = _heightBag_size
898−
899−heightBagFromList :: [Height] -> HeightBag
900−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
901−
902−heightBagAdd :: Height -> HeightBag -> HeightBag
903−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
904−
905−heightBagRemove :: Height -> HeightBag -> HeightBag
906−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
907− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
908− Just old -> HeightBag (pred s) $ case old of
909− 0 -> IntMap.delete h c
910− _ -> IntMap.insert h (pred old) c
911−
912−heightBagMax :: HeightBag -> Height
913−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
914− Just ((h, _), _) -> Height h
915− Nothing -> zeroHeight
916−
917−heightBagVerify :: HeightBag -> HeightBag
918−#ifdef DEBUG
919−heightBagVerify b@(HeightBag s c) = if
920− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
921− -> error $ "heightBagVerify: size doesn't match: " <> show b
922− | unHeight invalidHeight `IntMap.member` c
923− -> error $ "heightBagVerify: contains invalid height: " <> show b
924− | otherwise -> b
925−#else
926−heightBagVerify = id
927−#endif
928−
929−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
930− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
931− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
932− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
933− }
934−
935−data FanSubscribed (x :: *) k
936− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
937− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
938− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
939− , fanSubscribedParent :: !(EventSubscription x)
940−#ifdef DEBUG_NODEIDS
941− , fanSubscribedNodeId :: Int
942−#endif
943− }
944−
945−data Fan x k
946− = Fan { fanParent :: !(Event x (DMap k Identity))
947− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
948− }
949−
950−data SwitchSubscribed x a
951− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
952− , switchSubscribedOccurrence :: !(IORef (Maybe a))
953− , switchSubscribedHeight :: !(IORef Height)
954− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
955− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
956− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
957− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
958− , switchSubscribedParent :: !(Behavior x (Event x a))
959− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
960− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
961−#ifdef DEBUG_NODEIDS
962− , switchSubscribedNodeId :: Int
963−#endif
964− }
965−
966−data Switch x a
967− = Switch { switchParent :: !(Behavior x (Event x a))
968− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
969− }
970−
971−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
972−data CoincidenceSubscribed x a
973− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
974− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
975− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
976− , coincidenceSubscribedHeight :: !(IORef Height)
977− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
978− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
979− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
980− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
981−#ifdef DEBUG_NODEIDS
982− , coincidenceSubscribedNodeId :: Int
983−#endif
984− }
985−
986−data Coincidence x a
987− = Coincidence { coincidenceParent :: !(Event x (Event x a))
988− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
989− }
990−
991−{-# NOINLINE newInvalidatorSwitch #-}
992−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
993−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
994−
995−{-# NOINLINE newInvalidatorPull #-}
996−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
997−newInvalidatorPull p = return $! InvalidatorPull p
998−
999−instance HasSpiderTimeline x => R.FunctorMaybe (Event x) where
1000− fmapMaybe f = push $ return . f
1001−
1002−instance HasSpiderTimeline x => Align (Event x) where
1003− nil = eventNever
1004− align ea eb = R.fmapMaybe R.dmapToThese $ merge $ dynamicConst $ DMap.fromList [R.LeftTag :=> ea, R.RightTag :=> eb]
1005−
1006−newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (R.PatchTarget p), Event x p) (Hold x p)) }
1007−
1008−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1009−newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1010−
1011−--TODO: Avoid the duplication between this and R.zipDynWith
1012−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1013−zipDynWith f da db =
1014− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1015− ec = flip push eab $ \o -> do
1016− (a, b) <- case o of
1017− This (Identity a) -> do
1018− b <- readBehaviorUntracked $ dynamicCurrent db
1019− return (a, b)
1020− That (Identity b) -> do
1021− a <- readBehaviorUntracked $ dynamicCurrent da
1022− return (a, b)
1023− These (Identity a) (Identity b) -> return (a, b)
1024− return $ Just $ Identity $ f a b
1025− in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1026−
1027−unsafeDyn :: BehaviorM x (R.PatchTarget p) -> Event x p -> Dyn x p
1028−unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1029− where x = (readV0, v')
1030−
1031−newJoinDyn :: HasSpiderTimeline x => Dynamic x (Identity (Dynamic x (Identity a))) -> Dyn x (Identity a)
1032−newJoinDyn d =
1033− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
1034− eOuter = push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
1035− eInner = switch $ dynamicUpdated <$> dynamicCurrent d
1036− eBoth = coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
1037− v' = unSpiderEvent $ R.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
1038− in unsafeDyn readV0 v'
1039−
1040−-- ResultM can read behaviors and events
1041−type ResultM = EventM
1042−
1043−{-# NOINLINE unsafeNewIORef #-}
1044−unsafeNewIORef :: a -> b -> IORef b
1045−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1046−
1047−instance HasSpiderTimeline x => Functor (Event x) where
1048− fmap f = push $ return . Just . f
1049−
1050−instance Functor (Behavior x) where
1051− fmap f = pull . fmap f . readBehaviorTracked
1052−
1053−{-# INLINABLE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
1054−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1055−push f e = cacheEvent (pushCheap f e)
1056−{-
1057−push f e = eventPush $ Push
1058− { pushCompute = f
1059− , pushParent = e
1060− , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
1061− }
1062−-- DISABLED: {- RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
1063−-}
1064−
1065−{-# INLINABLE pull #-}
1066−pull :: BehaviorM x a -> Behavior x a
1067−pull a = behaviorPull $ Pull
1068− { pullCompute = a
1069− , pullValue = unsafeNewIORef a Nothing
1070−#ifdef DEBUG_NODEIDS
1071− , pullNodeId = unsafeNodeId a
1072−#endif
1073− }
1074−
1075−{-# INLINABLE switch #-}
1076−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1077−switch a = eventSwitch $ Switch
1078− { switchParent = a
1079− , switchSubscribed = unsafeNewIORef a Nothing
1080− }
1081−
1082−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1083−coincidence a = eventCoincidence $ Coincidence
1084− { coincidenceParent = a
1085− , coincidenceSubscribed = unsafeNewIORef a Nothing
1086− }
1087−
1088−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1089−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1090−run roots after = do
1091− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1092− spiderTimeline <- SpiderHost ask
1093− result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock spiderTimeline) $ \_ -> flip runReaderT spiderTimeline $ unSpiderHost $ runFrame $ do
1094− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1095− occBefore <- liftIO $ do
1096− occBefore <- readIORef occRef
1097− writeIORef occRef $! DMap.insert k a occBefore
1098− return occBefore
1099− if DMap.null occBefore
1100− then do scheduleRootClear occRef
1101− return $ Just r
1102− else return Nothing
1103− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1104− propagate a subscribersRef
1105− delayedRef <- asksEventEnv eventEnvDelayedMerges
1106− let go = do
1107− delayed <- liftIO $ readIORef delayedRef
1108− case IntMap.minViewWithKey delayed of
1109− Nothing -> return ()
1110− Just ((currentHeight, cur), future) -> do
1111− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1112− putCurrentHeight $ Height currentHeight
1113− liftIO $ writeIORef delayedRef $! future
1114− sequence_ cur
1115− go
1116− go
1117− putCurrentHeight maxBound
1118− after
1119− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1120− return result
1121−
1122−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1123−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1124− height <- liftIO $ readIORef heightRef
1125− currentHeight <- getCurrentHeight
1126− case height `compare` currentHeight of
1127− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1128− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1129− EQ -> a
1130−
1131−data SomeClear = forall a. SomeClear (IORef (Maybe a))
1132−
1133−data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1134−
1135−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1136−
1137−debugFinalize :: Bool
1138−debugFinalize = False
1139−
1140−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1141−mkWeakPtrWithDebug x debugNote = do
1142− x' <- evaluate x
1143− mkWeakPtr x' $
1144− if debugFinalize
1145− then Just $ putStrLn $ "finalizing: " ++ debugNote
1146− else Nothing
1147−
1148−type WeakList a = [Weak a]
1149−
1150−{-# INLINE withIncreasedDepth #-}
1151−#ifdef DEBUG
1152−withIncreasedDepth :: CanTrace x m => m a -> m a
1153−withIncreasedDepth a = do
1154− spiderTimeline <- askSpiderTimeline
1155− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1156− result <- a
1157− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1158− return result
1159−#else
1160−withIncreasedDepth :: m a -> m a
1161−withIncreasedDepth = id
1162−#endif
1163−
1164−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1165−
1166−{-# INLINE tracePropagate #-}
1167−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1168−tracePropagate p = traceWhen p debugPropagate
1169−
1170−{-# INLINE traceInvalidate #-}
1171−traceInvalidate :: String -> IO ()
1172−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1173−
1174−{-# INLINE traceWhen #-}
1175−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1176−traceWhen p b message = traceMWhen p b $ return message
1177−
1178−{-# INLINE traceMWhen #-}
1179−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1180−traceMWhen _ b getMessage = when b $ do
1181− message <- getMessage
1182−#ifdef DEBUG
1183− spiderTimeline <- askSpiderTimeline
1184− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1185−#else
1186− let d = 0
1187−#endif
1188− liftIO $ putStrLn $ replicate d ' ' <> message
1189−
1190−whoCreatedIORef :: IORef a -> IO [String]
1191−whoCreatedIORef (IORef a) = whoCreated $! a
1192−
1193−#ifdef DEBUG_CYCLES
1194−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1195−groupByHead = \case
1196− [] -> []
1197− (x :| xs) : t -> case groupByHead t of
1198− [] -> [(x, xs :| [])]
1199− l@((y, yss) : t')
1200− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1201− | otherwise -> (x, xs :| []) : l
1202−
1203−listsToForest :: Eq a => [[a]] -> Forest a
1204−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1205−#endif
1206−
1207−{-# INLINE propagateSubscriberHold #-}
1208−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, R.Patch p) => Hold x p -> p -> EventM x ()
1209−propagateSubscriberHold h a = do
1210− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1211− invalidators <- liftIO $ readIORef $ holdInvalidators h
1212− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1213− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1214− case {-# SCC "apply" #-} R.apply a v of
1215− Nothing -> return ()
1216− Just v' -> do
1217− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1218− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1219− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1220− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1221−
1222−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1223−
1224−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1225−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1226−
1227−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1228−askInvalidator = do
1229− (!m, _) <- BehaviorM ask
1230− case m of
1231− Nothing -> return Nothing
1232− Just (!wi, _) -> return $ Just wi
1233−
1234−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1235−askParentsRef = do
1236− (!m, _) <- BehaviorM ask
1237− case m of
1238− Nothing -> return Nothing
1239− Just (_, !p) -> return $ Just p
1240−
1241−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1242−askBehaviorHoldInits = do
1243− (_, !his) <- BehaviorM ask
1244− return his
1245−
1246−{-# INLINE getDynHold #-}
1247−getDynHold :: (Defer (SomeHoldInit x) m, R.Patch p) => Dyn x p -> m (Hold x p)
1248−getDynHold d = do
1249− mh <- liftIO $ readIORef $ unDyn d
1250− case mh of
1251− Right h -> return h
1252− Left (readV0, v') -> do
1253− holdInits <- getDeferralQueue
1254− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1255− h <- hold v0 v'
1256− liftIO $ writeIORef (unDyn d) $ Right h
1257− return h
1258−
1259−-- Always refers to 0
1260−{-# NOINLINE zeroRef #-}
1261−zeroRef :: IORef Height
1262−zeroRef = unsafePerformIO $ newIORef zeroHeight
1263−
1264−type CanSubscribe x m =
1265− ( HasSpiderTimeline x
1266− , HasCurrentHeight x m
1267− , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1268− , Defer SomeClear m -- Wiping out event firings
1269− , Defer (SomeAssignment x) m -- Updating state
1270− , Defer (SomeResetCoincidence x) m
1271− , m ~ EventM x
1272− )
1273−
1274−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1275−getRootSubscribed k r sub = do
1276− mSubscribed <- readIORef $ rootSubscribed r
1277− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1278− case DMap.lookup k mSubscribed of
1279− Just subscribed -> {-# SCC "hitRoot" #-} do
1280− sln <- subscribeRootSubscribed subscribed sub
1281− occ <- getOcc
1282− return (sln, subscribed, occ)
1283− Nothing -> {-# SCC "missRoot" #-} do
1284− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1285− let !cached = rootSubscribed r
1286− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1287− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1288− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1289− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1290− writeIORef uninitRef $! uninit
1291− let subscribed = RootSubscribed
1292− { rootSubscribedKey = k
1293− , rootSubscribedCachedSubscribed = cached
1294− , rootSubscribedOccurrence = getOcc
1295− , rootSubscribedSubscribers = subs
1296− , rootSubscribedUninit = uninit
1297− , rootSubscribedWeakSelf = weakSelf
1298−#ifdef DEBUG_NODEIDS
1299− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1300−#endif
1301− }
1302− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1303− 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
1304− occ <- getOcc
1305− return (sln, subscribed, occ)
1306−
1307−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1308−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1309−cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1310− rootSubscribedUninit self
1311− modifyIORef' cached $ DMap.delete k
1312−
1313−{-# INLINE subscribeRootSubscribed #-}
1314−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1315−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1316−
1317−{-# SPECIALIZE getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a) #-}
1318−getFanSubscribed :: (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x, GCompare k) => k a -> Fan x k -> Subscriber x a -> m (WeakBagTicket, FanSubscribed x k, Maybe a)
1319−getFanSubscribed k f sub = do
1320− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1321− case mSubscribed of
1322− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1323− sln <- subscribeFanSubscribed k subscribed sub
1324− occ <- readIORef $ fanSubscribedOccurrence subscribed
1325− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1326− Nothing -> {-# SCC "missFan" #-} do
1327− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1328− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1329− s <- liftIO $ newSubscriberFan subscribedUnsafe
1330− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1331− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1332− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1333− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1334− occRef <- liftIO $ newIORef parentOcc
1335− when (isJust parentOcc) $ scheduleClear occRef
1336− let subscribed = FanSubscribed
1337− { fanSubscribedCachedSubscribed = fanSubscribed f
1338− , fanSubscribedOccurrence = occRef
1339− , fanSubscribedParent = subscription
1340− , fanSubscribedSubscribers = subscribersRef
1341−#ifdef DEBUG_NODEIDS
1342− , fanSubscribedNodeId = unsafeNodeId f
1343−#endif
1344− }
1345− let !self = (k, subscribed)
1346− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1347− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1348− liftIO $ writeIORef subscribedRef $! subscribed
1349− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1350− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1351−
1352−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1353−cleanupFanSubscribed (k, subscribed) = do
1354− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1355− let reducedSubscribers = DMap.delete k subscribers
1356− if DMap.null reducedSubscribers
1357− then do
1358− unsubscribe $ fanSubscribedParent subscribed
1359− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1360− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1361− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1362−
1363−{-# INLINE subscribeFanSubscribed #-}
1364−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1365−subscribeFanSubscribed k subscribed sub = do
1366− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1367− case DMap.lookup k subscribers of
1368− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1369− let !self = (k, subscribed)
1370− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1371− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1372− 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
1373− return sln
1374− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1375−
1376−{-# SPECIALIZE getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a) #-}
1377−getSwitchSubscribed :: (Defer (SomeHoldInit x) m, Defer (SomeAssignment x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, Defer (SomeResetCoincidence x) m, HasCurrentHeight x m, HasSpiderTimeline x, m ~ EventM x) => Switch x a -> Subscriber x a -> m (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1378−getSwitchSubscribed s sub = do
1379− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1380− case mSubscribed of
1381− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1382− sln <- subscribeSwitchSubscribed subscribed sub
1383− occ <- readIORef $ switchSubscribedOccurrence subscribed
1384− return (sln, subscribed, occ)
1385− Nothing -> {-# SCC "missSwitch" #-} do
1386− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1387− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1388− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1389− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1390− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1391− wiRef <- liftIO $ newIORef wi
1392− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1393− holdInits <- getDeferralQueue
1394− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1395− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1396− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1397− subscriptionRef <- liftIO $ newIORef subscription
1398− occRef <- liftIO $ newIORef parentOcc
1399− when (isJust parentOcc) $ scheduleClear occRef
1400− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1401− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1402− let !subscribed = SwitchSubscribed
1403− { switchSubscribedCachedSubscribed = switchSubscribed s
1404− , switchSubscribedOccurrence = occRef
1405− , switchSubscribedHeight = heightRef
1406− , switchSubscribedSubscribers = subs
1407− , switchSubscribedOwnInvalidator = i
1408− , switchSubscribedOwnWeakInvalidator = wiRef
1409− , switchSubscribedBehaviorParents = parentsRef
1410− , switchSubscribedParent = switchParent s
1411− , switchSubscribedCurrentParent = subscriptionRef
1412− , switchSubscribedWeakSelf = weakSelf
1413−#ifdef DEBUG_NODEIDS
1414− , switchSubscribedNodeId = unsafeNodeId s
1415−#endif
1416− }
1417− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1418− liftIO $ writeIORef subscribedRef $! subscribed
1419− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1420− return (slnForSub, subscribed, parentOcc)
1421−
1422−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1423−cleanupSwitchSubscribed subscribed = do
1424− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1425− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1426− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1427−
1428−{-# INLINE subscribeSwitchSubscribed #-}
1429−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1430−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1431−
1432−{-# SPECIALIZE getCoincidenceSubscribed :: HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a) #-}
1433−getCoincidenceSubscribed :: forall x a m. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x) => Coincidence x a -> Subscriber x a -> m (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1434−getCoincidenceSubscribed c sub = do
1435− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1436− case mSubscribed of
1437− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1438− sln <- subscribeCoincidenceSubscribed subscribed sub
1439− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1440− return (sln, subscribed, occ)
1441− Nothing -> {-# SCC "missCoincidence" #-} do
1442− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1443− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1444− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1445− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1446− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1447− (occ, height, mInnerSubd) <- case outerOcc of
1448− Nothing -> return (Nothing, outerHeight, Nothing)
1449− Just o -> do
1450− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1451− return (occ, height, Just innerSubd)
1452− occRef <- liftIO $ newIORef occ
1453− when (isJust occ) $ scheduleClear occRef
1454− heightRef <- liftIO $ newIORef height
1455− innerSubdRef <- liftIO $ newIORef mInnerSubd
1456− scheduleClear innerSubdRef
1457− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1458− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1459− let subscribed = CoincidenceSubscribed
1460− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1461− , coincidenceSubscribedOccurrence = occRef
1462− , coincidenceSubscribedHeight = heightRef
1463− , coincidenceSubscribedSubscribers = subs
1464− , coincidenceSubscribedOuter = subOuter
1465− , coincidenceSubscribedOuterParent = outerSubscription
1466− , coincidenceSubscribedInnerParent = innerSubdRef
1467− , coincidenceSubscribedWeakSelf = weakSelf
1468−#ifdef DEBUG_NODEIDS
1469− , coincidenceSubscribedNodeId = unsafeNodeId c
1470−#endif
1471− }
1472− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1473− liftIO $ writeIORef subscribedRef $! subscribed
1474− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1475− return (slnForSub, subscribed, occ)
1476−
1477−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1478−cleanupCoincidenceSubscribed subscribed = do
1479− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1480− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1481−
1482−{-# INLINE subscribeCoincidenceSubscribed #-}
1483−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1484−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1485−
1486−{-# INLINE merge #-}
1487−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (R.PatchDMap k (Event x)) -> Event x (DMap k Identity)
1488−merge d = cacheEvent $ Event $ \sub -> do
1489− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1490− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1491− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1492− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1493− parentsRef <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1494− let scheduleSelf height = scheduleMerge' height heightRef $ do
1495− m <- liftIO $ readIORef accumRef
1496− liftIO $ writeIORef accumRef $! DMap.empty
1497− --TODO: Assert that m is not empty
1498− subscriberPropagate sub m
1499− invalidateMyHeight = do
1500− oldHeight <- readIORef heightRef
1501− 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
1502− writeIORef heightRef $! invalidHeight
1503− subscriberInvalidateHeight sub oldHeight
1504− revalidateMyHeight = do
1505− currentHeight <- readIORef heightRef
1506− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1507− heights <- readIORef heightBagRef
1508− parents <- readIORef parentsRef
1509− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1510− case heightBagSize heights `compare` DMap.size parents of
1511− LT -> return ()
1512− EQ -> do
1513− let height = succHeight $ heightBagMax heights
1514− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1515− writeIORef heightRef $! height
1516− subscriberRecalculateHeight sub height
1517− GT -> error $ "revalidateMergeHeight: more heights than parents for Merge"
1518− subscriber :: forall a. k a -> Subscriber x a
1519− subscriber k = Subscriber
1520− { subscriberPropagate = \a -> do
1521− oldM <- liftIO $ readIORef accumRef
1522− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1523− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1524− liftIO $ writeIORef accumRef $! newM
1525− when (DMap.null oldM) $ do -- Only schedule the firing once
1526− height <- liftIO $ readIORef heightRef
1527− --TODO: assertions about height
1528− currentHeight <- getCurrentHeight
1529− when (height <= currentHeight) $ do
1530− if height /= invalidHeight
1531− then do
1532− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1533− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1534− else liftIO $ do
1535−#ifdef DEBUG_CYCLES
1536− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1537− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1538− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1539−#else
1540− let cycleInfo = ""
1541−#endif
1542− error $ "Causality loop found" <> cycleInfo
1543− scheduleSelf height
1544− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1545− modifyIORef' heightBagRef $ heightBagRemove old
1546− invalidateMyHeight
1547− , subscriberRecalculateHeight = \new -> do
1548− modifyIORef' heightBagRef $ heightBagAdd new
1549− revalidateMyHeight
1550− }
1551− subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1552− let s = subscriber k
1553− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1554− height <- liftIO $ getEventSubscribedHeight parentSubd
1555− return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1556− let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1557− heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1558− myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1559− myHeight = if invalidHeight `elem` heights
1560− then invalidHeight
1561− else succHeight $ heightBagMax myHeightBag
1562− currentHeight <- getCurrentHeight
1563− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1564− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1565− else (Nothing, dm)
1566− unless (DMap.null accum) $ do
1567− scheduleSelf myHeight
1568− occRef <- liftIO $ newIORef occ
1569− when (isJust occ) $ scheduleClear occRef
1570− liftIO $ writeIORef accumRef $! accum
1571− liftIO $ writeIORef heightRef $! myHeight
1572− liftIO $ writeIORef heightBagRef $! myHeightBag
1573− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1574− liftIO $ writeIORef parentsRef $! DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1575− let updateMe (R.PatchDMap p) = do
1576− oldParents <- liftIO $ readIORef parentsRef
1577− let f (subscriptionsToKill, ps) (k :=> R.ComposeMaybe me) = do
1578− (mOldSubd, newPs) <- case me of
1579− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1580− Just e -> do
1581− let s = subscriber k
1582− subscription@(EventSubscription _ subd) <- subscribe e s
1583− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1584− let newParent = MergeSubscribedParent subscription
1585− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1586− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1587− forM_ mOldSubd $ \oldSubd -> do
1588− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1589− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1590− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1591− (subscriptionsToKill, newParents) <- foldM f ([], oldParents) $ DMap.toList p --TODO: I think this runEventM is OK, since no events are firing at this time, but it might not be
1592− liftIO $ writeIORef parentsRef $! newParents
1593− return subscriptionsToKill
1594− defer $ SomeMergeInit $ do
1595− let s = Subscriber
1596− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1597− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1598− defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1599− , subscriberInvalidateHeight = \_ -> return ()
1600− , subscriberRecalculateHeight = \_ -> return ()
1601− }
1602− (EventSubscription _ changeSubd, change) <- subscribeAndRead (dynamicUpdated d) s
1603− forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1604− liftIO $ writeIORef changeSubdRef (s, changeSubd)
1605− let unsubscribeAll = do
1606− parents <- readIORef parentsRef
1607− forM_ (DMap.toList parents) $ \(_ :=> MergeSubscribedParent s) -> unsubscribe s
1608− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1609− , occ
1610− )
1611−
1612−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1613−
1614−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
1615−fan e =
1616− let f = Fan
1617− { fanParent = e
1618− , fanSubscribed = unsafeNewIORef e Nothing
1619− }
1620− in EventSelector $ \k -> eventFan k f
1621−
1622−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1623−runHoldInits holdInitRef mergeInitRef = do
1624− holdInits <- liftIO $ readIORef holdInitRef
1625− mergeInits <- liftIO $ readIORef mergeInitRef
1626− unless (null holdInits && null mergeInits) $ do
1627− liftIO $ writeIORef holdInitRef []
1628− liftIO $ writeIORef mergeInitRef []
1629− mapM_ initHold holdInits
1630− mapM_ unSomeMergeInit mergeInits
1631− runHoldInits holdInitRef mergeInitRef
1632−
1633−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
1634−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1635−
1636−newEventEnv :: IO (EventEnv x)
1637−newEventEnv = do
1638− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1639− holdInitRef <- newIORef []
1640− mergeUpdateRef <- newIORef []
1641− mergeInitRef <- newIORef []
1642− heightRef <- newIORef zeroHeight
1643− toClearRef <- newIORef []
1644− toClearRootRef <- newIORef []
1645− coincidenceInfosRef <- newIORef []
1646− delayedRef <- newIORef IntMap.empty
1647− return $ EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1648−
1649−clearEventEnv :: EventEnv x -> IO ()
1650−clearEventEnv (EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
1651− writeIORef toAssignRef []
1652− writeIORef holdInitRef []
1653− writeIORef mergeUpdateRef []
1654− writeIORef mergeInitRef []
1655− writeIORef heightRef zeroHeight
1656− writeIORef toClearRef []
1657− writeIORef toClearRootRef []
1658− writeIORef coincidenceInfosRef []
1659− writeIORef delayedRef IntMap.empty
1660−
1661−-- | Run an event action outside of a frame
1662−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1663−runFrame a = SpiderHost $ ask >>= \spiderTimeline -> lift $ do
1664− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimeline x)
1665− let go = do
1666− result <- a
1667− runHoldInits (eventEnvHoldInits 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
1668− return result
1669− result <- runEventM go
1670− toClear <- readIORef $ eventEnvClears env
1671− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1672− toClearRoot <- readIORef $ eventEnvRootClears env
1673− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1674− toAssign <- readIORef $ eventEnvAssignments env
1675− toReconnectRef <- newIORef []
1676− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
1677− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1678− writeIORef vRef v
1679− when debugInvalidate $ putStrLn $ "Invalidating Hold"
1680− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1681− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
1682− writeIORef (eventEnvMergeUpdates env) []
1683− when debugPropagate $ putStrLn "Updating merges"
1684− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1685− when debugPropagate $ putStrLn "Updating merges done"
1686− toReconnect <- readIORef toReconnectRef
1687− clearEventEnv env
1688− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1689− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1690− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1691− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1692− finalize wi
1693− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1694− wi' <- mkWeakPtrWithDebug i "wi'"
1695− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1696− writeIORef (switchSubscribedBehaviorParents subscribed) []
1697− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
1698− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
1699− runEventM $ runHoldInits (eventEnvHoldInits 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
1700− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1701− sub <- newSubscriberSwitch subscribed
1702− subscription <- runReaderT (unSpiderHost (runFrame ({-# SCC "subscribeSwitch" #-} subscribe e sub))) spiderTimeline --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
1703− {-
1704− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1705− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1706− EventRoot _ -> "EventRoot"
1707− EventNever -> "EventNever"
1708− _ -> "something else"
1709− -}
1710− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1711− return oldSubscription
1712− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1713− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1714− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1715− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1716− parentHeight <- getEventSubscribedHeight subd'
1717− myHeight <- readIORef $ switchSubscribedHeight subscribed
1718− when (parentHeight /= myHeight) $ do
1719− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1720− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1721− 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
1722− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1723− unsubscribe subscription
1724− mapM_ invalidateCoincidenceHeight mcs
1725− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1726− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1727− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1728− height <- calculateSwitchHeight subscribed
1729− updateSwitchHeight height subscribed
1730− return result
1731−
1732−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1733−
1734−{-# INLINE zeroHeight #-}
1735−zeroHeight :: Height
1736−zeroHeight = Height 0
1737−
1738−{-# INLINE invalidHeight #-}
1739−invalidHeight :: Height
1740−invalidHeight = Height (-1000)
1741−
1742−#ifdef DEBUG_CYCLES
1743−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1744−{-# INLINE invalidHeightBeingTraversed #-}
1745−invalidHeightBeingTraversed :: Height
1746−invalidHeightBeingTraversed = Height (-1001)
1747−#endif
1748−
1749−{-# INLINE succHeight #-}
1750−succHeight :: Height -> Height
1751−succHeight h@(Height a) =
1752− if h == invalidHeight
1753− then invalidHeight
1754− else Height $ succ a
1755−
1756−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1757−invalidateCoincidenceHeight subscribed = do
1758− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1759− when (oldHeight /= invalidHeight) $ do
1760− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1761− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1762−
1763−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1764−updateSwitchHeight new subscribed = do
1765− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1766− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1767− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1768− writeIORef (switchSubscribedHeight subscribed) $! new
1769− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1770−
1771−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1772−recalculateCoincidenceHeight subscribed = do
1773− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1774− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1775− height <- calculateCoincidenceHeight subscribed
1776− when (height /= invalidHeight) $ do
1777− writeIORef (coincidenceSubscribedHeight subscribed) $! height
1778− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1779−
1780−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1781−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1782−
1783−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1784−calculateCoincidenceHeight subscribed = do
1785− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1786− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1787− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1788−
1789−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1790−
1791−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1792−invalidate toReconnectRef wis = do
1793− forM_ wis $ \wi -> do
1794− mi <- deRefWeak wi
1795− case mi of
1796− Nothing -> do
1797− traceInvalidate "invalidate Dead"
1798− return () --TODO: Should we clean this up here?
1799− Just i -> do
1800− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1801− case i of
1802− InvalidatorPull p -> do
1803− traceInvalidate $ "invalidate: Pull" <> showNodeId p
1804− mVal <- readIORef $ pullValue p
1805− forM_ mVal $ \val -> do
1806− writeIORef (pullValue p) Nothing
1807− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1808− InvalidatorSwitch subscribed -> do
1809− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1810− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1811− 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
1812−
1813−--------------------------------------------------------------------------------
1814−-- Reflex integration
1815−--------------------------------------------------------------------------------
1816−
1817−-- | The default, global Spider environment
1818−type Spider = SpiderTimeline Global
1819−
1820−-- | Designates the default, global Spider timeline
1821−data Global
1822−
1823−{-# NOINLINE globalSpiderTimeline #-}
1824−globalSpiderTimeline :: SpiderTimeline Global
1825−globalSpiderTimeline = unsafePerformIO unsafeNewSpiderTimeline
1826−
1827−-- | Stores all global data relevant to a particular Spider timeline; only one
1828−-- value should exist for each type @x@
1829−data SpiderTimeline x = SpiderTimeline
1830− { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
1831− , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
1832−#ifdef DEBUG
1833− , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
1834−#endif
1835− }
1836−type role SpiderTimeline nominal
1837−
1838−instance GEq SpiderTimeline where
1839− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
1840− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimeline can't have two different 'x' arguments
1841− else Nothing
1842−
1843−unsafeNewSpiderTimeline :: forall x. IO (SpiderTimeline x)
1844−unsafeNewSpiderTimeline = do
1845− lock <- newMVar ()
1846− env <- newEventEnv
1847−#ifdef DEBUG
1848− depthRef <- newIORef 0
1849−#endif
1850− return $ SpiderTimeline
1851− { _spiderTimeline_lock = lock
1852− , _spiderTimeline_eventEnv = env
1853−#ifdef DEBUG
1854− , _spiderTimeline_depth = depthRef
1855−#endif
1856− }
1857−
1858−-- | Create a new SpiderTimeline
1859−newSpiderTimeline :: IO (Some SpiderTimeline)
1860−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
1861−
1862−-- | Pass a new timeline to the given function.
1863−withSpiderTimeline :: (forall x. SpiderTimeline x -> IO r) -> IO r
1864−withSpiderTimeline k = unsafeNewSpiderTimeline >>= k
1865−
1866−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1867−
1868−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1869−
1870−instance HasSpiderTimeline x => Functor (R.Dynamic (SpiderTimeline x)) where
1871− fmap f = SpiderDynamic . newMapDyn f . unSpiderDynamic
1872−
1873−instance HasSpiderTimeline x => Applicative (R.Dynamic (SpiderTimeline x)) where
1874− pure = SpiderDynamic . dynamicConst
1875− SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ zipDynWith ($) a b
1876− _ *> b = b
1877− a <* _ = a
1878−
1879−instance HasSpiderTimeline x => Monad (R.Dynamic (SpiderTimeline x)) where
1880− {-# INLINE return #-}
1881− return = pure
1882− {-# INLINE (>>=) #-}
1883− x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
1884− {-# INLINE (>>) #-}
1885− _ >> y = y
1886− {-# INLINE fail #-}
1887− fail _ = error "Dynamic does not support 'fail'"
1888−
1889−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
1890− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
1891− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
1892− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
1893− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
1894− type PullM (SpiderTimeline x) = SpiderPullM x
1895− type PushM (SpiderTimeline x) = SpiderPushM x
1896− {-# INLINABLE never #-}
1897− never = SpiderEvent eventNever
1898− {-# INLINABLE constant #-}
1899− constant = SpiderBehavior . behaviorConst
1900− {-# INLINABLE push #-}
1901− push f = SpiderEvent . push (coerce f) . unSpiderEvent
1902− {-# INLINABLE pull #-}
1903− pull = SpiderBehavior . pull . coerce
1904− {-# INLINABLE merge #-}
1905− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
1906− {-# INLINABLE fan #-}
1907− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1908− {-# INLINABLE switch #-}
1909− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
1910− {-# INLINABLE coincidence #-}
1911− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
1912− {-# INLINABLE current #-}
1913− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
1914− {-# INLINABLE updated #-}
1915− updated = SpiderEvent . fmap runIdentity . dynamicUpdated . unSpiderDynamic
1916− {-# INLINABLE unsafeBuildDynamic #-}
1917− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
1918− {-# INLINABLE unsafeBuildIncremental #-}
1919− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
1920− {-# INLINABLE mergeIncremental #-}
1921− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (R.PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (R.PatchDMap k (Event x))) . unSpiderIncremental
1922− {-# INLINABLE currentIncremental #-}
1923− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
1924− {-# INLINABLE updatedIncremental #-}
1925− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
1926− {-# INLINABLE incrementalToDynamic #-}
1927− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
1928− c <- readBehaviorUntracked $ dynamicCurrent i
1929− return $ Identity <$> R.apply p c --TODO: Avoid the redundant 'apply'
1930− eventCoercion Coercion = Coercion
1931− behaviorCoercion Coercion = Coercion
1932− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
1933−
1934−instance HasSpiderTimeline x => R.MonadSample (SpiderTimeline x) (EventM x) where
1935− {-# INLINABLE sample #-}
1936− sample (SpiderBehavior b) = readBehaviorUntracked b
1937−
1938−instance HasSpiderTimeline x => R.MonadHold (SpiderTimeline x) (EventM x) where
1939− {-# INLINABLE hold #-}
1940− hold = holdSpiderEventM
1941− {-# INLINABLE holdDyn #-}
1942− holdDyn = holdDynSpiderEventM
1943− {-# INLINABLE holdIncremental #-}
1944− holdIncremental = holdIncrementalSpiderEventM
1945−
1946−holdSpiderEventM :: HasSpiderTimeline x => a -> R.Event (SpiderTimeline x) a -> EventM x (R.Behavior (SpiderTimeline x) a)
1947−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
1948−
1949−holdDynSpiderEventM :: HasSpiderTimeline x => a -> R.Event (SpiderTimeline x) a -> EventM x (R.Dynamic (SpiderTimeline x) a)
1950−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
1951−
1952−holdIncrementalSpiderEventM :: (HasSpiderTimeline x, R.Patch p) => R.PatchTarget p -> R.Event (SpiderTimeline x) p -> EventM x (R.Incremental (SpiderTimeline x) p)
1953−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
1954−
1955−instance HasSpiderTimeline x => R.MonadHold (SpiderTimeline x) (SpiderHost x) where
1956− {-# INLINABLE hold #-}
1957− hold v0 e = R.runHostFrame $ R.hold v0 e
1958− {-# INLINABLE holdDyn #-}
1959− holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
1960− {-# INLINABLE holdIncremental #-}
1961− holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
1962−
1963−instance HasSpiderTimeline x => R.MonadSample (SpiderTimeline x) (SpiderHost x) where
1964− {-# INLINABLE sample #-}
1965− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
1966−
1967−instance HasSpiderTimeline x => R.MonadSample (SpiderTimeline x) (SpiderPullM x) where
1968− {-# INLINABLE sample #-}
1969− sample = coerce . readBehaviorTracked . unSpiderBehavior
1970−
1971−instance HasSpiderTimeline x => R.MonadSample (SpiderTimeline x) (SpiderPushM x) where
1972− {-# INLINABLE sample #-}
1973− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
1974−
1975−instance HasSpiderTimeline x => R.MonadHold (SpiderTimeline x) (SpiderPushM x) where
1976− {-# INLINABLE hold #-}
1977− hold v0 e = R.current <$> R.holdDyn v0 e
1978− {-# INLINABLE holdDyn #-}
1979− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce e
1980− {-# INLINABLE holdIncremental #-}
1981− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> hold v0 e
1982−
1983−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
1984−
1985−data SpiderEventHandle x a = SpiderEventHandle
1986− { spiderEventHandleSubscription :: EventSubscription x
1987− , spiderEventHandleValue :: IORef (Maybe a)
1988− }
1989−
1990−instance HasSpiderTimeline x => R.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
1991− {-# INLINABLE subscribeEvent #-}
1992− subscribeEvent e = SpiderHostFrame $ do
1993− --TODO: Unsubscribe eventually (manually and/or with weak ref)
1994− val <- liftIO $ newIORef Nothing
1995− subscription <- subscribe (unSpiderEvent e) $ Subscriber
1996− { subscriberPropagate = \a -> do
1997− liftIO $ writeIORef val $ Just a
1998− scheduleClear val
1999− , subscriberInvalidateHeight = \_ -> return ()
2000− , subscriberRecalculateHeight = \_ -> return ()
2001− }
2002− return $ SpiderEventHandle
2003− { spiderEventHandleSubscription = subscription
2004− , spiderEventHandleValue = val
2005− }
2006−
2007−instance HasSpiderTimeline x => R.ReflexHost (SpiderTimeline x) where
2008− type EventTrigger (SpiderTimeline x) = RootTrigger x
2009− type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2010− type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2011−
2012−instance HasSpiderTimeline x => R.MonadReadEvent (SpiderTimeline x) (ReadPhase x) where
2013− {-# NOINLINE readEvent #-}
2014− readEvent h = ReadPhase $ fmap (fmap return) $ liftIO $ do
2015− result <- readIORef $ spiderEventHandleValue h
2016− touch h
2017− return result
2018−
2019−instance MonadRef (EventM x) where
2020− type Ref (EventM x) = Ref IO
2021− {-# INLINABLE newRef #-}
2022− {-# INLINABLE readRef #-}
2023− {-# INLINABLE writeRef #-}
2024− newRef = liftIO . newRef
2025− readRef = liftIO . readRef
2026− writeRef r a = liftIO $ writeRef r a
2027−
2028−instance MonadAtomicRef (EventM x) where
2029− {-# INLINABLE atomicModifyRef #-}
2030− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2031−
2032−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2033−newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimeline x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2034−
2035−instance Monad (SpiderHost x) where
2036− {-# INLINABLE (>>=) #-}
2037− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2038− {-# INLINABLE (>>) #-}
2039− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2040− {-# INLINABLE return #-}
2041− return x = SpiderHost $ return x
2042− {-# INLINABLE fail #-}
2043− fail s = SpiderHost $ fail s
2044−
2045−-- | Run an action affecting the global Spider timeline; this will be guarded by
2046−-- a mutex for that timeline
2047−runSpiderHost :: SpiderHost Global a -> IO a
2048−runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimeline
2049−
2050−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2051−-- mutex for that timeline
2052−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimeline x -> IO a
2053−runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2054−
2055−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2056−
2057−instance Monad (SpiderHostFrame x) where
2058− {-# INLINABLE (>>=) #-}
2059− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2060− {-# INLINABLE (>>) #-}
2061− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2062− {-# INLINABLE return #-}
2063− return x = SpiderHostFrame $ return x
2064− {-# INLINABLE fail #-}
2065− fail s = SpiderHostFrame $ fail s
2066−
2067−instance HasSpiderTimeline x => R.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2068− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2069−
2070−instance HasSpiderTimeline x => R.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2071− {-# INLINABLE hold #-}
2072− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2073− {-# INLINABLE holdDyn #-}
2074− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2075− {-# INLINABLE holdIncremental #-}
2076− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
2077−
2078−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2079−newEventWithTriggerIO f = do
2080− es <- newFanEventWithTriggerIO $ \Refl -> f
2081− return $ select es Refl
2082−
2083−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2084−newFanEventWithTriggerIO f = do
2085− occRef <- newIORef DMap.empty
2086− subscribedRef <- newIORef DMap.empty
2087− let !r = Root
2088− { rootOccurrence = occRef
2089− , rootSubscribed = subscribedRef
2090− , rootInit = f
2091− }
2092− return $ EventSelector $ \k -> eventRoot k r
2093−
2094−instance R.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2095− newEventWithTrigger = SpiderHost . lift . fmap SpiderEvent . newEventWithTriggerIO
2096− newFanEventWithTrigger f = SpiderHost $ lift $ do
2097− es <- newFanEventWithTriggerIO f
2098− return $ R.EventSelector $ SpiderEvent . select es
2099−
2100−instance R.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2101− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2102− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2103− es <- newFanEventWithTriggerIO f
2104− return $ R.EventSelector $ SpiderEvent . select es
2105−
2106−instance HasSpiderTimeline x => R.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2107− {-# INLINABLE subscribeEvent #-}
2108− subscribeEvent = runFrame . runSpiderHostFrame . R.subscribeEvent
2109−
2110−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2111−
2112−instance HasSpiderTimeline x => R.MonadSample (SpiderTimeline x) (ReadPhase x) where
2113− {-# INLINABLE sample #-}
2114− sample = ReadPhase . R.sample
2115−
2116−instance HasSpiderTimeline x => R.MonadHold (SpiderTimeline x) (ReadPhase x) where
2117− {-# INLINABLE hold #-}
2118− hold v0 e = ReadPhase $ R.hold v0 e
2119− {-# INLINABLE holdDyn #-}
2120− holdDyn v0 e = ReadPhase $ R.holdDyn v0 e
2121− {-# INLINABLE holdIncremental #-}
2122− holdIncremental v0 e = ReadPhase $ R.holdIncremental v0 e
2123−
2124−instance HasSpiderTimeline x => R.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2125− type ReadPhase (SpiderHost x) = ReadPhase x
2126− fireEventsAndRead es (ReadPhase a) = run es a
2127− runHostFrame = runFrame . runSpiderHostFrame
2128−
2129−instance MonadRef (SpiderHost x) where
2130− type Ref (SpiderHost x) = Ref IO
2131− newRef = SpiderHost . newRef
2132− readRef = SpiderHost . readRef
2133− writeRef r = SpiderHost . writeRef r
2134−
2135−instance MonadAtomicRef (SpiderHost x) where
2136− atomicModifyRef r = SpiderHost . atomicModifyRef r
2137−
2138−instance MonadRef (SpiderHostFrame x) where
2139− type Ref (SpiderHostFrame x) = Ref IO
2140− newRef = SpiderHostFrame . newRef
2141− readRef = SpiderHostFrame . readRef
2142− writeRef r = SpiderHostFrame . writeRef r
2143−
2144−instance MonadAtomicRef (SpiderHostFrame x) where
2145− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2146−
2147−instance PrimMonad (SpiderHostFrame x) where
2148− type PrimState (SpiderHostFrame x) = PrimState IO
2149− primitive = SpiderHostFrame . EventM . primitive
2150−
2151−--------------------------------------------------------------------------------
2152−-- Deprecated items
2153−--------------------------------------------------------------------------------
2154−
2155−{-# DEPRECATED SpiderEnv "Use 'SpiderTimeline' instead" #-}
2156−type SpiderEnv = SpiderTimeline
stylizenew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+
4+for x in **/*.hs ; do stylish-haskell -i "$x" ; done
test/Reflex/Bench/Focused.hsdeleted−369
@@ -1,369 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE RecursiveDo #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeSynonymInstances #-}
11−
12−module Reflex.Bench.Focused where
13−
14−import Reflex
15−import Reflex.TestPlan
16−
17−import Control.Applicative
18−import Control.Monad
19−import Control.Monad.Fix
20−import Control.Monad.Identity
21−import Data.Traversable (for, traverse)
22−
23−import qualified Data.Dependent.Map as DMap
24−import Data.Map (Map)
25−import qualified Data.Map as Map
26−import Data.Maybe
27−
28−import Data.Functor.Misc
29−
30−import Data.List
31−import Data.List.Split
32−import Data.Tuple
33−
34−import Data.Monoid
35−import Data.Word
36−
37−import Control.DeepSeq
38−
39−import Prelude hiding (concat, sum)
40−
41−
42−mergeTree :: Num a => (Monoid (f [a]), Functor f) => Int -> [f a] -> f a
43−mergeTree n es | length es <= n = sum' es
44− | otherwise = mergeTree n subTrees
45− where
46− merges = chunksOf n es
47− subTrees = map sum' merges
48− sum' = fmap sum . mconcat . fmap (fmap (:[]) )
49−
50−mergeListDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
51−mergeListDyn = mconcat . fmap (fmap pure)
52−
53−mergeTreeDyn :: (Num a, Reflex t) => Int -> [Dynamic t a] -> Dynamic t a
54−mergeTreeDyn n dyns | length dyns <= n = sumDyns dyns
55− | otherwise = mergeTreeDyn n $ fmap sumDyns merges
56− where
57− merges = chunksOf n dyns
58− sumDyns = fmap sum . mergeListDyn
59−
60−
61−
62−-- N events all firing for N frames
63−continuous :: TestPlan t m => Word -> Word -> m [Event t Word]
64−continuous n frames = for [1..n] $ \i -> plan $ (, i) <$> [1..frames]
65−
66−-- Fire N events once every P frames for total N frames (interspersed evenly)
67−occasional :: TestPlan t m => Word -> Word -> Word -> m [Event t Word]
68−occasional n period frames = traverse plan $ zipWith occs [1..] phases
69− where
70− phases = take (fromIntegral n) $ concat (repeat [1..period])
71− occs i phase = (, i) <$> [1, phase+1..frames]
72−
73−
74−
75−-- Event which never fires (but isn't 'never')
76−never' :: TestPlan t m => m (Event t Word)
77−never' = plan []
78−
79−
80−-- Event which fires once on first frame
81−event :: TestPlan t m => m (Event t Word)
82−event = plan [(1, 0)]
83−
84−-- Event which fires constantly over N frames
85−events :: TestPlan t m => Word -> m (Event t Word)
86−events n = plan $ (\i -> (i, i)) <$> [1..n]
87−
88−
89−-- N events all originating from one event
90−fmapFan :: Reflex t => Word -> Event t Word -> [Event t Word]
91−fmapFan n e = (\i -> (+i) <$> e) <$> [1..n]
92−
93−
94−-- Make a fan using the value in the event converting it to a singleton Map
95−-- use a fan of size n (key is the value mod n)
96−fanMerge :: Reflex t => Word -> Event t Word -> Event t Word
97−fanMerge n e = leftmost $ s <$> [0..n - 1] where
98− s k = select f (Const2 k)
99− f = fan (toMap <$> e)
100− toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k)
101−
102−-- Dumb version of the above using simple fmapMaybe to filter
103−fmapFanMerge :: Reflex t => Word -> Event t Word -> Event t Word
104−fmapFanMerge n e = leftmost $ s <$> [0..n - 1] where
105− s k = flip fmapMaybe e $ \j -> if k == j `mod` n
106− then Just k
107− else Nothing
108−
109−
110−
111−-- Create an Event with a Map which is dense to size N
112−denseMap :: TestPlan t m => Word -> m (Event t (Map Word Word))
113−denseMap n = plan [(1, m)] where
114− m = Map.fromList $ zip [1..n] [1..n]
115−
116−iter :: (a -> a) -> Word -> a -> a
117−iter _ 0 a = a
118−iter f n a = iter f (n - 1) (f a)
119−
120−iterM :: Monad m => (a -> m a) -> Word -> a -> m a
121−iterM _ 0 a = return a
122−iterM f n a = iterM f (n - 1) =<< f a
123−
124−fmapChain :: (Functor f) => Word -> f Word -> f Word
125−fmapChain = iter (fmap (+1))
126−
127−mapDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
128−mapDynChain = iterM (return . fmap (+1))
129−
130−joinDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
131−joinDynChain = iterM (\d -> return $ join $ fmap (const d) d)
132−
133−combineDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
134−combineDynChain = iterM (\d -> return $ zipDynWith (+) d d)
135−
136−pingPong :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> Event t a -> m (Event t a)
137−pingPong e1 e2 = do
138− rec
139− d <- foldDyn (const swap) (e1, e2) e
140− let e = switch (fst <$> current d)
141− return e
142−
143−switchFactors :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
144−switchFactors 0 e = return e
145−switchFactors i e = do
146− b <- hold ((+1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)
147− switchFactors (i - 1) (switch b)
148−
149−
150−switchChain :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
151−switchChain = iterM (\e -> pingPong e ((+1) <$> e))
152−
153−
154−switchChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
155−switchChain2 = iterM (\e -> pingPong e ((+1) <$> leftmost [e, e]))
156−
157−switchPromptlyChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
158−switchPromptlyChain = iterM $ \e ->
159− switchPromptlyDyn <$> holdDyn e (e <$ e)
160−
161−
162−coinChain :: Reflex t => Word -> Event t Word -> Event t Word
163−coinChain = iter $ \e -> coincidence (e <$ e)
164−
165−fanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
166−fanMergeChain width = iter $ fanMerge width
167−
168−fmapFanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
169−fmapFanMergeChain width = iter $ fmapFanMerge width
170−
171−-- | Data type for a collection (a map) which is updated by providing differences
172−data UpdatedMap t k a = UpdatedMap (Map k a) (Event t (Map k (Maybe a)))
173−
174−-- This will hopefully become a primitive (faster!)
175−switchMergeEvents :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
176−switchMergeEvents mapChanges = switch . fmap mergeMap <$> holdMap mapChanges
177−
178−-- switchMergeMaybe :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
179−-- switchMergeMaybe (UpdatedMap initial changes) = switchMergeMap initial (fmap (fromMaybe never) <$> changes)
180−
181−switchMergeBehaviors :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Behavior t a) -> m (Behavior t (Map k a))
182−switchMergeBehaviors mapChanges = pull . joinMap <$> holdMap mapChanges
183− where joinMap m = traverse sample =<< sample m
184−
185−-- | Turn an UpdatedMap into a Dynamic by applying the differences to the initial value
186−holdMapDyn :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Dynamic t (Map k a))
187−holdMapDyn (UpdatedMap initial changes) = foldDyn (flip (Map.foldWithKey modify)) initial changes
188−
189− where
190− modify k Nothing items = Map.delete k items
191− modify k (Just item) items = Map.insert k item items
192−
193−
194−-- | Hold an UpdatedMap as a behavior by applying differences to the initial value
195−holdMap :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Behavior t (Map k a))
196−holdMap = (current <$>) . holdMapDyn
197−
198−
199−increasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a)
200−increasingMerge xs = do
201− e <- planList (zipWith Map.singleton [1..] (Just <$> xs) ++ [reset])
202− return (UpdatedMap Map.empty e)
203− where
204− reset = Map.fromList $ zip [1..] (const Nothing <$> xs)
205−
206−decreasingMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
207−decreasingMerge xs = do
208− e <- planList (zipWith Map.singleton [1..] (const Nothing <$> xs) ++ [reset])
209− return (UpdatedMap initial e)
210− where
211− initial = Map.fromList $ zip [1..] xs
212− reset = Just <$> initial
213−
214−modifyMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
215−modifyMerge xs = do
216− e <- planList $ zipWith Map.singleton [1..] (Just <$> xs)
217− return (UpdatedMap initial e)
218− where
219− initial = Map.fromList $ zip [1..] xs
220−
221−
222−countMany :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Behavior t Int]
223−countMany = traverse (fmap current . count)
224−
225−countManyDyn :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Dynamic t Int]
226−countManyDyn = traverse count
227−
228−
229−-- Given a function which creates a sub-network (from a single event)
230−-- Create a plan which uses a switch to substitute it
231−switches :: TestPlan t m => Word -> (forall n. (MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> m (Event t a)
232−switches numFrames f = do
233− es <- events numFrames
234− switch <$> hold never (makeEvents es)
235−
236− where
237− makeEvents es = pushAlways (\n -> f (fmap (+n) es)) es
238−
239−
240−
241−-- Two sets of benchmarks, one which we're interested in testing subscribe time (as well as time to fire frames)
242−-- the other, which we're only interested in time for running frames
243−subscribing :: Word -> Word -> [(String, TestCase)]
244−subscribing n frames =
245− [ testSub "fmapFanMerge" $ return . mergeList . fmapFan n
246− , testSub "fanMerge" $ return . fanMerge n
247− , testSub "fmapFan/mergeTree" $ return . mergeTree 8 . fmapFan n
248− , testSub "fmapChain" $ return . fmapChain n
249− , testSub "switchChain" $ switchChain n
250− , testSub "switchPromptlyChain" $ switchPromptlyChain n
251− , testSub "switchFactors" $ switchFactors n
252− , testSub "coincidenceChain" $ return . coinChain n
253− ]
254−
255− where
256− testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)
257− testSub name test = testE name (switches frames test)
258−
259−-- Set of benchmark to test specifically merging dynamic collections
260−-- a pattern which occurs frequently in reflex-dom collections
261−merging :: Word -> [(String, TestCase)]
262−merging n =
263− [ testE "static events" $ mergeList <$> sparse
264− , testE "increasing events" $ switchMergeEvents =<< increasingMerge =<< sparse
265− , testE "decreasing events" $ switchMergeEvents =<< decreasingMerge =<< sparse
266− , testE "modify events" $ switchMergeEvents =<< modifyMerge =<< sparse
267−
268− , testB "static behaviors" $ pull . traverse sample <$> counters
269− , testB "increasing behaviors" $ switchMergeBehaviors =<< increasingMerge =<< counters
270− , testB "decreasing behaviors" $ switchMergeBehaviors =<< decreasingMerge =<< counters
271− , testB "modify behaviors" $ switchMergeBehaviors =<< modifyMerge =<< counters
272−
273−
274− -- , testE "increasing events/switchMerge" $ switchMergeMaybe =<< increasingMerge =<< sparse
275− -- , testE "decreasing events/switchMerge" $ switchMergeMaybe =<< decreasingMerge =<< sparse
276− -- , testE "modify events/switchMerge" $ switchMergeMaybe =<< modifyMerge =<< sparse
277− ]
278−
279− where
280− sparse :: TestPlan t m => m [Event t Word]
281− sparse = fmap (fmap (+1)) <$> occasional n 8 n
282−
283− counters :: TestPlan t m => m [Behavior t Int]
284− counters = countMany =<< sparse
285−
286−
287−
288−fans :: Word -> [(String, TestCase)]
289−fans n =
290− [ testE "fanMapChain" $ fanMergeChain n 10 <$> e
291− , testE "fmapFanMapChain" $ fmapFanMergeChain n 10 <$> e
292−
293− , testE "fanMerge " $ fanMerge n <$> events n
294−
295− , testE "fmapFanMerge " $ fmapFanMerge n <$> events n
296− , testE "triggerMerge" $ leftmost <$> for [1..n] (\i -> plan [(i, i)])
297−
298− ]
299− where
300−
301− e :: TestPlan t m => m (Event t Word)
302− e = events 100
303−
304−
305−
306−
307−dynamics :: Word -> [(String, TestCase)]
308−dynamics n =
309− [ testE "mapDynChain" $ fmap updated $ mapDynChain n =<< d
310− , testE "joinDynChain" $ fmap updated $ joinDynChain n =<< d
311− , testE "combineDynChain" $ fmap updated $ combineDynChain n =<< d
312− , testE "dense mergeTree" $ fmap (updated . mergeTreeDyn 8) dense
313− , testE "sparse mergeTree" $ fmap (updated . mergeTreeDyn 8) sparse
314− , testE "mergeDyn" $ fmap (updated . fmap sum . mergeListDyn) sparse
315− ] where
316−
317− d :: TestPlan t m => m (Dynamic t Word)
318− d = count =<< events 10
319−
320− sparse, dense :: TestPlan t m => m [Dynamic t Int]
321− sparse = countManyDyn =<< occasional n 8 16
322− dense = countManyDyn =<< continuous n 2
323−
324−
325−firing :: Word -> [(String, TestCase)]
326−firing n =
327− [ testE "fmapChain" $ fmapChain n <$> e
328− , testE "switchChain2" $ switchChain2 n =<< e
329− , testE "switchPromptlyChain" $ switchPromptlyChain n =<< e
330− , testE "switchFactors" $ switchFactors n =<< e
331− , testE "coincidenceChain" $ coinChain n <$> e
332−
333− , testE "dense mergeTree" $ mergeTree 8 <$> dense
334− , testE "sparse mergeTree" $ mergeTree 8 <$> sparse
335−
336− -- Triggers test failure in Spider
337− --, testE "runFrame" $ events n
338−
339− , testB "sum counters" $ do
340− counts <- counters
341− return $ pull $ sum <$> traverse sample counts
342−
343− , testB "pullChain" $ fmapChain n . current <$> (count =<< events 4)
344− , testB "pullChain2" $ do
345− es <- events 4
346− e' <- plan [(0, ())]
347−
348− b <- hold (constant 0) $
349− pushAlways (const $ fmapChain n <$> hold 0 es) e'
350−
351− return (join b)
352− , testB "counters/pullTree" $ mergeTree 8 <$> counters
353−
354− ]
355− where
356− e :: TestPlan t m => m (Event t Word)
357− e = events 10
358−
359− dense, sparse :: TestPlan t m => m [Event t Word]
360− dense = continuous n 2
361− sparse = occasional n 8 16
362−
363− counters :: TestPlan t m => m [Behavior t Int]
364− counters = countMany =<< sparse
365−
366−
367−
368−
369−
test/Reflex/Plan/Pure.hsdeleted−70
@@ -1,70 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−
9−module Reflex.Plan.Pure where
10−
11−import Reflex
12−import Reflex.Pure
13−import Reflex.TestPlan
14−
15−import Control.Applicative
16−import Control.Monad.Fix
17−import Control.Monad.State
18−import Data.IntMap (IntMap)
19−import qualified Data.IntMap as IntMap
20−import Data.IntSet (IntSet)
21−import qualified Data.IntSet as IntSet
22−
23−import Data.Bifunctor
24−import Data.Maybe
25−import Data.Monoid
26−import Prelude
27−
28−
29−mapToPureEvent :: IntMap a -> Event (Pure Int) a
30−mapToPureEvent m = Event $ flip IntMap.lookup m
31−
32−type TimeM = (->) Int
33−newtype PurePlan a = PurePlan { unPlan :: StateT IntSet TimeM a } deriving (Functor, Applicative, Monad, MonadFix)
34−
35−liftPlan :: TimeM a -> PurePlan a
36−liftPlan = PurePlan . lift
37−
38−instance MonadHold (Pure Int) PurePlan where
39− hold initial = liftPlan . hold initial
40− holdDyn initial = liftPlan . holdDyn initial
41− holdIncremental initial = liftPlan . holdIncremental initial
42−
43−instance MonadSample (Pure Int) PurePlan where
44− sample = liftPlan . sample
45−
46−
47−instance TestPlan (Pure Int) PurePlan where
48− plan occs = do
49− PurePlan . modify $ IntSet.union (IntMap.keysSet m)
50− return $ mapToPureEvent m
51− where m = IntMap.fromList (first fromIntegral <$> occs)
52−
53−runPure :: PurePlan a -> (a, IntSet)
54−runPure (PurePlan p) = runStateT p mempty $ 0
55−
56−relavantTimes :: IntSet -> IntSet
57−relavantTimes occs = IntSet.fromList [0..l + 1]
58− where l = fromMaybe 0 (fst <$> IntSet.maxView occs)
59−
60−testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a
61−testBehavior (b, occs) = IntMap.fromSet (sample b) (relavantTimes occs)
62−
63−testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a)
64−testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relavantTimes occs)
65−
66−
67−
68−
69−
70−
test/Reflex/Plan/Reflex.hsdeleted−135
@@ -1,135 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE StandaloneDeriving #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−module Reflex.Plan.Reflex
12− ( TestPlan(..)
13− , runPlan
14− , Plan (..)
15− , Schedule
16− , Firing (..)
17− , MonadIORef
18−
19−
20− , readSchedule
21− , readSchedule_
22− , testSchedule
23− , readEvent'
24− , makeDense
25−
26− , runTestE
27− , runTestB
28−
29− ) where
30−
31−import Reflex.Class
32−import Reflex.Host.Class
33−import Reflex.TestPlan
34−
35−import Control.Applicative
36−import Control.Monad
37−import Control.Monad.Identity
38−import Control.Monad.State.Strict
39−
40−import Control.Monad.Ref
41−import Data.Dependent.Sum (DSum (..))
42−import qualified Data.IntMap.Strict as IntMap
43−import Data.Maybe
44−import Data.Monoid
45−import Data.Traversable (sequenceA, traverse)
46−
47−import Control.DeepSeq
48−import Control.Exception
49−import Data.IntMap.Strict (IntMap)
50−import Data.IORef
51−import System.Mem
52−
53−-- Note: this import must come last to silence warnings from AMP
54−import Prelude
55−
56−type MonadIORef m = (MonadIO m, MonadRef m, Ref m ~ Ref IO)
57−
58−data Firing t where
59− Firing :: IORef (Maybe (EventTrigger t a)) -> a -> Firing t
60−
61−
62−type Schedule t = IntMap [Firing t]
63−
64−-- Implementation of a TestPlan in terms of ReflexHost
65−newtype Plan t a = Plan (StateT (Schedule t) (HostFrame t) a)
66−
67−deriving instance ReflexHost t => Functor (Plan t)
68−deriving instance ReflexHost t => Applicative (Plan t)
69−deriving instance ReflexHost t => Monad (Plan t)
70−
71−deriving instance ReflexHost t => MonadSample t (Plan t)
72−deriving instance ReflexHost t => MonadHold t (Plan t)
73−deriving instance ReflexHost t => MonadFix (Plan t)
74−
75−
76−instance (ReflexHost t, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => TestPlan t (Plan t) where
77− plan occurances = 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 <$> occurances)
84− makeFiring ref (t, a) = (fromIntegral t, [Firing ref a])
85−
86−
87−firingTrigger :: (MonadReflexHost t m, MonadIORef m) => Firing t -> m (Maybe (DSum (EventTrigger t) Identity))
88−firingTrigger (Firing ref a) = fmap (:=> Identity a) <$> readRef ref
89−
90−runPlan :: (MonadReflexHost t m) => Plan t a -> m (a, Schedule t)
91−runPlan (Plan p) = runHostFrame $ runStateT p mempty
92−
93−
94−makeDense :: Schedule t -> Schedule t
95−makeDense s = fromMaybe (emptyRange 0) $ do
96− (end, _) <- fst <$> IntMap.maxViewWithKey s
97− return $ IntMap.union s (emptyRange end)
98− where
99− emptyRange end = IntMap.fromList (zip [0..end + 1] (repeat []))
100−
101−
102−-- For the purposes of testing, we add in a zero frame and extend one frame (to observe changes to behaviors
103−-- after the last event)
104−-- performGC is called at each frame to test for GC issues
105−testSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
106−testSchedule schedule readResult = IntMap.traverseWithKey (\t occs -> liftIO performGC *> triggerFrame readResult t occs) (makeDense schedule)
107−
108−readSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
109−readSchedule schedule readResult = IntMap.traverseWithKey (triggerFrame readResult) schedule
110−
111−readSchedule_ :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m ()
112−readSchedule_ schedule readResult = mapM_ (uncurry $ triggerFrame readResult) $ IntMap.toList schedule
113−
114−triggerFrame :: (MonadReflexHost t m, MonadIORef m, NFData a) => ReadPhase m a -> Int -> [Firing t] -> m a
115−triggerFrame readResult _ occs = do
116− triggers <- catMaybes <$> traverse firingTrigger occs
117− liftIO . evaluate . force =<< fireEventsAndRead triggers readResult
118−
119−readEvent' :: MonadReadEvent t m => EventHandle t a -> m (Maybe a)
120−readEvent' = readEvent >=> sequenceA
121−
122−
123−-- Convenience functions for running tests producing Events/Behaviors
124−runTestB :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Behavior t a) -> m (IntMap a)
125−runTestB p = do
126− (b, s) <- runPlan p
127− testSchedule s $ sample b
128−
129−runTestE :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Event t a) -> m (IntMap (Maybe a))
130−runTestE p = do
131− (e, s) <- runPlan p
132− h <- subscribeEvent e
133− testSchedule s (readEvent' h)
134−
135−
test/Reflex/Test.hsdeleted−66
@@ -1,66 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−
8−module Reflex.Test
9− ( testAgreement
10− , compareResult
11− , runTests
12−
13− , module Reflex.TestPlan
14−
15− ) where
16−
17−import Reflex.Spider
18−
19−import Reflex.TestPlan
20−
21−import Reflex.Plan.Pure
22−import Reflex.Plan.Reflex
23−
24−import Control.Monad
25−import Data.Monoid
26−
27−import Data.IntMap (IntMap)
28−
29−--import Data.Foldable
30−import System.Exit
31−
32−import Prelude
33−
34−
35−testAgreement :: TestCase -> IO Bool
36−testAgreement (TestE p) = do
37− spider <- runSpiderHost $ runTestE p
38− let results = [("spider", spider)]
39−
40− compareResult results (testEvent $ runPure p)
41−
42−testAgreement (TestB p) = do
43− spider <- runSpiderHost $ runTestB p
44− let results = [("spider", spider)]
45−
46− compareResult results (testBehavior $ runPure p)
47−
48−
49−compareResult :: (Show a, Eq a) => [(String, IntMap a)] -> IntMap a -> IO Bool
50−compareResult results expected = fmap and $ forM results $ \(name, r) -> do
51−
52− when (r /= expected) $ do
53− putStrLn ("Got: " ++ show (name, r))
54− putStrLn ("Expected: " ++ show expected)
55− return (r == expected)
56−
57−
58−runTests :: [(String, TestCase)] -> IO ()
59−runTests testCases = do
60− results <- forM testCases $ \(name, test) -> do
61− putStrLn $ "Test: " <> name
62− testAgreement test
63− exitWith $ if and results
64− then ExitSuccess
65− else ExitFailure 1
66−
test/Reflex/Test/CrossImpl.hsdeleted−244
@@ -1,244 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE LambdaCase #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE NoMonomorphismRestriction #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−module Reflex.Test.CrossImpl (test) where
16−
17−import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_)
18−
19−import Control.Monad.Ref
20−import Reflex.Class
21−import Reflex.Dynamic
22−import Reflex.Host.Class
23−import qualified Reflex.Pure as P
24−import qualified Reflex.Spider.Internal as S
25−
26−import Control.Arrow (second, (&&&))
27−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
28−import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
29−import Control.Monad.Writer hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
30−import Data.Dependent.Map (DSum (..))
31−import Data.Foldable
32−import Data.Map.Strict (Map)
33−import qualified Data.Map.Strict as Map
34−import qualified Data.Set as Set
35−import Data.Traversable
36−import System.Exit
37−import System.Mem
38−
39−import System.IO.Unsafe
40−
41−mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a
42−mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of
43− Nothing -> error $ "mapToPureBehavior: no value for time " <> show t
44− Just (_, v) -> v
45−
46−mapToPureEvent :: Map Int a -> Event PureReflexDomain a
47−mapToPureEvent m = P.Event $ flip Map.lookup m
48−
49−relevantTestingTimes :: (Map Int a, Map Int b) -> [Int]
50−relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of
51− (Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event
52− _ -> [] -- Doesn't actually make much sense
53−
54−type PureReflexDomain = P.Pure Int
55−type TimeM = (->) Int
56−
57−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)
58−testPure builder (b, e) =
59− let (P.Behavior b', P.Event e') = ($ 0) $ builder (mapToPureBehavior b, mapToPureEvent e)
60− relevantTimes = relevantTestingTimes (b, e)
61− e'' = Map.mapMaybe id $ Map.fromList $ map (id &&& e') relevantTimes
62− b'' = Map.fromList $ map (id &&& b') relevantTimes
63− in (b'', e'')
64−
65−class MapMSignals a a' t t' | a -> t, a' -> t', a t' -> a', a' t -> a where
66− mapMSignals :: Monad m => (forall b. Behavior t b -> m (Behavior t' b)) -> (forall b. Event t b -> m (Event t' b)) -> a -> m a'
67−
68−instance MapMSignals (Behavior t a) (Behavior t' a) t t' where
69− mapMSignals fb _ = fb
70−
71−instance MapMSignals (Event t a) (Event t' a) t t' where
72− mapMSignals _ fe = fe
73−
74−instance (MapMSignals a a' t t', MapMSignals b b' t t') => MapMSignals (a, b) (a', b') t t' where
75− mapMSignals fb fe (a, b) = liftM2 (,) (mapMSignals fb fe a) (mapMSignals fb fe b)
76−
77−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)
78−testSpider builder (bMap, eMap) = unsafePerformIO $ S.runSpiderHost $ do
79− (re, reTrigger) <- newEventWithTriggerRef
80− (rb, rbTrigger) <- newEventWithTriggerRef
81− b <- runHostFrame $ hold (error "testSpider: No value for input behavior yet") rb
82− (b', e') <- runHostFrame $ builder (b, re)
83− e'Handle <- subscribeEvent e' --TODO: This should be unnecessary
84− let times = relevantTestingTimes (bMap, eMap)
85− liftIO performGC
86− outputs <- forM times $ \t -> do
87− forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger
88− bOutput <- sample b'
89− eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do
90− mret <- readRef reTrigger
91− let firing = case mret of
92− Just ret -> [ret :=> Identity val]
93− Nothing -> []
94− fireEventsAndRead firing $ sequence =<< readEvent e'Handle
95− liftIO performGC
96− return (t, (bOutput, eOutput))
97− return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)
98−
99−tracePerf :: Show a => a -> b -> b
100−tracePerf = flip const
101−
102−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
103−testAgreement builder inputs = do
104− let identityResult = testPure builder inputs
105− tracePerf "---------" $ return ()
106− let spiderResult = testSpider builder inputs
107− tracePerf "---------" $ return ()
108− let resultsAgree = identityResult == spiderResult
109− if resultsAgree
110− then do putStrLn "Success:"
111− print identityResult
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− , (,) "onceE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
131− e' <- onceE $ 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− , (,) "switchPromptly-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'' <- switchPromptly never e'
157− return (b, e'')
158− , (,) "switchPromptly-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'' <- switchPromptly never $ leftmost [e', e']
161− return (b, e'')
162− , (,) "switchPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
163− let e' = leftmost [e, e]
164− e'' <- switchPromptly never (fmap (const e) e')
165− return (b, e'')
166− , (,) "switchPromptly-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'' <- switchPromptly 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− , (,) "switchPromptly-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 <$> onceE e
177− e'' <- switchPromptly never e'
178− return (b, e'')
179− , (,) "switchPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
180− let e' = flip pushAlways e $ \_ -> do
181− switchPromptly e never
182− e'' <- switchPromptly 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 $ \_ -> onceE 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 <- onceE 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) =<< onceE e
224− eOuter <- pushAlways sample . fmap (const bb) <$> onceE e
225− let eInner = switch bd
226− e' = leftmost [eOuter, eInner]
227− return (b, e')
228− ]
229−
230−splitRecombineEvent :: Reflex t => Event t a -> Event t String
231−splitRecombineEvent e =
232− let ea = "a" <$ e
233− eb = "b" <$ e
234− in leftmost [ea, eb]
235−
236−
237−test :: IO ()
238−test = do
239− results <- forM testCases $ \(name, TestCase inputs builder) -> do
240− putStrLn $ "Test: " <> name
241− testAgreement builder inputs
242− exitWith $ if and results
243− then ExitSuccess
244− else ExitFailure 1
test/Reflex/Test/Micro.hsdeleted−280
@@ -1,280 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE RecursiveDo #-}
9−
10−module Reflex.Test.Micro (testCases) where
11−
12−import Reflex
13−import Reflex.TestPlan
14−
15−import Control.Applicative
16−import Control.Monad
17−import Control.Monad.Fix
18−import Data.Char
19−import Data.Foldable
20−import Data.Functor.Misc
21−import qualified Data.Map as Map
22−import Data.Monoid
23−
24−import Prelude
25−
26−{-# ANN testCases "HLint: ignore Functor law" #-}
27−testCases :: [(String, TestCase)]
28−testCases =
29− [ testB "hold" $ hold "0" =<< events1
30−
31− , testB "count" $ do
32− b <- current <$> (count =<< events2)
33− return $ (+ (0::Int)) <$> b
34−
35− , testB "pull-1" $ do
36− b <- hold "0" =<< events1
37− return (pull $ sample $ pull $ sample b)
38−
39− , testB "pull-2" $ do
40− b1 <- behavior1
41− return (pull $ liftA2 (<>) (sample b1) (sample b1))
42−
43− , testB "pull-3" $ do
44− b1 <- behavior1
45− b2 <- behavior2
46− return (pull $ liftA2 (<>) (sample b1) (sample b2))
47−
48− , testB "pull-4" $ do
49− es <- planList ["a", "b", "c"]
50− e <- plan [(0, ())]
51− b <- hold (constant "") $
52− pushAlways (const $ hold "z" es) e
53− return (join b)
54−
55− , testE "id" $ do
56− events2
57−
58− , testE "fmap-id" $ do
59− e <- events2
60− return $ fmap id e
61−
62− , testE "tag-1" $ do
63− b1 <- behavior1
64− e <- events2
65− return (tag b1 e)
66−
67− , testE "tag-2" $ do
68− b1 <- behavior1
69− e <- events2
70− return (tag (map toUpper <$> b1) e)
71−
72− , testE "attach-1" $ do
73− b1 <- behavior1
74− e <- events2
75− return (attachWith (++) (map toUpper <$> b1) e)
76−
77− , testE "leftmost" $ liftA2 leftmost2 events1 events2
78−
79− , testE "appendEvents-1" $ liftA2 mappend events1 events2
80−
81− , testE "appendEvents-2" $ liftA2 mappend events3 events2
82−
83− , testE "merge-1" $ do
84− e <- events1
85− return $ leftmost ["x" <$ e, "y" <$ e]
86−
87− , testE "merge-2" $ do
88− e <- events1
89− let m = mergeMap $ Map.fromList [(1::Int, "y" <$ e), (2, "z" <$ e)]
90− let ee = flip pushAlways e $ const $ return m
91− return $ coincidence ee
92−
93− , testE "headE-1" $ do
94− e <- events1
95− headE $ leftmost [e, e]
96−
97− , testE "headE-2" $ do
98− e <- events1
99− b <- hold never (e <$ e)
100− headE $ switch b
101−
102− , testE "switch-1" $ do
103− e <- events1
104− b <- hold never (e <$ e)
105− return $ switch b
106−
107− , testE "switch-2" $ do
108− e <- events1
109− return $ coincidence $ flip pushAlways e $ const $ do
110− switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) (e <$ e)
111−
112− , testE "switch-3" $ do
113− e <- events1
114− return $ coincidence $ flip pushAlways e $ const $ do
115− switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) never
116−
117− , testE "switch-4" $ do
118− e <- events1
119− switch <$> hold (deep e) (e <$ e)
120−
121− , testE "switch-5" $ do
122− e <- events1
123− return $ coincidence $ flip pushAlways e $ const $
124− return $ leftmost ["x" <$ e, "y" <$ e, "z" <$ e]
125−
126− , testE "switch-6" $ do
127− e <- events1
128− return $ coincidence $ flip pushAlways e $ const $ do
129− switch <$> hold ("x" <$ e) (e <$ e)
130−
131− , testE "switchPromptly-1" $ do
132− e <- events1
133− let e' = e <$ e
134− switchPromptly never $ e <$ e'
135−
136− , testE "switchPromptly-2" $ do
137− e <- events1
138− switchPromptly never $ deep (e <$ e)
139−
140− , testE "switchPromptly-3" $ do
141− e <- events1
142− switchPromptly never $ (e <$ deep e)
143−
144− , testE "switchPromptly-4" $ do
145− e <- events1
146− switchPromptly never $ (deep e <$ e)
147−
148− , testE "switch-5" $ do
149− e <- events1
150− switch <$> hold never (deep e <$ e)
151−
152− , testE "switchPromptly-5" $ do
153− e <- events1
154− switchPromptly never $ flip push e $
155− const (Just <$> headE e)
156−
157− , testE "switchPromptly-6" $ do
158− e <- events1
159− switchPromptly never $ flip pushAlways e $
160− const (switchPromptly e never)
161−
162− , testE "coincidence-1" $ do
163− e <- events1
164− return $ coincidence $ flip pushAlways e $
165− const $ return e
166−
167− , testE "coincidence-2" $ do
168− e <- events1
169− return $ coincidence $ flip pushAlways e $
170− const $ return (deep e)
171−
172− , testE "coincidence-3" $ do
173− e <- events1
174− return $ coincidence $ flip pushAlways e $
175− const $ return (coincidence (e <$ e))
176−
177− , testE "coincidence-4" $ do
178− e <- events1
179− return $ coincidence $ flip pushAlways e $
180− const (headE e)
181−
182− , testE "coincidence-5" $ do
183− e <- events1
184− return $ coincidence $ flip pushAlways e $ const $ do
185− let e' = deep e
186− return (coincidence (e' <$ e'))
187−
188− , testE "coincidence-6" $ do
189− e <- events1
190− return $ coincidence $ flip pushAlways e $ const $ do
191− let e' = coincidence (e <$ e)
192− return $ deep e'
193−
194− , testE "coincidence-7" $ do
195− e <- events1
196− return $ coincidence (deep e <$ e)
197−
198− , testB "holdWhileFiring" $ do
199− e <- events1
200− eo <- headE e
201− bb <- hold (constant "x") $ pushAlways (const $ hold "a" eo) eo
202− return $ pull $ sample =<< sample bb
203−
204− , testE "joinDyn" $ do
205− e <- events1
206− bb <- hold "b" e
207− bd <- hold never . fmap (const e) =<< headE e
208−
209− eOuter <- pushAlways sample . fmap (const bb) <$> headE e
210− let eInner = switch bd
211− return $ leftmost [eOuter, eInner]
212−
213− , testB "foldDyn" $ do
214− d <- foldDyn (++) "0" =<< events1
215− return (current d)
216−
217− , testB "mapDyn" $ do
218− d <- foldDyn (++) "0" =<< events1
219− return $ current $ fmap (map toUpper) d
220−
221− , testB "combineDyn" $ do
222− d1 <- foldDyn (++) "0" =<< events1
223− d2 <- fmap (fmap (map toUpper)) $ foldDyn (++) "0" =<< events2
224−
225− return $ current $ zipDynWith (<>) d1 d2
226− , testE "fan-1" $ do
227− e <- fmap toMap <$> events1
228− let es = select (fanMap e) . Const2 <$> values
229−
230− return (mergeList es)
231−
232− , testE "fan-2" $ do
233− e <- fmap toMap <$> events3
234− let es = select (fanMap e) . Const2 <$> values
235−
236− return (mergeList es)
237−
238− , testE "fan-3" $ do
239− f <- fanMap . fmap toMap <$> events3
240− return $ select f (Const2 'c')
241−
242− , testE "fan-4" $ do
243− e <- fmap toMap <$> events1
244− return $ toUpper <$> select (fanMap e) (Const2 'a')
245−
246− , testE "fan-5" $ do
247− e <- fmap toMap <$> events2
248− return $ toUpper <$> select (fanMap e) (Const2 'c')
249−
250− , testE "fan-6" $ do
251− f <- fanMap . fmap toMap <$> events1
252− return $ toList <$> mergeList [ select f (Const2 'b'), select f (Const2 'b'), select f (Const2 'e'), select f (Const2 'e') ]
253−
254− , testE "lazy-hold" $ do
255− let lazyHold :: forall t m. (Reflex t, MonadHold t m, MonadFix m) => m (Event t ())
256− lazyHold = do
257− rec !b <- hold never e
258− let e = never <$ switch b
259− return $ void e
260− lazyHold
261−
262− ] where
263−
264− events1, events2, events3 :: TestPlan t m => m (Event t String)
265− events1 = plan [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")]
266− events2 = plan [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")]
267−
268− events3 = liftA2 mappend events1 events2
269−
270− values = "abcde"
271− toMap str = Map.fromList $ map (\c -> (c, c)) str
272−
273− behavior1, behavior2 :: forall t m. TestPlan t m => m (Behavior t String)
274− behavior1 = hold "1" =<< events1
275− behavior2 = hold "2" =<< events2
276−
277− deep e = leftmost [e, e]
278− leftmost2 e1 e2 = leftmost [e1, e2]
279−
280−
test/Reflex/TestPlan.hsdeleted−52
@@ -1,52 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE UndecidableInstances #-}
9−module Reflex.TestPlan
10− ( TestPlan(..)
11−
12− , TestCase (..)
13− , testE, testB
14− , TestE, TestB
15−
16− , planList
17−
18− ) where
19−
20−import Control.DeepSeq
21−import Control.Monad.Fix
22−import Data.Word
23−import Reflex.Class
24−
25−
26−import Prelude
27−
28−class (Reflex t, MonadHold t m, MonadFix m) => TestPlan t m where
29− -- | Speicify a plan of an input Event firing
30− -- Occurances 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/hlint.hs+34−11
@@ -1,16 +1,39 @@
1−import Language.Haskell.HLint3 (hlint)
1+module Main where
2+
3+import Control.Monad
4+import Language.Haskell.HLint (hlint)
5+import System.Directory
26import System.Exit (exitFailure, exitSuccess)
7+import System.FilePath
8+import System.FilePath.Find
39
410main :: IO ()
511main = do
6− ideas <- hlint
7− [ "."
8− , "--ignore=Redundant do"
9− , "--ignore=Use camelCase"
10− , "--ignore=Redundant $"
11− , "--ignore=Use &&&"
12− , "--ignore=Use const"
13− , "--ignore=Use >=>"
14− , "--ignore=Use ."
15− ]
12+ pwd <- getCurrentDirectory
13+ let runHlint f = hlint $ f:
14+ [ "--ignore=Redundant do"
15+ , "--ignore=Use camelCase"
16+ , "--ignore=Redundant $"
17+ , "--ignore=Use &&"
18+ , "--ignore=Use &&&"
19+ , "--ignore=Use const"
20+ , "--ignore=Use >=>"
21+ , "--ignore=Use ."
22+ , "--ignore=Use unless"
23+ , "--ignore=Reduce duplication"
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+ ]
28+ recurseInto = and <$> sequence
29+ [ fileType ==? Directory
30+ , fileName /=? ".git"
31+ ]
32+ matchFile = and <$> sequence
33+ [ extension ==? ".hs"
34+ ]
35+ files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
36+ ideas <- fmap concat $ forM files $ \f -> do
37+ putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
38+ runHlint f
1639 if null ideas then exitSuccess else exitFailure
test/semantics.hsdeleted−49
@@ -1,49 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−
8−module Main (main) where
9−
10−import Reflex.Test
11−
12−import Data.Bifunctor
13−import Data.Functor
14−import Data.List
15−import qualified Reflex.Bench.Focused as Focused
16−import qualified Reflex.Test.Micro as Micro
17−
18−import System.Environment
19−import System.Exit
20−
21−import Prelude
22−
23−matchPrefixes :: [String] -> (String -> Bool)
24−matchPrefixes [] = const True
25−matchPrefixes args = \name -> any (`isPrefixOf` name) args
26−
27−
28−main :: IO ()
29−main = do
30− args <- getArgs
31−
32− case args of
33− ["--list"] -> mapM_ putStrLn (fst <$> allTests) >> exitWith (ExitFailure 1)
34− _ -> case filter (matchPrefixes args . fst) allTests of
35− [] -> putStrLn "filter did not match any tests" >> exitWith (ExitFailure 1)
36− tests -> runTests tests
37−
38− where
39− allTests = concat
40− [ makeGroup "micro" Micro.testCases
41− , makeGroup "subscribing (100,40)" (Focused.subscribing 100 40)
42− , makeGroup "firing 1000" (Focused.firing 1000)
43− , makeGroup "merge 100" (Focused.merging 100)
44− , makeGroup "fan 50" (Focused.fans 50)
45− ]
46−
47− makeGroup name tests = first (\test -> intercalate "/" [name, test]) <$> tests
48−
49−
test/tests.hsnew file+43
@@ -0,0 +1,43 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+module Main where
3+
4+import Test.HUnit (runTestTT, (~:), assertEqual, errors, failures, test)
5+import Data.Patch ( Patch(apply) )
6+import Data.Patch.MapWithMove ( patchThatChangesMap )
7+import Data.Map as Map ( Map, fromList, singleton )
8+import Hedgehog (checkParallel, discover, Property, property, forAll, PropertyT, (===))
9+import Hedgehog.Gen as Gen ( int )
10+import Hedgehog.Range as Range ( linear )
11+import Control.Monad (replicateM)
12+import System.Exit (exitFailure, exitSuccess)
13+import Data.Sequence as Seq ( foldMapWithIndex, replicateM )
14+
15+main :: IO ()
16+main = do
17+ counts <- runTestTT $ test [
18+ "Simple Move" ~: (do
19+ let mapBefore = Map.fromList [(0,1)]
20+ mapAfter = Map.fromList [(0,0),(1,1)]
21+ patch = patchThatChangesMap mapBefore mapAfter
22+ afterPatch = apply patch mapBefore
23+ assertEqual "Patch creates the same Map" (Just mapAfter) afterPatch),
24+ "Property Checks" ~: propertyChecks
25+ ]
26+ if errors counts + failures counts == 0 then exitSuccess else exitFailure
27+
28+propertyChecks :: IO Bool
29+propertyChecks = checkParallel $$(discover)
30+
31+prop_patchThatChangesMap :: Property
32+prop_patchThatChangesMap = property $ do
33+ mapBefore <- makeRandomIntMap
34+ mapAfter <- makeRandomIntMap
35+ let patch = patchThatChangesMap mapBefore mapAfter
36+ Just mapAfter === apply patch mapBefore
37+
38+makeRandomIntMap :: Monad m => PropertyT m (Map Int Int)
39+makeRandomIntMap = do
40+ let genNum = Gen.int (Range.linear 0 100)
41+ length <- forAll genNum
42+ listOfNumbers <- forAll $ Seq.replicateM length genNum
43+ pure $ Seq.foldMapWithIndex Map.singleton listOfNumbers