on 82bb22a help sign in
40 files changed+2348−2726
since splitsnapshots
unifiedsplit
.ghci+3−1 .github/workflows/haskell.yml−47 .gitignore−7 .stylish-haskell.yaml−153 CONTRIBUTING.md−66 ChangeLog.md−61 LICENSE−12 README.md−52 Setup.hs−2 bench-cbits/checkCapability.c−208 cabal.project−1 default.nix+12 dep/reflex-platform/default.nix−8 dep/reflex-platform/github.json−8 patch.cabal−100 reflex.cabal+42 release.nix−49 src/Control/Monad/Ref.hs+85 src/Control/Monad/TypedId.hs+50 src/Data/Functor/Misc.hs+40−200 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/Reflex.hs+10 src/Reflex/Class.hs+240 src/Reflex/Dynamic.hs+423 src/Reflex/Dynamic/TH.hs+39 src/Reflex/Host/Class.hs+56 src/Reflex/Spider.hs+5 src/Reflex/Spider/Internal.hs+1343 stylize−4 test/hlint.hs−39 test/tests.hs−43
.ghci+3−1
@@ -1,2 +1,4 @@
11:set -isrc
2−:seti -XOverloadedStrings
2+:set -hide-package MonadCatchIO-mtl
3+:set -hide-package monads-fd
4+:set -XOverloadedStrings
.github/workflows/haskell.ymldeleted−47
@@ -1,47 +0,0 @@
1−name: github-action
2−
3−on: [push, pull_request]
4−
5−jobs:
6− build:
7− strategy:
8− matrix:
9− ghc: ['8.0.2', '8.2.2', '8.4.4', '8.6.5', '8.8.4', '8.10.2']
10− os: ['ubuntu-latest', 'macos-latest']
11− exclude:
12− # There are some linker warnings in 802 on darwin that
13− # cause compilation to fail
14− # See https://github.com/NixOS/nixpkgs/issues/25139
15− - ghc: '8.0.2'
16− os: 'macos-latest'
17− runs-on: ${{ matrix.os }}
18−
19− name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20− steps:
21− - uses: actions/checkout@v2
22− - uses: actions/setup-haskell@v1
23− with:
24− ghc-version: ${{ matrix.ghc }}
25− - name: Cache
26− uses: actions/cache@v1
27− env:
28− cache-name: cache-cabal
29− with:
30− path: ~/.cabal
31− key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32− restore-keys: |
33− ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34− ${{ runner.os }}-${{ matrix.ghc }}-build-
35− ${{ runner.os }}-${{ matrix.ghc }}-
36− ${{ runner.os }}
37−
38− - name: Install dependencies
39− run: |
40− cabal update
41− cabal build --only-dependencies --enable-tests --enable-benchmarks
42− - name: Build
43− run: cabal build --enable-tests --enable-benchmarks all
44− - name: Run tests
45− run: cabal test --enable-tests all
46− - name: Build Docs
47− run: cabal haddock
.gitignore−7
@@ -1,7 +1,4 @@
11dist
2−cabal.sandbox.config
3−.cabal-sandbox/
4−dist-*
52cabal-dev
63*.o
74*.hi
@@ -32,7 +29,3 @@ tags
3229hsenv.log
3330\#*#
3431.#*
35−/shell.nix
36−/ghci-tmp
37−*.dump-*
38−*.verbose-core2core
.stylish-haskell.yamldeleted−153
@@ -1,153 +0,0 @@
1−# stylish-haskell configuration file
2−# ==================================
3−
4−# The stylish-haskell tool is mainly configured by specifying steps. These steps
5−# are a list, so they have an order, and one specific step may appear more than
6−# once (if needed). Each file is processed by these steps in the given order.
7−steps:
8− # Convert some ASCII sequences to their Unicode equivalents. This is disabled
9− # by default.
10− # - unicode_syntax:
11− # # In order to make this work, we also need to insert the UnicodeSyntax
12− # # language pragma. If this flag is set to true, we insert it when it's
13− # # not already present. You may want to disable it if you configure
14− # # language extensions using some other method than pragmas. Default:
15− # # true.
16− # add_language_pragma: true
17−
18− # Import cleanup
19− - imports:
20− # There are different ways we can align names and lists.
21− #
22− # - global: Align the import names and import list throughout the entire
23− # file.
24− #
25− # - file: Like global, but don't add padding when there are no qualified
26− # imports in the file.
27− #
28− # - group: Only align the imports per group (a group is formed by adjacent
29− # import lines).
30− #
31− # - none: Do not perform any alignment.
32− #
33− # Default: global.
34− align: none
35−
36− # Folowing options affect only import list alignment.
37− #
38− # List align has following options:
39− #
40− # - after_alias: Import list is aligned with end of import including
41− # 'as' and 'hiding' keywords.
42− #
43− # > import qualified Data.List as List (concat, foldl, foldr, head,
44− # > init, last, length)
45− #
46− # - with_alias: Import list is aligned with start of alias or hiding.
47− #
48− # > import qualified Data.List as List (concat, foldl, foldr, head,
49− # > init, last, length)
50− #
51− # - new_line: Import list starts always on new line.
52− #
53− # > import qualified Data.List as List
54− # > (concat, foldl, foldr, head, init, last, length)
55− #
56− # Default: after alias
57− list_align: after_alias
58−
59− # Long list align style takes effect when import is too long. This is
60− # determined by 'columns' setting.
61− #
62− # - inline: This option will put as much specs on same line as possible.
63− #
64− # - new_line: Import list will start on new line.
65− #
66− # - new_line_multiline: Import list will start on new line when it's
67− # short enough to fit to single line. Otherwise it'll be multiline.
68− #
69− # - multiline: One line per import list entry.
70− # Type with contructor list acts like single import.
71− #
72− # > import qualified Data.Map as M
73− # > ( empty
74− # > , singleton
75− # > , ...
76− # > , delete
77− # > )
78− #
79− # Default: inline
80− long_list_align: inline
81−
82− # List padding determines indentation of import list on lines after import.
83− # This option affects 'list_align' and 'long_list_align'.
84− list_padding: 2
85−
86− # Separate lists option affects formating of import list for type
87− # or class. The only difference is single space between type and list
88− # of constructors, selectors and class functions.
89− #
90− # - true: There is single space between Foldable type and list of it's
91− # functions.
92− #
93− # > import Data.Foldable (Foldable (fold, foldl, foldMap))
94− #
95− # - false: There is no space between Foldable type and list of it's
96− # functions.
97− #
98− # > import Data.Foldable (Foldable(fold, foldl, foldMap))
99− #
100− # Default: true
101− separate_lists: true
102−
103− # Language pragmas
104− - language_pragmas:
105− # We can generate different styles of language pragma lists.
106− #
107− # - vertical: Vertical-spaced language pragmas, one per line.
108− #
109− # - compact: A more compact style.
110− #
111− # - compact_line: Similar to compact, but wrap each line with
112− # `{-#LANGUAGE #-}'.
113− #
114− # Default: vertical.
115− style: vertical
116−
117− # Align affects alignment of closing pragma brackets.
118− #
119− # - true: Brackets are aligned in same collumn.
120− #
121− # - false: Brackets are not aligned together. There is only one space
122− # between actual import and closing bracket.
123− #
124− # Default: true
125− align: false
126−
127− # stylish-haskell can detect redundancy of some language pragmas. If this
128− # is set to true, it will remove those redundant pragmas. Default: true.
129− remove_redundant: true
130−
131− # Align the types in record declarations
132− # - records: {}
133−
134− # Replace tabs by spaces. This is disabled by default.
135− # - tabs:
136− # # Number of spaces to use for each tab. Default: 8, as specified by the
137− # # Haskell report.
138− # spaces: 8
139−
140− # Remove trailing whitespace
141− - trailing_whitespace: {}
142−
143−# A common setting is the number of columns (parts of) code will be wrapped
144−# to. Different steps take this into account. Default: 80.
145−columns: 110
146−
147−# Sometimes, language extensions are specified in a cabal file or from the
148−# command line instead of using language pragmas in the file. stylish-haskell
149−# needs to be aware of these, so it can parse the file correctly.
150−#
151−# No language extensions are enabled by default.
152−language_extensions:
153− - TemplateHaskell
CONTRIBUTING.mddeleted−66
@@ -1,66 +0,0 @@
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.mddeleted−61
@@ -1,61 +0,0 @@
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.
LICENSE−12
@@ -1,12 +0,0 @@
1−Copyright (c) 2015, Obsidian Systems LLC
2−All rights reserved.
3−
4−Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5−
6−1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7−
8−2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9−
10−3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11−
12−THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.mddeleted−52
@@ -1,52 +0,0 @@
1−# patch
2−
3−[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/patch.svg)](https://hackage.haskell.org/package/patch) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/patch/badge)](https://matrix.hackage.haskell.org/#/package/patch) [![Travis CI](https://api.travis-ci.org/reflex-frp/patch.svg?branch=develop)](https://travis-ci.org/reflex-frp/patch) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/reflex-frp/patch/LICENSE)
4−
5−Data structures for describing changes to other data structures.
6−
7−A `Patch` type represents a kind of change made to a data structure.
8−
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−```
16−
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).
19−
20−`PatchMap` is defined as:
21−
22−```haskell
23−newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
24−```
25−
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`!
Setup.hsdeleted−2
@@ -1,2 +0,0 @@
1−import Distribution.Simple
2−main = defaultMain
bench-cbits/checkCapability.cdeleted−208
@@ -1,208 +0,0 @@
1−#include <Rts.h>
2−
3−// The InCall structure represents either a single in-call from C to
4−// Haskell, or a worker thread.
5−typedef struct InCall_ {
6− StgTSO * tso; // the bound TSO (or NULL for a worker)
7−
8− StgTSO * suspended_tso; // the TSO is stashed here when we
9− // make a foreign call (NULL otherwise);
10−
11− Capability *suspended_cap; // The capability that the
12− // suspended_tso is on, because
13− // we can't read this from the TSO
14− // without owning a Capability in the
15− // first place.
16−
17− SchedulerStatus rstat; // return status
18− StgClosure ** ret; // return value
19−
20− struct Task_ *task;
21−
22− // When a Haskell thread makes a foreign call that re-enters
23− // Haskell, we end up with another Task associated with the
24− // current thread. We have to remember the whole stack of InCalls
25− // associated with the current Task so that we can correctly
26− // save & restore the InCall on entry to and exit from Haskell.
27− struct InCall_ *prev_stack;
28−
29− // Links InCalls onto suspended_ccalls, spare_incalls
30− struct InCall_ *prev;
31− struct InCall_ *next;
32−} InCall;
33−
34−typedef struct Task_ {
35−#if defined(THREADED_RTS)
36− OSThreadId id; // The OS Thread ID of this task
37−
38− Condition cond; // used for sleeping & waking up this task
39− Mutex lock; // lock for the condition variable
40−
41− // this flag tells the task whether it should wait on task->cond
42− // or just continue immediately. It's a workaround for the fact
43− // that signalling a condition variable doesn't do anything if the
44− // thread is already running, but we want it to be sticky.
45− HsBool wakeup;
46−#endif
47−
48− // This points to the Capability that the Task "belongs" to. If
49− // the Task owns a Capability, then task->cap points to it. If
50− // the task does not own a Capability, then either (a) if the task
51− // is a worker, then task->cap points to the Capability it belongs
52− // to, or (b) it is returning from a foreign call, then task->cap
53− // points to the Capability with the returning_worker queue that this
54− // this Task is on.
55− //
56− // When a task goes to sleep, it may be migrated to a different
57− // Capability. Hence, we always check task->cap on wakeup. To
58− // syncrhonise between the migrater and the migratee, task->lock
59− // must be held when modifying task->cap.
60− struct Capability_ *cap;
61−
62− // The current top-of-stack InCall
63− struct InCall_ *incall;
64−
65− uint32_t n_spare_incalls;
66− struct InCall_ *spare_incalls;
67−
68− HsBool worker; // == rtsTrue if this is a worker Task
69− HsBool stopped; // this task has stopped or exited Haskell
70−
71− // So that we can detect when a finalizer illegally calls back into Haskell
72− HsBool running_finalizers;
73−
74− // Links tasks on the returning_tasks queue of a Capability, and
75− // on spare_workers.
76− struct Task_ *next;
77−
78− // Links tasks on the all_tasks list; need ACQUIRE_LOCK(&all_tasks_mutex)
79− struct Task_ *all_next;
80− struct Task_ *all_prev;
81−
82−} Task;
83−
84−struct Capability_ {
85− // State required by the STG virtual machine when running Haskell
86− // code. During STG execution, the BaseReg register always points
87− // to the StgRegTable of the current Capability (&cap->r).
88− StgFunTable f;
89− StgRegTable r;
90−
91− uint32_t no; // capability number.
92−
93− // The Task currently holding this Capability. This task has
94− // exclusive access to the contents of this Capability (apart from
95− // returning_tasks_hd/returning_tasks_tl).
96− // Locks required: cap->lock.
97− Task *running_task;
98−
99− // true if this Capability is running Haskell code, used for
100− // catching unsafe call-ins.
101− HsBool in_haskell;
102−
103− // Has there been any activity on this Capability since the last GC?
104− uint32_t idle;
105−
106− HsBool disabled;
107−
108− // The run queue. The Task owning this Capability has exclusive
109− // access to its run queue, so can wake up threads without
110− // taking a lock, and the common path through the scheduler is
111− // also lock-free.
112− StgTSO *run_queue_hd;
113− StgTSO *run_queue_tl;
114−
115− // Tasks currently making safe foreign calls. Doubly-linked.
116− // When returning, a task first acquires the Capability before
117− // removing itself from this list, so that the GC can find all
118− // the suspended TSOs easily. Hence, when migrating a Task from
119− // the returning_tasks list, we must also migrate its entry from
120− // this list.
121− InCall *suspended_ccalls;
122−
123− // One mutable list per generation, so we don't need to take any
124− // locks when updating an old-generation thunk. This also lets us
125− // keep track of which closures this CPU has been mutating, so we
126− // can traverse them using the right thread during GC and avoid
127− // unnecessarily moving the data from one cache to another.
128− bdescr **mut_lists;
129− bdescr **saved_mut_lists; // tmp use during GC
130−
131− // block for allocating pinned objects into
132− bdescr *pinned_object_block;
133− // full pinned object blocks allocated since the last GC
134− bdescr *pinned_object_blocks;
135−
136− // per-capability weak pointer list associated with nursery (older
137− // lists stored in generation object)
138− StgWeak *weak_ptr_list_hd;
139− StgWeak *weak_ptr_list_tl;
140−
141− // Context switch flag. When non-zero, this means: stop running
142− // Haskell code, and switch threads.
143− int context_switch;
144−
145− // Interrupt flag. Like the context_switch flag, this also
146− // indicates that we should stop running Haskell code, but we do
147− // *not* switch threads. This is used to stop a Capability in
148− // order to do GC, for example.
149− //
150− // The interrupt flag is always reset before we start running
151− // Haskell code, unlike the context_switch flag which is only
152− // reset after we have executed the context switch.
153− int interrupt;
154−
155− // Total words allocated by this cap since rts start
156− // See [Note allocation accounting] in Storage.c
157− W_ total_allocated;
158−
159−#if defined(THREADED_RTS)
160− // Worker Tasks waiting in the wings. Singly-linked.
161− Task *spare_workers;
162− uint32_t n_spare_workers; // count of above
163−
164− // This lock protects:
165− // running_task
166− // returning_tasks_{hd,tl}
167− // wakeup_queue
168− // inbox
169− Mutex lock;
170−
171− // Tasks waiting to return from a foreign call, or waiting to make
172− // a new call-in using this Capability (NULL if empty).
173− // NB. this field needs to be modified by tasks other than the
174− // running_task, so it requires cap->lock to modify. A task can
175− // check whether it is NULL without taking the lock, however.
176− Task *returning_tasks_hd; // Singly-linked, with head/tail
177− Task *returning_tasks_tl;
178−
179− // Messages, or END_TSO_QUEUE.
180− // Locks required: cap->lock
181− Message *inbox;
182−
183− SparkPool *sparks;
184−
185− // Stats on spark creation/conversion
186− SparkCounters spark_stats;
187−#if !defined(mingw32_HOST_OS)
188− // IO manager for this cap
189− int io_manager_control_wr_fd;
190−#endif
191−#endif
192−
193− // Per-capability STM-related data
194− StgTVarWatchQueue *free_tvar_watch_queues;
195− StgTRecChunk *free_trec_chunks;
196− StgTRecHeader *free_trec_headers;
197− uint32_t transaction_tokens;
198−} // typedef Capability is defined in RtsAPI.h
199− // We never want a Capability to overlap a cache line with anything
200− // else, so round it up to a cache line size:
201−#ifndef mingw32_HOST_OS
202− ATTRIBUTE_ALIGNED(64)
203−#endif
204− ;
205−
206−HsBool myCapabilityHasOtherRunnableThreads() {
207− return rts_unsafeGetMyCapability()->run_queue_hd == END_TSO_QUEUE ? HS_BOOL_FALSE : HS_BOOL_TRUE;
208−}
cabal.projectdeleted−1
@@ -1 +0,0 @@
1−packages: .
default.nixnew file+12
@@ -0,0 +1,12 @@
1+{ mkDerivation, dependent-map, dependent-sum, lens
2+, mtl, semigroups, these
3+}:
4+mkDerivation {
5+ pname = "reflex";
6+ version = "0.1";
7+ src = builtins.filterSource (path: type: baseNameOf path != ".git") ./.;
8+ buildDepends = [
9+ dependent-map dependent-sum lens mtl semigroups these
10+ ];
11+ license = null;
12+}
dep/reflex-platform/default.nixdeleted−8
@@ -1,8 +0,0 @@
1−# DO NOT HAND-EDIT THIS FILE
2−let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3− if !fetchSubmodules && !private then builtins.fetchTarball {
4− url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5− } else (import <nixpkgs> {}).fetchFromGitHub {
6− inherit owner repo rev sha256 fetchSubmodules private;
7− };
8−in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))
dep/reflex-platform/github.jsondeleted−8
@@ -1,8 +0,0 @@
1−{
2− "owner": "reflex-frp",
3− "repo": "reflex-platform",
4− "branch": "master",
5− "private": false,
6− "rev": "c9d11db1b98855fe8ab24a3ff6a5dbe0ad902ad9",
7− "sha256": "0sfzkqdvyah5mwvmli0wq1nl0b8cvk2cmfgfy4rz57wv42x3099y"
8−}
patch.cabaldeleted−100
@@ -1,100 +0,0 @@
1−Name: patch
2−Version: 0.0.5.0
3−Synopsis: Data structures for describing changes to other data structures.
4−Description:
5− Data structures for describing changes to other data structures.
6− .
7− In this library, a patch is something which can be applied, analogous to a
8− function, and which distinguishes returning the argument it was provided from
9− returning something else.
10−License: BSD3
11−License-file: LICENSE
12−Author: Ryan Trinkle
13−Maintainer: maintainer@obsidian.systems
14−Stability: Experimental
15−Category: FRP
16−Build-type: Simple
17−Cabal-version: >=1.10
18−homepage: https://obsidian.systems
19−bug-reports: https://github.com/reflex-frp/patch/issues
20−extra-source-files:
21− README.md
22− ChangeLog.md
23−
24−tested-with:
25− GHC ==8.0.2 || ==8.2.2 || ==8.4.4 || ==8.6.5 || ==8.8.1
26− GHCJS ==8.4
27−
28−flag split-these
29− description: Use split these/semialign packages
30− manual: False
31− default: True
32−
33−library
34− hs-source-dirs: src
35− default-language: Haskell2010
36− build-depends: base >= 4.9 && < 4.15
37− , constraints-extras >= 0.3 && < 0.4
38− , containers >= 0.6 && < 0.7
39− , dependent-map >= 0.3 && < 0.5
40− , dependent-sum >= 0.6 && < 0.8
41− , lens >= 4.7 && < 5
42− , semigroupoids >= 4.0 && < 6
43− , transformers >= 0.5.6.0 && < 0.6
44− , witherable >= 0.3 && < 0.5
45−
46− if impl(ghc < 8.6) -- really, if base < 8.12
47− build-depends: base-orphans >= 0.8 && < 0.9
48−
49− exposed-modules: Data.Functor.Misc
50− , Data.Monoid.DecidablyEmpty
51− , Data.Patch
52− , Data.Patch.Class
53− , Data.Patch.DMap
54− , Data.Patch.DMapWithMove
55− , Data.Patch.IntMap
56− , Data.Patch.Map
57− , Data.Patch.MapWithMove
58− , Data.Patch.MapWithPatchingMove
59− , Data.Semigroup.Additive
60−
61− ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs
62− default-extensions: PolyKinds
63−
64− if flag(split-these)
65− build-depends: these >= 1 && <1.2
66− , semialign >=1 && <1.2
67− , monoidal-containers >= 0.6 && < 0.7
68− else
69− build-depends: these >= 0.4 && <0.9
70− , monoidal-containers == 0.4.0.0
71−
72−test-suite tests
73− default-language: Haskell2010
74− type: exitcode-stdio-1.0
75− main-is: tests.hs
76− hs-source-dirs: test
77− build-depends: base
78− , patch
79− , containers
80− , hedgehog
81− , HUnit
82− if impl(ghcjs)
83− buildable: False
84−
85−test-suite hlint
86− default-language: Haskell2010
87− type: exitcode-stdio-1.0
88− main-is: hlint.hs
89− hs-source-dirs: test
90− build-depends: base
91− , directory
92− , filepath
93− , filemanip
94− , hlint (< 2.1 || >= 2.2.2) && < 3.3
95− if impl(ghcjs)
96− buildable: False
97−
98−source-repository head
99− type: git
100− location: https://github.com/reflex-frp/patch
reflex.cabalnew file+42
@@ -0,0 +1,42 @@
1+Name: reflex
2+Version: 0.1
3+Synopsis: Glitch-free higher-order Functional Reactive Programming
4+Description: Reflex is a high-performance, deterministic, higher-order Functional Reactive Programming system
5+License: AllRightsReserved
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+
14+library
15+ hs-source-dirs: src
16+ build-depends:
17+ base,
18+ dependent-sum,
19+ dependent-map,
20+ semigroups,
21+ mtl,
22+ containers,
23+ these,
24+ lens,
25+ primitive,
26+ template-haskell
27+
28+ exposed-modules:
29+ Reflex,
30+ Reflex.Spider,
31+ Reflex.Spider.Internal,
32+ Reflex.Class,
33+ Reflex.Dynamic,
34+ Reflex.Dynamic.TH,
35+ Reflex.Host.Class,
36+ Data.Functor.Misc,
37+ Control.Monad.TypedId,
38+ Control.Monad.Ref
39+
40+ other-extensions: TemplateHaskell
41+ ghc-prof-options: -fprof-auto
42+ ghc-options: -threaded -Wall -fwarn-tabs -funbox-strict-fields -O2
release.nixdeleted−49
@@ -1,49 +0,0 @@
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/Control/Monad/Ref.hsnew file+85
@@ -0,0 +1,85 @@
1+{-# LANGUAGE RecursiveDo, TypeFamilies, LambdaCase #-}
2+module Control.Monad.Ref where
3+
4+import Control.Monad
5+import Control.Monad.Trans
6+import Control.Monad.Reader
7+import Control.Monad.Writer
8+import Data.IORef
9+
10+class Monad m => MonadRef m where
11+ type Ref m :: * -> *
12+ newRef :: a -> m (Ref m a)
13+ readRef :: Ref m a -> m a
14+ writeRef :: Ref m a -> a -> m ()
15+ atomicModifyRef :: Ref m a -> (a -> (a, b)) -> m b
16+
17+instance MonadRef IO where
18+ type Ref IO = IORef
19+ {-# INLINE newRef #-}
20+ newRef = newIORef
21+ {-# INLINE readRef #-}
22+ readRef = readIORef
23+ {-# INLINE writeRef #-}
24+ writeRef = writeIORef
25+ {-# INLINE atomicModifyRef #-}
26+ atomicModifyRef r f = do
27+ result <- atomicModifyIORef' r f
28+-- evaluate =<< readIORef r --TODO: Verify that ghcjs now strictly evaluates the values in atomicModifyIORef', then remove this line
29+ return result
30+
31+{-# INLINE cacheM #-}
32+cacheM :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a, m ())
33+cacheM a = do
34+ r <- newRef undefined
35+ let invalidate = writeRef r $ do
36+ result <- a
37+ writeRef r $ return result
38+ return result
39+ invalidate
40+ return (join $ readRef r, invalidate)
41+
42+{-# INLINE cacheMWithTry #-}
43+cacheMWithTry :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a, m (Maybe a), m ())
44+cacheMWithTry a = do
45+ r <- newRef $ Left a
46+ let invalidate = writeRef r $ Left a
47+ get = readRef r >>= \case
48+ Left a' -> do
49+ result <- a'
50+ writeRef r $ Right result
51+ return result
52+ Right result -> return result
53+ tryGet = readRef r >>= \case
54+ Left _ -> return Nothing
55+ Right result -> return $ Just result
56+ return (get, tryGet, invalidate)
57+
58+-- | Not thread-safe or reentrant
59+{-# INLINE memoM #-}
60+memoM :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a)
61+memoM = liftM fst . cacheM
62+
63+{-# INLINE replaceRef #-}
64+replaceRef :: MonadRef m => Ref m a -> a -> m a
65+replaceRef r new = atomicModifyRef r $ \old -> (new, old)
66+
67+{-# INLINE modifyRef #-}
68+modifyRef :: MonadRef m => Ref m a -> (a -> a) -> m ()
69+modifyRef r f = atomicModifyRef r $ \a -> (f a, ())
70+
71+instance (Monoid w, MonadRef m) => MonadRef (WriterT w m) where
72+ {-# SPECIALIZE instance Monoid w => MonadRef (WriterT w IO) #-}
73+ type Ref (WriterT w m) = Ref m
74+ newRef = lift . newRef
75+ readRef = lift . readRef
76+ writeRef r = lift . writeRef r
77+ atomicModifyRef r f = lift $ atomicModifyRef r f
78+
79+instance MonadRef m => MonadRef (ReaderT r m) where
80+ {-# SPECIALIZE instance MonadRef (ReaderT r IO) #-}
81+ type Ref (ReaderT r m) = Ref m
82+ newRef = lift . newRef
83+ readRef = lift . readRef
84+ writeRef r = lift . writeRef r
85+ atomicModifyRef r f = lift $ atomicModifyRef r f
src/Control/Monad/TypedId.hsnew file+50
@@ -0,0 +1,50 @@
1+{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
2+module Control.Monad.TypedId ( MonadTypedId (..)
3+ ) where
4+
5+import Data.GADT.Compare
6+import Data.IORef
7+
8+import Control.Monad.State
9+import Control.Monad.Reader
10+
11+import Unsafe.Coerce
12+import System.IO.Unsafe
13+
14+class (Monad m, GCompare (TypedId m)) => MonadTypedId m where
15+ type TypedId m :: * -> *
16+ getTypedId :: m (TypedId m a)
17+
18+nextTypedIdIO :: IORef Int
19+{-# NOINLINE nextTypedIdIO #-}
20+nextTypedIdIO = unsafePerformIO $ newIORef 1
21+
22+newtype TypedId_IO a = TypedId_IO Int deriving (Show)
23+
24+instance MonadTypedId IO where
25+ type TypedId IO = TypedId_IO
26+ {-# INLINE getTypedId #-}
27+ getTypedId = do
28+ n <- atomicModifyIORef' nextTypedIdIO $ \n -> (succ n, n)
29+ return $ TypedId_IO n
30+
31+instance GCompare TypedId_IO where
32+ {-# INLINE gcompare #-}
33+ TypedId_IO a `gcompare` TypedId_IO b = case a `compare` b of
34+ LT -> GLT
35+ EQ -> unsafeCoerce GEQ
36+ GT -> GGT
37+
38+instance GEq TypedId_IO where
39+ {-# INLINE geq #-}
40+ TypedId_IO a `geq` TypedId_IO b = if a == b then Just $ unsafeCoerce Refl else Nothing
41+
42+instance MonadTypedId m => MonadTypedId (StateT s m) where
43+ type TypedId (StateT s m) = TypedId m
44+ {-# INLINE getTypedId #-}
45+ getTypedId = lift getTypedId
46+
47+instance MonadTypedId m => MonadTypedId (ReaderT r m) where
48+ type TypedId (ReaderT r m) = TypedId m
49+ {-# INLINE getTypedId #-}
50+ getTypedId = lift getTypedId
src/Data/Functor/Misc.hs+40−200
@@ -1,78 +1,29 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE DeriveFunctor #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE LambdaCase #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE PolyKinds #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE StandaloneDeriving #-}
13−-- | This module provides types and functions with no particular theme, but
14−-- which are relevant to the use of 'Functor'-based datastructures like
15−-- 'Data.Dependent.Map.DMap'.
16−module Data.Functor.Misc
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
1+{-# LANGUAGE KindSignatures, GADTs, DeriveDataTypeable, RankNTypes, ScopedTypeVariables #-}
2+module Data.Functor.Misc where
383
39−import Control.Applicative ((<$>))
40−import Data.Dependent.Map (DMap)
41−import qualified Data.Dependent.Map as DMap
42−import Data.Dependent.Sum
43−import Data.Functor.Identity
444import Data.GADT.Compare
45−import Data.GADT.Show
46−import Data.IntMap (IntMap)
47−import qualified Data.IntMap as IntMap
485import Data.Map (Map)
496import qualified Data.Map as Map
50−import Data.Some (Some, mkSome)
51−import Data.These
52−import Data.Type.Equality ((:~:)(Refl))
7+import Data.Dependent.Map (DMap, DSum (..))
8+import qualified Data.Dependent.Map as DMap
539import Data.Typeable hiding (Refl)
10+import Data.These
5411
55−--------------------------------------------------------------------------------
56−-- Const2
57−--------------------------------------------------------------------------------
58−
59−-- | 'Const2' stores a value of a given type 'k' and ensures that a particular
60−-- type 'v' is always given for the last type parameter
61−data Const2 :: * -> x -> x -> * where
62− Const2 :: k -> Const2 k v v
63− deriving (Typeable)
12+data WrapArg :: (* -> *) -> (* -> *) -> * -> * where
13+ WrapArg :: f a -> WrapArg g f (g a)
6414
65−-- | Extract the value from a Const2
66−unConst2 :: Const2 k v v' -> k
67−unConst2 (Const2 k) = k
15+instance GEq f => GEq (WrapArg g f) where
16+ geq (WrapArg a) (WrapArg b) = fmap (\Refl -> Refl) $ geq a b
6817
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)
18+instance GCompare f => GCompare (WrapArg g f) where
19+ gcompare (WrapArg a) (WrapArg b) = case gcompare a b of
20+ GLT -> GLT
21+ GEQ -> GEQ
22+ GGT -> GGT
7323
74−instance Show k => GShow (Const2 k v) where
75− gshowsPrec n x@(Const2 _) = showsPrec n x
24+data Const2 :: * -> * -> * -> * where
25+ Const2 :: k -> Const2 k v v
26+ deriving (Typeable)
7627
7728instance Eq k => GEq (Const2 k v) where
7829 geq (Const2 a) (Const2 b) =
@@ -86,146 +37,35 @@ instance Ord k => GCompare (Const2 k v) where
8637 EQ -> GEQ
8738 GT -> GGT
8839
89−-- | Convert a 'DMap' to a regular 'Map'
90−dmapToMap :: DMap (Const2 k v) Identity -> Map k v
91−dmapToMap = Map.fromDistinctAscList . map (\(Const2 k :=> Identity v) -> (k, v)) . DMap.toAscList
92−
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−
102−-- | Convert a regular 'Map' to a 'DMap'
103−mapToDMap :: Map k v -> DMap (Const2 k v) Identity
104−mapToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> Identity v) . Map.toAscList
105−
106−-- | Convert a regular 'Map', where the values are already wrapped in a functor,
107−-- to a 'DMap'
108−mapWithFunctorToDMap :: Map k (f v) -> DMap (Const2 k v) f
109−mapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> v) . Map.toAscList
110−
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−
121−--------------------------------------------------------------------------------
122−-- WrapArg
123−--------------------------------------------------------------------------------
124−
125−-- | 'WrapArg' can be used to tag a value in one functor with a type
126−-- representing another functor. This was primarily used with dependent-map <
127−-- 0.2, in which the value type was not wrapped in a separate functor.
128−data WrapArg :: (k -> *) -> (k -> *) -> * -> * where
129− WrapArg :: f a -> WrapArg g f (g a)
130−
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−
136−instance GEq f => GEq (WrapArg g f) where
137− geq (WrapArg a) (WrapArg b) = (\Refl -> Refl) <$> geq a b
138−
139−instance GCompare f => GCompare (WrapArg g f) where
140− gcompare (WrapArg a) (WrapArg b) = case gcompare a b of
141− GLT -> GLT
142− GEQ -> GEQ
143− GGT -> GGT
144−
145−--------------------------------------------------------------------------------
146−-- Convenience functions for DMap
147−--------------------------------------------------------------------------------
148−
149−-- | Map over all key/value pairs in a 'DMap', potentially altering the key as
150−-- well as the value. The provided function MUST preserve the ordering of the
151−-- keys, or the resulting 'DMap' will be malformed.
152−mapKeyValuePairsMonotonic :: (DSum k v -> DSum k' v') -> DMap k v -> DMap k' v'
153−mapKeyValuePairsMonotonic f = DMap.fromDistinctAscList . map f . DMap.toAscList
40+{-# INLINE sequenceDmap #-}
41+sequenceDmap :: (Monad m, GCompare f) => DMap (WrapArg m f) -> m (DMap f)
42+sequenceDmap = DMap.foldrWithKey (\(WrapArg k) mv mx -> mx >>= \x -> mv >>= \v -> return $ DMap.insert k v x) (return DMap.empty)
15443
15544{-# INLINE combineDMapsWithKey #-}
156−-- | Union two 'DMap's of different types, yielding another type. Each key that
157−-- is present in either input map will be present in the output.
158−combineDMapsWithKey :: forall f g h i.
159− GCompare f
160− => (forall a. f a -> These (g a) (h a) -> i a)
161− -> DMap f g
162− -> DMap f h
163− -> DMap f i
45+combineDMapsWithKey :: forall f g h i. GCompare f => (forall a. f a -> These (g a) (h a) -> i a) -> DMap (WrapArg g f) -> DMap (WrapArg h f) -> DMap (WrapArg i f)
16446combineDMapsWithKey f mg mh = DMap.fromList $ go (DMap.toList mg) (DMap.toList mh)
165− where go :: [DSum f g] -> [DSum f h] -> [DSum f i]
166− go [] hs = map (\(hk :=> hv) -> hk :=> f hk (That hv)) hs
167− go gs [] = map (\(gk :=> gv) -> gk :=> f gk (This gv)) gs
168− go gs@((gk :=> gv) : gs') hs@((hk :=> hv) : hs') = case gk `gcompare` hk of
169− GLT -> (gk :=> f gk (This gv)) : go gs' hs
170− GEQ -> (gk :=> f gk (These gv hv)) : go gs' hs'
171− GGT -> (hk :=> f hk (That hv)) : go gs hs'
172−
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
47+ where go :: [DSum (WrapArg g f)] -> [DSum (WrapArg h f)] -> [DSum (WrapArg i f)]
48+ go [] hs = map (\(WrapArg hk :=> hv) -> WrapArg hk :=> f hk (That hv)) hs
49+ go gs [] = map (\(WrapArg gk :=> gv) -> WrapArg gk :=> f gk (This gv)) gs
50+ go gs@((WrapArg gk :=> gv) : gs') hs@((WrapArg hk :=> hv) : hs') = case gk `gcompare` hk of
51+ GLT -> (WrapArg gk :=> f gk (This gv)) : go gs' hs
52+ GEQ -> (WrapArg gk :=> f gk (These gv hv)) : go gs' hs'
53+ GGT -> (WrapArg hk :=> f hk (That hv)) : go gs hs'
20354
204−instance GShow (EitherTag l r) where
205− gshowsPrec _ a = case a of
206− LeftTag -> showString "LeftTag"
207− RightTag -> showString "RightTag"
55+wrapDMap :: (forall a. a -> f a) -> DMap k -> DMap (WrapArg f k)
56+wrapDMap f = DMap.fromDistinctAscList . map (\(k :=> v) -> WrapArg k :=> f v) . DMap.toAscList
20857
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)
58+rewrapDMap :: (forall a. f a -> g a) -> DMap (WrapArg f k) -> DMap (WrapArg g k)
59+rewrapDMap f = DMap.fromDistinctAscList . map (\(WrapArg k :=> v) -> WrapArg k :=> f v) . DMap.toAscList
21460
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
61+unwrapDMap :: (forall a. f a -> a) -> DMap (WrapArg f k) -> DMap k
62+unwrapDMap f = DMap.fromDistinctAscList . map (\(WrapArg k :=> v) -> k :=> f v) . DMap.toAscList
22063
221−--------------------------------------------------------------------------------
222−-- ComposeMaybe
223−--------------------------------------------------------------------------------
64+mapToDMap :: Map k v -> DMap (Const2 k v)
65+mapToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> v) . Map.toAscList
22466
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)
67+mapWithFunctorToDMap :: Map k (f v) -> DMap (WrapArg f (Const2 k v))
68+mapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> WrapArg (Const2 k) :=> v) . Map.toAscList
23069
231−deriving instance Functor f => Functor (ComposeMaybe f)
70+dmapToMap :: DMap (Const2 k v) -> Map k v
71+dmapToMap = Map.fromDistinctAscList . map (\(Const2 k :=> v) -> (k, v)) . DMap.toAscList
src/Data/Monoid/DecidablyEmpty.hsdeleted−115
@@ -1,115 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DefaultSignatures #-}
3−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4−{-# LANGUAGE StandaloneDeriving #-}
5−{-# LANGUAGE TypeOperators #-}
6−
7−-- TODO upstream somwhere else?
8−module Data.Monoid.DecidablyEmpty where
9−
10−import Data.Functor.Identity
11−import Data.Functor.Const
12−import Data.Monoid
13−import Data.Maybe (isNothing)
14−#if MIN_VERSION_base(4,11,0)
15−import Data.Ord
16−#endif
17−import Data.Proxy
18−import Data.Semigroup hiding (First, Last)
19−#if MIN_VERSION_base(4,12,0)
20−import GHC.Generics
21−#endif
22−
23−import qualified Data.IntSet as IntSet
24−import qualified Data.IntMap as IntMap
25−import qualified Data.Map as Map
26−import qualified Data.Sequence as Seq
27−import qualified Data.Set as Set
28−
29−import Data.GADT.Compare
30−import qualified Data.Dependent.Map as DMap
31−
32−-- | A 'DecidablyEmpty' is one where it can be computed whether or not an
33−-- arbitrary value is 'mempty'.
34−--
35−-- By using this class rather than 'Eq', we avoid unnecessary constraining the
36−-- contents of 'Functor's. This makes it possible to efficiently combine and/or
37−-- nest patch maps with 'Eq'-lacking values (e.g. functions) at the leaves.
38−class Monoid a => DecidablyEmpty a where
39− isEmpty :: a -> Bool
40− default isEmpty :: Eq a => a -> Bool
41− isEmpty = (==) mempty
42−
43−-- base
44−
45−instance DecidablyEmpty Ordering
46−instance DecidablyEmpty ()
47−instance DecidablyEmpty Any
48−instance DecidablyEmpty All
49−-- instance DecidablyEmpty Lifetime
50−-- instance DecidablyEmpty Event
51−instance DecidablyEmpty [a] where
52− isEmpty = null
53−instance
54−#if MIN_VERSION_base(4,11,0)
55− Semigroup a
56−#else
57− Monoid a
58−#endif
59− => DecidablyEmpty (Maybe a) where
60− isEmpty = isNothing
61−deriving instance (Num a, DecidablyEmpty a) => DecidablyEmpty (Product a)
62−deriving instance (DecidablyEmpty a, Num a) => DecidablyEmpty (Sum a)
63−deriving instance DecidablyEmpty a => DecidablyEmpty (Dual a)
64−instance DecidablyEmpty (First a) where
65− isEmpty (First a) = isNothing a
66−instance DecidablyEmpty (Last a) where
67− isEmpty (Last a) = isNothing a
68−deriving instance DecidablyEmpty a => DecidablyEmpty (Identity a)
69−instance Semigroup a => DecidablyEmpty (Option a) where
70− isEmpty (Option a) = isNothing a
71−deriving instance DecidablyEmpty m => DecidablyEmpty (WrappedMonoid m)
72−instance (Ord a, Bounded a) => DecidablyEmpty (Max a)
73−instance (Ord a, Bounded a) => DecidablyEmpty (Min a)
74−instance DecidablyEmpty (Proxy s)
75−deriving instance DecidablyEmpty a => DecidablyEmpty (Const a b)
76−#if MIN_VERSION_base(4,11,0)
77−deriving instance DecidablyEmpty a => DecidablyEmpty (Down a)
78−#endif
79−#if MIN_VERSION_base(4,12,0)
80−deriving instance DecidablyEmpty p => DecidablyEmpty (Par1 p)
81−instance DecidablyEmpty (U1 p)
82−deriving instance DecidablyEmpty (f p) => DecidablyEmpty (Rec1 f p)
83−deriving instance DecidablyEmpty (f p) => DecidablyEmpty (M1 i c f p)
84−deriving instance DecidablyEmpty c => DecidablyEmpty (K1 i c p)
85−instance (DecidablyEmpty (f p), DecidablyEmpty (g p)) => DecidablyEmpty ((f :*: g) p) where
86− isEmpty (x :*: y) = isEmpty x && isEmpty y
87−deriving instance DecidablyEmpty (f (g p)) => DecidablyEmpty ((f :.: g) p)
88−#endif
89−
90−instance (DecidablyEmpty a, DecidablyEmpty b) => DecidablyEmpty (a, b) where
91− isEmpty (a, b) = isEmpty a && isEmpty b
92−instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c) => DecidablyEmpty (a, b, c) where
93− isEmpty (a, b, c) = isEmpty a && isEmpty b && isEmpty c
94−instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d) => DecidablyEmpty (a, b, c, d) where
95− isEmpty (a, b, c, d) = isEmpty a && isEmpty b && isEmpty c && isEmpty d
96−instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d, DecidablyEmpty e) => DecidablyEmpty (a, b, c, d, e) where
97− isEmpty (a, b, c, d, e) = isEmpty a && isEmpty b && isEmpty c && isEmpty d && isEmpty e
98−
99−-- containers
100−
101−instance DecidablyEmpty IntSet.IntSet where
102− isEmpty = IntSet.null
103−instance DecidablyEmpty (IntMap.IntMap v) where
104− isEmpty = IntMap.null
105−instance Ord k => DecidablyEmpty (Map.Map k v) where
106− isEmpty = Map.null
107−instance DecidablyEmpty (Seq.Seq v) where
108− isEmpty = Seq.null
109−instance Ord k => DecidablyEmpty (Set.Set k) where
110− isEmpty = Set.null
111−
112−-- dependent-map
113−
114−instance GCompare k => DecidablyEmpty (DMap.DMap k v) where
115− isEmpty = DMap.null
src/Data/Patch.hsdeleted−95
@@ -1,95 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3−{-# LANGUAGE StandaloneDeriving #-}
4−{-# LANGUAGE TypeFamilies #-}
5−{-# LANGUAGE TypeOperators #-}
6−-- |
7−-- Module:
8−-- Data.Patch
9−-- Description:
10−-- This module defines the 'Patch' class.
11−module Data.Patch
12− ( module Data.Patch
13− , module X
14− ) where
15−
16−import Control.Applicative
17−import Data.Functor.Const (Const (..))
18−import Data.Functor.Identity
19−import Data.Map.Monoidal (MonoidalMap)
20−import Data.Proxy
21−#if !MIN_VERSION_base(4,11,0)
22−import Data.Semigroup (Semigroup (..))
23−#endif
24−import GHC.Generics
25−
26−import Data.Semigroup.Additive as X
27−import Data.Patch.Class as X
28−import Data.Patch.DMap as X hiding (getDeletions)
29−import Data.Patch.DMapWithMove as X
30− ( PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove
31− , patchDMapWithMoveToPatchMapWithMoveWith
32− , traversePatchDMapWithMoveWithKey, unPatchDMapWithMove
33− , unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith
34− )
35−import Data.Patch.IntMap as X hiding (getDeletions)
36−import Data.Patch.Map as X
37−import Data.Patch.MapWithMove as X
38− ( PatchMapWithMove, patchMapWithMoveNewElements
39− , patchMapWithMoveNewElementsMap, unPatchMapWithMove
40− , unsafePatchMapWithMove
41− )
42−
43−-- | A 'Group' is a 'Monoid' where every element has an inverse.
44−class (Semigroup q, Monoid q) => Group q where
45− negateG :: q -> q
46− (~~) :: q -> q -> q
47− r ~~ s = r <> negateG s
48−
49−-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
50−newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
51−
52−instance Additive p => Patch (AdditivePatch p) where
53− type PatchTarget (AdditivePatch p) = p
54− apply (AdditivePatch p) q = Just $ p <> q
55−
56−instance (Ord k, Group q) => Group (MonoidalMap k q) where
57− negateG = fmap negateG
58−
59−-- | Trivial group.
60−instance Group () where
61− negateG _ = ()
62− _ ~~ _ = ()
63−
64−-- | Product group. A Pair of groups gives rise to a group
65−instance (Group a, Group b) => Group (a, b) where
66− negateG (a, b) = (negateG a, negateG b)
67− (a, b) ~~ (c, d) = (a ~~ c, b ~~ d)
68−
69−-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
70−-- Base does not define Monoid (Compose f g a) so this is the best we can
71−-- really do for functor composition.
72−instance Group (f (g a)) => Group ((f :.: g) a) where
73− negateG (Comp1 xs) = Comp1 (negateG xs)
74− Comp1 xs ~~ Comp1 ys = Comp1 (xs ~~ ys)
75−
76−-- | Product of groups, Functor style.
77−instance (Group (f a), Group (g a)) => Group ((f :*: g) a) where
78− negateG (a :*: b) = negateG a :*: negateG b
79− (a :*: b) ~~ (c :*: d) = (a ~~ c) :*: (b ~~ d)
80−
81−-- | Trivial group, Functor style
82−instance Group (Proxy x) where
83− negateG _ = Proxy
84− _ ~~ _ = Proxy
85−
86−-- | Const lifts groups into a functor.
87−deriving instance Group a => Group (Const a x)
88−
89−-- | Identity lifts groups pointwise (at only one point)
90−deriving instance Group a => Group (Identity a)
91−
92−-- | Functions lift groups pointwise.
93−instance Group b => Group (a -> b) where
94− negateG f = negateG . f
95− (~~) = liftA2 (~~)
src/Data/Patch/Class.hsdeleted−45
@@ -1,45 +0,0 @@
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.hsdeleted−93
@@ -1,93 +0,0 @@
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.hsdeleted−371
@@ -1,371 +0,0 @@
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.hsdeleted−76
@@ -1,76 +0,0 @@
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.hsdeleted−72
@@ -1,72 +0,0 @@
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.hsdeleted−312
@@ -1,312 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveTraversable #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE PatternGuards #-}
9−{-# LANGUAGE PatternSynonyms #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE StandaloneDeriving #-}
12−{-# LANGUAGE TemplateHaskell #-}
13−{-# LANGUAGE TypeApplications #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE ViewPatterns #-}
16−
17−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
18−-- another
19−module Data.Patch.MapWithMove
20− ( PatchMapWithMove
21− ( PatchMapWithMove
22− , unPatchMapWithMove
23− , ..
24− )
25− , patchMapWithMove
26− , patchMapWithMoveInsertAll
27− , insertMapKey
28− , moveMapKey
29− , swapMapKey
30− , deleteMapKey
31− , unsafePatchMapWithMove
32− , patchMapWithMoveNewElements
33− , patchMapWithMoveNewElementsMap
34− , patchThatSortsMapWith
35− , patchThatChangesAndSortsMapWith
36− , patchThatChangesMap
37−
38− -- * Node Info
39− , NodeInfo
40− ( NodeInfo
41− , _nodeInfo_to
42− , _nodeInfo_from
43− , ..
44− )
45− , bitraverseNodeInfo
46− , nodeInfoMapFrom
47− , nodeInfoMapMFrom
48− , nodeInfoSetTo
49−
50− -- * From
51− , From
52− ( From_Insert
53− , From_Delete
54− , From_Move
55− , ..
56− )
57− , bitraverseFrom
58−
59− -- * To
60− , To
61− ) where
62−
63−import Data.Coerce
64−import Data.Kind (Type)
65−import Data.Patch.Class
66−import Data.Patch.MapWithPatchingMove (PatchMapWithPatchingMove(..), To)
67−import qualified Data.Patch.MapWithPatchingMove as PM -- already a transparent synonym
68−
69−import Control.Lens
70−import Data.List
71−import Data.Map (Map)
72−import qualified Data.Map as Map
73−import Data.Proxy
74−#if !MIN_VERSION_base(4,11,0)
75−import Data.Semigroup (Semigroup (..))
76−#endif
77−import Data.Traversable (foldMapDefault)
78−
79−-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
80−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
81−-- and vice versa. There should never be any unpaired From/To keys.
82−newtype PatchMapWithMove k (v :: Type) = PatchMapWithMove'
83− { -- | Extract the underlying 'PatchMapWithPatchingMove k (Proxy v)'
84− unPatchMapWithMove' :: PatchMapWithPatchingMove k (Proxy v)
85− }
86− deriving ( Show, Read, Eq, Ord
87−-- Haddock cannot handle documentation here before GHC 8.6
88− ,
89−#if __GLASGOW_HASKELL__ >= 806
90− -- | Compose patches having the same effect as applying the
91− -- patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p .
92− -- 'applyAlways' q@
93−#endif
94− Semigroup
95− , Monoid
96− )
97−
98−pattern Coerce :: Coercible a b => a -> b
99−pattern Coerce x <- (coerce -> x)
100− where Coerce x = coerce x
101−
102−{-# COMPLETE PatchMapWithMove #-}
103−pattern PatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
104−-- | Extract the representation of the 'PatchMapWithMove' as a map of
105−-- 'NodeInfo'.
106−unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
107−pattern PatchMapWithMove { unPatchMapWithMove } = PatchMapWithMove' (PatchMapWithPatchingMove (Coerce unPatchMapWithMove))
108−
109−_PatchMapWithMove
110− :: Iso
111− (PatchMapWithMove k0 v0)
112− (PatchMapWithMove k1 v1)
113− (Map k0 (NodeInfo k0 v0))
114− (Map k1 (NodeInfo k1 v1))
115−_PatchMapWithMove = iso unPatchMapWithMove PatchMapWithMove
116−
117−instance Functor (PatchMapWithMove k) where
118− fmap f = runIdentity . traverse (Identity . f)
119−
120−instance Foldable (PatchMapWithMove k) where
121− foldMap = foldMapDefault
122−
123−instance Traversable (PatchMapWithMove k) where
124− traverse =
125− _PatchMapWithMove .
126− traverse .
127− traverse
128−
129−instance FunctorWithIndex k (PatchMapWithMove k)
130−instance FoldableWithIndex k (PatchMapWithMove k)
131−instance TraversableWithIndex k (PatchMapWithMove k) where
132− itraverse = itraversed . Indexed
133− itraversed =
134− _PatchMapWithMove .>
135− itraversed <.
136− traverse
137−
138−-- | Create a 'PatchMapWithMove', validating it
139−patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
140−patchMapWithMove = fmap PatchMapWithMove' . PM.patchMapWithPatchingMove . coerce
141−
142−-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
143−patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
144−patchMapWithMoveInsertAll = PatchMapWithMove' . PM.patchMapWithPatchingMoveInsertAll
145−
146−-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
147−insertMapKey :: k -> v -> PatchMapWithMove k v
148−insertMapKey k v = PatchMapWithMove' $ PM.insertMapKey k v
149−
150−-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
151−--
152−-- @
153−-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
154−-- @
155−moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
156−moveMapKey src dst = PatchMapWithMove' $ PM.moveMapKey src dst
157−
158−-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
159−--
160−-- @
161−-- let aMay = Map.lookup a map
162−-- bMay = Map.lookup b map
163−-- in maybe id (Map.insert a) (bMay <> aMay)
164−-- . maybe id (Map.insert b) (aMay <> bMay)
165−-- . Map.delete a . Map.delete b $ map
166−-- @
167−swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
168−swapMapKey src dst = PatchMapWithMove' $ PM.swapMapKey src dst
169−
170−-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
171−deleteMapKey :: k -> PatchMapWithMove k v
172−deleteMapKey = PatchMapWithMove' . PM.deleteMapKey
173−
174−-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
175−--
176−-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
177−unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
178−unsafePatchMapWithMove = coerce PM.unsafePatchMapWithPatchingMove
179−
180−-- | Apply the insertions, deletions, and moves to a given 'Map'
181−instance Ord k => Patch (PatchMapWithMove k v) where
182− type PatchTarget (PatchMapWithMove k v) = Map k v
183− apply (PatchMapWithMove' p) = apply p
184−
185−-- | Returns all the new elements that will be added to the 'Map'.
186−patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
187−patchMapWithMoveNewElements = PM.patchMapWithPatchingMoveNewElements . unPatchMapWithMove'
188−
189−-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
190−patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
191−patchMapWithMoveNewElementsMap = PM.patchMapWithPatchingMoveNewElementsMap . unPatchMapWithMove'
192−
193−-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
194−-- its values using the given ordering function. The set keys of the 'Map' is
195−-- not changed.
196−patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
197−patchThatSortsMapWith cmp = PatchMapWithMove' . PM.patchThatSortsMapWith cmp
198−
199−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
200−-- will produce a 'Map' with the same values as the second 'Map' but with the
201−-- values sorted with the given ordering function.
202−patchThatChangesAndSortsMapWith :: (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
203−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
204− where newList = Map.toList newByIndexUnsorted
205− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
206−
207−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
208−-- will produce the second 'Map'.
209−patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
210−patchThatChangesMap oldByIndex newByIndex = PatchMapWithMove' $
211− PM.patchThatChangesMap oldByIndex newByIndex
212−
213−--
214−-- NodeInfo
215−--
216−
217−-- | Holds the information about each key: where its new value should come from,
218−-- and where its old value should go to
219−newtype NodeInfo k (v :: Type) = NodeInfo' { unNodeInfo' :: PM.NodeInfo k (Proxy v) }
220−
221−deriving instance (Show k, Show p) => Show (NodeInfo k p)
222−deriving instance (Read k, Read p) => Read (NodeInfo k p)
223−deriving instance (Eq k, Eq p) => Eq (NodeInfo k p)
224−deriving instance (Ord k, Ord p) => Ord (NodeInfo k p)
225−
226−{-# COMPLETE NodeInfo #-}
227−pattern NodeInfo :: To k -> From k v -> NodeInfo k v
228−_nodeInfo_to :: NodeInfo k v -> To k
229−_nodeInfo_from :: NodeInfo k v -> From k v
230−pattern NodeInfo { _nodeInfo_to, _nodeInfo_from } = NodeInfo'
231− PM.NodeInfo
232− { PM._nodeInfo_to = _nodeInfo_to
233− , PM._nodeInfo_from = Coerce _nodeInfo_from
234− }
235−
236−_NodeInfo
237− :: Iso
238− (NodeInfo k0 v0)
239− (NodeInfo k1 v1)
240− (PM.NodeInfo k0 (Proxy v0))
241− (PM.NodeInfo k1 (Proxy v1))
242−_NodeInfo = iso unNodeInfo' NodeInfo'
243−
244−instance Functor (NodeInfo k) where
245− fmap f = runIdentity . traverse (Identity . f)
246−
247−instance Foldable (NodeInfo k) where
248− foldMap = foldMapDefault
249−
250−instance Traversable (NodeInfo k) where
251− traverse = bitraverseNodeInfo pure
252−
253−bitraverseNodeInfo
254− :: Applicative f
255− => (k0 -> f k1)
256− -> (v0 -> f v1)
257− -> NodeInfo k0 v0 -> f (NodeInfo k1 v1)
258−bitraverseNodeInfo fk fv = fmap NodeInfo'
259− . PM.bitraverseNodeInfo fk (\ ~Proxy -> pure Proxy) fv
260− . coerce
261−
262−-- | Change the 'From' value of a 'NodeInfo'
263−nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
264−nodeInfoMapFrom f = coerce $ PM.nodeInfoMapFrom (unFrom' . f . From')
265−
266−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
267−-- 'Applicative', 'Monad', etc.) action to get the new value
268−nodeInfoMapMFrom
269− :: Functor f
270− => (From k v -> f (From k v))
271− -> NodeInfo k v -> f (NodeInfo k v)
272−nodeInfoMapMFrom f = fmap NodeInfo'
273− . PM.nodeInfoMapMFrom (fmap unFrom' . f . From')
274− . coerce
275−
276−-- | Set the 'To' field of a 'NodeInfo'
277−nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
278−nodeInfoSetTo = coerce . PM.nodeInfoSetTo
279−
280−--
281−-- From
282−--
283−
284−-- | Describe how a key's new value should be produced
285−newtype From k (v :: Type) = From' { unFrom' :: PM.From k (Proxy v) }
286−
287−{-# COMPLETE From_Insert, From_Delete, From_Move #-}
288−
289−-- | Insert the given value here
290−pattern From_Insert :: v -> From k v
291−pattern From_Insert v = From' (PM.From_Insert v)
292−
293−-- | Delete the existing value, if any, from here
294−pattern From_Delete :: From k v
295−pattern From_Delete = From' PM.From_Delete
296−
297−-- | Move the value here from the given key
298−pattern From_Move :: k -> From k v
299−pattern From_Move k = From' (PM.From_Move k Proxy)
300−
301−bitraverseFrom
302− :: Applicative f
303− => (k0 -> f k1)
304− -> (v0 -> f v1)
305− -> From k0 v0 -> f (From k1 v1)
306−bitraverseFrom fk fv = fmap From'
307− . PM.bitraverseFrom fk (\ ~Proxy -> pure Proxy) fv
308− . coerce
309−
310−makeWrapped ''PatchMapWithMove
311−makeWrapped ''NodeInfo
312−makeWrapped ''From
src/Data/Patch/MapWithPatchingMove.hsdeleted−432
@@ -1,432 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE PatternGuards #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE StandaloneDeriving #-}
10−{-# LANGUAGE TemplateHaskell #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−
14−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15−-- another
16−module Data.Patch.MapWithPatchingMove
17− ( PatchMapWithPatchingMove (..)
18− , patchMapWithPatchingMove
19− , patchMapWithPatchingMoveInsertAll
20− , insertMapKey
21− , moveMapKey
22− , swapMapKey
23− , deleteMapKey
24− , unsafePatchMapWithPatchingMove
25− , patchMapWithPatchingMoveNewElements
26− , patchMapWithPatchingMoveNewElementsMap
27− , patchThatSortsMapWith
28− , patchThatChangesAndSortsMapWith
29− , patchThatChangesMap
30−
31− -- * Node Info
32− , NodeInfo (..)
33− , bitraverseNodeInfo
34− , nodeInfoMapFrom
35− , nodeInfoMapMFrom
36− , nodeInfoSetTo
37−
38− -- * From
39− , From(..)
40− , bitraverseFrom
41−
42− -- * To
43− , To
44−
45− -- TODO internals module
46− , Fixup (..)
47− ) where
48−
49−import Data.Patch.Class
50−
51−import Control.Lens hiding (from, to)
52−import Control.Lens.TH (makeWrapped)
53−import Data.Align (align)
54−import Data.Foldable (toList)
55−import Data.Function
56−import Data.List
57−import Data.Map (Map)
58−import qualified Data.Map as Map
59−import Data.Maybe
60−#if !MIN_VERSION_base(4,11,0)
61−import Data.Semigroup (Semigroup (..))
62−#endif
63−import Data.Monoid.DecidablyEmpty
64−import Data.Set (Set)
65−import qualified Data.Set as Set
66−import Data.These (These (..))
67−
68−-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
69−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
70−-- and vice versa. There should never be any unpaired From/To keys.
71−newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
72− { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
73− unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
74− }
75−
76−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
77−deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
78−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
79−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
80−
81−deriving instance ( Ord k
82−#if !MIN_VERSION_base(4,11,0)
83− , Semigroup p
84−#endif
85− , DecidablyEmpty p
86− , Patch p
87− ) => DecidablyEmpty (PatchMapWithPatchingMove k p)
88−
89−-- | Create a 'PatchMapWithPatchingMove', validating it
90−patchMapWithPatchingMove
91− :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
92−patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
93− where valid = forwardLinks == backwardLinks
94− forwardLinks = Map.mapMaybe _nodeInfo_to m
95− backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
96− case _nodeInfo_from p of
97− From_Move from _ -> Just (from, to)
98− _ -> Nothing
99−
100−-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
101−patchMapWithPatchingMoveInsertAll
102− :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
103−patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
104− { _nodeInfo_from = From_Insert v
105− , _nodeInfo_to = Nothing
106− }
107−
108−-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
109−insertMapKey
110− :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
111−insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
112−
113−-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
114−--
115−-- @
116−-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
117−-- @
118−moveMapKey
119− :: ( DecidablyEmpty p
120−#if !MIN_VERSION_base(4,11,0)
121− , Semigroup p
122−#endif
123− , Patch p
124− )
125− => Ord k => k -> k -> PatchMapWithPatchingMove k p
126−moveMapKey src dst
127− | src == dst = mempty
128− | otherwise =
129− PatchMapWithPatchingMove $ Map.fromList
130− [ (dst, NodeInfo (From_Move src mempty) Nothing)
131− , (src, NodeInfo From_Delete (Just dst))
132− ]
133−
134−-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
135−--
136−-- @
137−-- let aMay = Map.lookup a map
138−-- bMay = Map.lookup b map
139−-- in maybe id (Map.insert a) (bMay <> aMay)
140−-- . maybe id (Map.insert b) (aMay <> bMay)
141−-- . Map.delete a . Map.delete b $ map
142−-- @
143−swapMapKey
144− :: ( DecidablyEmpty p
145−#if !MIN_VERSION_base(4,11,0)
146− , Semigroup p
147−#endif
148− , Patch p
149− )
150− => Ord k => k -> k -> PatchMapWithPatchingMove k p
151−swapMapKey src dst
152− | src == dst = mempty
153− | otherwise =
154− PatchMapWithPatchingMove $ Map.fromList
155− [ (dst, NodeInfo (From_Move src mempty) (Just src))
156− , (src, NodeInfo (From_Move dst mempty) (Just dst))
157− ]
158−
159−-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160−-- the mapping, equivalent to 'Map.delete'.
161−deleteMapKey
162− :: k -> PatchMapWithPatchingMove k v
163−deleteMapKey k = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo From_Delete Nothing
164−
165−-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithPatchingMove' k v@, without checking any invariants.
166−--
167−-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithPatchingMove' are preserved; they will not be checked.
168−unsafePatchMapWithPatchingMove
169− :: Map k (NodeInfo k p) -> PatchMapWithPatchingMove k p
170−unsafePatchMapWithPatchingMove = PatchMapWithPatchingMove
171−
172−-- | Apply the insertions, deletions, and moves to a given 'Map'
173−instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
174− type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
175− -- TODO: return Nothing sometimes
176− -- Note: the strict application here is critical to ensuring that incremental
177− -- merges don't hold onto all their prerequisite events forever; can we make
178− -- this more robust?
179− apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
180− where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
181− From_Insert v -> Just v
182− From_Move k p -> applyAlways p <$> Map.lookup k old
183− From_Delete -> Nothing
184− deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
185− From_Delete -> Just ()
186− _ -> Nothing
187−
188−-- | Returns all the new elements that will be added to the 'Map'
189−patchMapWithPatchingMoveNewElements
190− :: PatchMapWithPatchingMove k p -> [PatchTarget p]
191−patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
192−
193−-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
194−patchMapWithPatchingMoveNewElementsMap
195− :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
196−patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
197− where f ni = case _nodeInfo_from ni of
198− From_Insert v -> Just v
199− From_Move _ _ -> Nothing
200− From_Delete -> Nothing
201−
202−-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
203−-- its values using the given ordering function. The set keys of the 'Map' is
204−-- not changed.
205−patchThatSortsMapWith
206− :: (Ord k, Monoid p)
207− => (PatchTarget p -> PatchTarget p -> Ordering)
208− -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
209−patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
210− where unsorted = Map.toList m
211− sorted = sortBy (cmp `on` snd) unsorted
212− f (to, _) (from, _) = if to == from then Nothing else
213− Just (from, to)
214− reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
215− g (to, _) (from, _) = if to == from then Nothing else
216− let Just movingTo = Map.lookup from reverseMapping
217− in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
218−
219−-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
220−-- will produce a 'Map' with the same values as the second 'Map' but with the
221−-- values sorted with the given ordering function.
222−patchThatChangesAndSortsMapWith
223− :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
224− => (PatchTarget p -> PatchTarget p -> Ordering)
225− -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
226−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
227− where newList = Map.toList newByIndexUnsorted
228− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
229−
230−-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
231−-- will produce the second 'Map'.
232−-- Note: this will never produce a patch on a value.
233−patchThatChangesMap
234− :: forall k p
235− . (Ord k, Ord (PatchTarget p), Monoid p)
236− => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
237−patchThatChangesMap oldByIndex newByIndex = patch
238− where invert :: Map k (PatchTarget p) -> Map (PatchTarget p) (Set k)
239− invert = Map.fromListWith (<>) . fmap (\(k, v) -> (v, Set.singleton k)) . Map.toList
240− -- In the places where we use unionDistinct, a non-distinct key indicates a bug in this function
241− unionDistinct :: forall k' v'. Ord k' => Map k' v' -> Map k' v' -> Map k' v'
242− unionDistinct = Map.unionWith (error "patchThatChangesMap: non-distinct keys")
243− unionPairDistinct :: (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k))
244− unionPairDistinct (oldFroms, oldTos) (newFroms, newTos) = (unionDistinct oldFroms newFroms, unionDistinct oldTos newTos)
245− -- Generate patch info for a single value
246− -- Keys that are found in both the old and new sets will not be patched
247− -- Keys that are found in only the old set will be moved to a new position if any are available; otherwise they will be deleted
248− -- Keys that are found in only the new set will be populated by moving an old key if any are available; otherwise they will be inserted
249− patchSingleValue :: PatchTarget p -> Set k -> Set k -> (Map k (From k p), Map k (To k))
250− patchSingleValue v oldKeys newKeys = foldl' unionPairDistinct mempty $ align (toList $ oldKeys `Set.difference` newKeys) (toList $ newKeys `Set.difference` oldKeys) <&> \case
251− This oldK -> (mempty, Map.singleton oldK Nothing) -- There's nowhere for this value to go, so we know we are deleting it
252− That newK -> (Map.singleton newK $ From_Insert v, mempty) -- There's nowhere fo this value to come from, so we know we are inserting it
253− These oldK newK -> (Map.singleton newK $ From_Move oldK mempty, Map.singleton oldK $ Just newK)
254− -- Run patchSingleValue on a These. Missing old or new sets are considered empty
255− patchSingleValueThese :: PatchTarget p -> These (Set k) (Set k) -> (Map k (From k p), Map k (To k))
256− patchSingleValueThese v = \case
257− This oldKeys -> patchSingleValue v oldKeys mempty
258− That newKeys -> patchSingleValue v mempty newKeys
259− These oldKeys newKeys -> patchSingleValue v oldKeys newKeys
260− -- Generate froms and tos for all values, then merge them together
261− (froms, tos) = foldl' unionPairDistinct mempty $ Map.mapWithKey patchSingleValueThese $ align (invert oldByIndex) (invert newByIndex)
262− patch = unsafePatchMapWithPatchingMove $ align froms tos <&> \case
263− This from -> NodeInfo from Nothing -- Since we don't have a 'to' record for this key, that must mean it isn't being moved anywhere, so it should be deleted.
264− That to -> NodeInfo From_Delete to -- Since we don't have a 'from' record for this key, it must be getting deleted
265− These from to -> NodeInfo from to
266−
267−--
268−-- NodeInfo
269−--
270−
271−-- | Holds the information about each key: where its new value should come from,
272−-- and where its old value should go to
273−data NodeInfo k p = NodeInfo
274− { _nodeInfo_from :: !(From k p)
275− -- ^ Where do we get the new value for this key?
276− , _nodeInfo_to :: !(To k)
277− -- ^ If the old value is being kept (i.e. moved rather than deleted or
278− -- replaced), where is it going?
279− }
280−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
281−deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
282−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
283−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
284−
285−-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
286−-- the type families here, this doesn't it any bi- or tri-traversal class.
287−bitraverseNodeInfo
288− :: Applicative f
289− => (k0 -> f k1)
290− -> (p0 -> f p1)
291− -> (PatchTarget p0 -> f (PatchTarget p1))
292− -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
293−bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
294− <$> bitraverseFrom fk fp fpt from
295− <*> traverse fk to
296−
297−-- | Change the 'From' value of a 'NodeInfo'
298−nodeInfoMapFrom
299− :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
300−nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
301−
302−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
303−-- 'Applicative', 'Monad', etc.) action to get the new value
304−nodeInfoMapMFrom
305− :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
306−nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
307−
308−-- | Set the 'To' field of a 'NodeInfo'
309−nodeInfoSetTo
310− :: To k -> NodeInfo k v -> NodeInfo k v
311−nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
312−
313−--
314−-- From
315−--
316−
317−-- | Describe how a key's new value should be produced
318−data From k p
319− = From_Insert (PatchTarget p) -- ^ Insert the given value here
320− | From_Delete -- ^ Delete the existing value, if any, from here
321− | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
322−
323−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
324−deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
325−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
326−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
327−
328−-- | Traverse the 'From' over the key, patch, and patch target. Because of
329−-- the type families here, this doesn't it any bi- or tri-traversal class.
330−bitraverseFrom
331− :: Applicative f
332− => (k0 -> f k1)
333− -> (p0 -> f p1)
334− -> (PatchTarget p0 -> f (PatchTarget p1))
335− -> From k0 p0 -> f (From k1 p1)
336−bitraverseFrom fk fp fpt = \case
337− From_Insert pt -> From_Insert <$> fpt pt
338− From_Delete -> pure From_Delete
339− From_Move k p -> From_Move <$> fk k <*> fp p
340−
341−--
342−-- To
343−--
344−
345−-- | Describe where a key's old value will go. If this is 'Just', that means
346−-- the key's old value will be moved to the given other key; if it is 'Nothing',
347−-- that means it will be deleted.
348−type To = Maybe
349−
350−--
351−-- Fixup
352−--
353−
354−-- | Helper data structure used for composing patches using the monoid instance.
355−data Fixup k v
356− = Fixup_Delete
357− | Fixup_Update (These (From k v) (To k))
358−
359−-- | Compose patches having the same effect as applying the patches in turn:
360−-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
361−instance ( Ord k
362−#if !MIN_VERSION_base(4,11,0)
363− , Semigroup p
364−#endif
365− , DecidablyEmpty p
366− , Patch p
367− ) => Semigroup (PatchMapWithPatchingMove k p) where
368− PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
369− where
370− connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
371− h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
372− h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
373− (Just toAfter, From_Move fromBefore p)
374− | fromBefore == toAfter && isEmpty p
375− -> [(toAfter, Fixup_Delete)]
376− | otherwise
377− -> [ (toAfter, Fixup_Update (This editBefore))
378− , (fromBefore, Fixup_Update (That mToAfter))
379− ]
380− (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
381− (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
382− (Nothing, _) -> []
383− mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
384− mergeFixups _ (Fixup_Update a) (Fixup_Update b)
385− | This x <- a, That y <- b
386− = Fixup_Update $ These x y
387− | That y <- a, This x <- b
388− = Fixup_Update $ These x y
389− mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
390− fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
391− combineNodeInfos _ nia nib = NodeInfo
392− { _nodeInfo_from = _nodeInfo_from nia
393− , _nodeInfo_to = _nodeInfo_to nib
394− }
395− applyFixup _ ni = \case
396− Fixup_Delete -> Nothing
397− Fixup_Update u -> Just $ NodeInfo
398− { _nodeInfo_from = case _nodeInfo_from ni of
399− f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
400− Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
401− Just (From_Insert v) -> From_Insert $ applyAlways p' v
402− Just From_Delete -> From_Delete
403− Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
404− _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
405− , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
406− }
407− m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
408− getHere :: These a b -> Maybe a
409− getHere = \case
410− This a -> Just a
411− These a _ -> Just a
412− That _ -> Nothing
413− getThere :: These a b -> Maybe b
414− getThere = \case
415− This _ -> Nothing
416− These _ b -> Just b
417− That b -> Just b
418−
419−--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
420−-- | Compose patches having the same effect as applying the patches in turn:
421−-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
422−instance ( Ord k
423−#if !MIN_VERSION_base(4,11,0)
424− , Semigroup p
425−#endif
426− , DecidablyEmpty p
427− , Patch p
428− ) => Monoid (PatchMapWithPatchingMove k p) where
429− mempty = PatchMapWithPatchingMove mempty
430− mappend = (<>)
431−
432−makeWrapped ''PatchMapWithPatchingMove
src/Data/Semigroup/Additive.hsdeleted−54
@@ -1,54 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE TypeOperators #-}
3−{-# LANGUAGE TypeFamilies #-}
4−-- |
5−-- Module:
6−-- Data.Semigroup.Additive
7−-- Description:
8−-- This module defines a class for commutative semigroups, until it is moved
9−-- to another library.
10−module Data.Semigroup.Additive
11− ( Additive
12− ) where
13−
14−import Data.Functor.Const (Const (..))
15−import Data.Functor.Identity
16−import Data.Proxy
17−#if !MIN_VERSION_base(4,12,0)
18−-- for :*: and :.: semigroup instances
19−import Data.Orphans ()
20−#endif
21−#if !MIN_VERSION_base(4,11,0)
22−import Data.Semigroup (Semigroup (..))
23−#endif
24−import GHC.Generics
25−
26−-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
27−class Semigroup q => Additive q where
28−
29−-- | Trivial additive semigroup.
30−instance Additive ()
31−
32−-- | Product additive semigroup.
33−-- A Pair of additive semigroups gives rise to a additive semigroup
34−instance (Additive a, Additive b) => Additive (a, b)
35−
36−-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
37−-- Base does not define Monoid (Compose f g a) so this is the best we can
38−-- really do for functor composition.
39−instance Additive (f (g a)) => Additive ((f :.: g) a)
40−
41−-- | Product of additive semigroups, Functor style.
42−instance (Additive (f a), Additive (g a)) => Additive ((f :*: g) a)
43−
44−-- | Trivial additive semigroup, Functor style
45−instance Additive (Proxy x)
46−
47−-- | Const lifts additive semigroups into a functor.
48−instance Additive a => Additive (Const a x)
49−
50−-- | Identity lifts additive semigroups pointwise (at only one point)
51−instance Additive a => Additive (Identity a)
52−
53−-- | Functions lift additive semigroups pointwise.
54−instance Additive b => Additive (a -> b)
src/Reflex.hsnew file+10
@@ -0,0 +1,10 @@
1+module Reflex ( module Reflex.Class
2+ , module Reflex.Dynamic
3+ , module Reflex.Dynamic.TH
4+ , module Reflex.Spider
5+ ) where
6+
7+import Reflex.Class
8+import Reflex.Dynamic
9+import Reflex.Dynamic.TH
10+import Reflex.Spider
src/Reflex/Class.hsnew file+240
@@ -0,0 +1,240 @@
1+{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RankNTypes, GADTs, ScopedTypeVariables, FunctionalDependencies, RecursiveDo, UndecidableInstances, GeneralizedNewtypeDeriving, StandaloneDeriving, EmptyDataDecls, NoMonomorphismRestriction, TypeOperators, DeriveDataTypeable, PackageImports, TemplateHaskell, LambdaCase #-}
2+module Reflex.Class where
3+
4+import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl)
5+
6+import Control.Monad.Identity hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
7+import Control.Monad.State.Strict hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
8+import Control.Monad.Reader hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
9+import Control.Monad.Writer hiding (mapM, mapM_, forM, forM_, sequence, sequence_, (<>))
10+import Data.List.NonEmpty (NonEmpty (..))
11+import Data.These
12+import Data.Align
13+import Data.GADT.Compare (GEq (..), (:~:) (..))
14+import Data.GADT.Show (GShow (..))
15+import Data.Dependent.Sum (ShowTag (..))
16+import Data.Map (Map)
17+import qualified Data.Map as Map
18+import Data.Dependent.Map (DMap, DSum (..), GCompare (..), GOrdering (..))
19+import qualified Data.Dependent.Map as DMap
20+import Data.Functor.Misc
21+import Data.Semigroup
22+
23+import Debug.Trace (trace)
24+
25+class (MonadHold t (PushM t), MonadSample t (PullM t), Functor (Event t), Functor (Behavior t)) => Reflex t where
26+ -- | A container for a value that can change over time. Behaviors can be sampled at will, but it is not possible to be notified when they change
27+ data Behavior t :: * -> *
28+ -- | A stream of occurrences. During any given frame, an Event is either occurring or not occurring; if it is occurring, it will contain a value of the given type (its "occurrence type")
29+ data Event t :: * -> *
30+ -- | An Event with no occurrences
31+ never :: Event t a
32+ -- | Create a Behavior that always has the given value
33+ 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 Behaviors doesn't have a negative performance impact
34+ -- | Create an Event from another Event; the provided function can sample Behaviors and hold Events, and use the results to produce a occurring (Just) or non-occurring (Nothing) result
35+ push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
36+ -- | A monad for doing complex push-based calculations efficiently
37+ type PushM t :: * -> *
38+ -- | Create a Behavior by reading from other Behaviors; the result will be recomputed whenever any of the read Behaviors changes
39+ pull :: PullM t a -> Behavior t a
40+ -- | A monad for doing complex pull-based calculations efficiently
41+ type PullM t :: * -> *
42+ -- | Merge a collection of events; the resulting Event will only occur if at least one input event is occuring, and will contain all of the input keys that are occurring simultaneously
43+ merge :: GCompare k => DMap (WrapArg (Event t) k) -> Event t (DMap k) --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
44+ -- | Efficiently fan-out an event to many destinations. This function should be partially applied, and then the result applied repeatedly to create child events
45+ fan :: GCompare k => Event t (DMap k) -> EventSelector t k --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
46+ -- | Create an Event that will occur whenever the currently-selected input Event occurs
47+ switch :: Behavior t (Event t a) -> Event t a
48+ -- | Create an Event that will occur whenever the input event is occurring and its occurrence value, another Event, is also occurring
49+ coincidence :: Event t (Event t a) -> Event t a
50+
51+class Monad m => MonadSample t m | m -> t where
52+ -- | Get the current value in the Behavior
53+ sample :: Behavior t a -> m a
54+
55+class MonadSample t m => MonadHold t m where
56+ -- | Create a new Behavior whose value will initially be equal to the given value and will be updated whenever the given Event occurs
57+ hold :: a -> Event t a -> m (Behavior t a)
58+
59+newtype EventSelector t k = EventSelector { select :: forall a. k a -> Event t a }
60+
61+--------------------------------------------------------------------------------
62+-- Instances
63+--------------------------------------------------------------------------------
64+
65+instance MonadSample t m => MonadSample t (ReaderT r m) where
66+ sample = lift . sample
67+
68+instance MonadHold t m => MonadHold t (ReaderT r m) where
69+ hold a0 = lift . hold a0
70+
71+--------------------------------------------------------------------------------
72+-- Convenience functions
73+--------------------------------------------------------------------------------
74+
75+pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
76+pushAlways f e = push (liftM Just . f) e
77+
78+ffor :: Functor f => f a -> (a -> b) -> f b
79+ffor = flip fmap
80+
81+instance Reflex t => Functor (Behavior t) where
82+ fmap f = pull . liftM f . sample
83+
84+--TODO: See if there's a better class in the standard libraries already
85+class FunctorMaybe f where
86+ fmapMaybe :: (a -> Maybe b) -> f a -> f b
87+
88+fforMaybe :: FunctorMaybe f => f a -> (a -> Maybe b) -> f b
89+fforMaybe = flip fmapMaybe
90+
91+ffilter :: FunctorMaybe f => (a -> Bool) -> f a -> f a
92+ffilter f = fmapMaybe $ \x -> if f x then Just x else Nothing
93+
94+instance Reflex t => FunctorMaybe (Event t) where
95+ fmapMaybe f = push $ return . f
96+
97+instance Reflex t => Functor (Event t) where
98+ fmap f = fmapMaybe $ Just . f
99+
100+zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
101+zipListWithEvent f l e = do
102+ rec lb <- hold l eTail
103+ let eBoth = flip push e $ \o -> do
104+ l' <- sample lb
105+ return $ case l' of
106+ (h : t) -> Just (f h o, t)
107+ [] -> Nothing
108+ let eTail = fmap snd eBoth
109+ lb `seq` eBoth `seq` eTail `seq` return ()
110+ return $ fmap fst eBoth
111+
112+-- | Replace the occurrence value of the Event with the value of the Behavior at the time of the occurrence
113+tag :: Reflex t => Behavior t b -> Event t a -> Event t b
114+tag b = pushAlways $ \_ -> sample b
115+
116+attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
117+attachWithMaybe f b e = flip push e $ \o -> liftM (flip f o) $ sample b
118+
119+attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
120+attachWith f = attachWithMaybe $ \a b -> Just $ f a b
121+
122+attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
123+attach = attachWith (,)
124+
125+onceE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
126+onceE = headE
127+
128+headE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
129+headE e = do
130+ rec be <- hold e $ fmap (const never) e'
131+ let e' = switch be
132+ e' `seq` return ()
133+ return e'
134+
135+tailE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
136+tailE e = liftM snd $ headTailE e
137+
138+headTailE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a, Event t a)
139+headTailE e = do
140+ eHead <- headE e
141+ be <- hold never $ fmap (const e) eHead
142+ return (eHead, switch be)
143+
144+splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
145+splitE e = (fmap fst e, fmap snd e)
146+
147+traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
148+traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
149+
150+traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
151+traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
152+
153+data EitherTag l r a where
154+ LeftTag :: EitherTag l r l
155+ RightTag :: EitherTag l r r
156+
157+instance GEq (EitherTag l r) where
158+ geq a b = case (a, b) of
159+ (LeftTag, LeftTag) -> Just Refl
160+ (RightTag, RightTag) -> Just Refl
161+ _ -> Nothing
162+
163+instance GCompare (EitherTag l r) where
164+ gcompare a b = case (a, b) of
165+ (LeftTag, LeftTag) -> GEQ
166+ (LeftTag, RightTag) -> GLT
167+ (RightTag, LeftTag) -> GGT
168+ (RightTag, RightTag) -> GEQ
169+
170+instance GShow (EitherTag l r) where
171+ gshowsPrec _ a = case a of
172+ LeftTag -> showString "LeftTag"
173+ RightTag -> showString "RightTag"
174+
175+instance (Show l, Show r) => ShowTag (EitherTag l r) where
176+ showTaggedPrec t n a = case t of
177+ LeftTag -> showsPrec n a
178+ RightTag -> showsPrec n a
179+
180+eitherToDSum :: Either a b -> DSum (EitherTag a b)
181+eitherToDSum = \case
182+ Left a -> LeftTag :=> a
183+ Right b -> RightTag :=> b
184+
185+dsumToEither :: DSum (EitherTag a b) -> Either a b
186+dsumToEither = \case
187+ LeftTag :=> a -> Left a
188+ RightTag :=> b -> Right b
189+
190+dmapToThese :: DMap (EitherTag a b) -> Maybe (These a b)
191+dmapToThese m = case (DMap.lookup LeftTag m, DMap.lookup RightTag m) of
192+ (Nothing, Nothing) -> Nothing
193+ (Just a, Nothing) -> Just $ This a
194+ (Nothing, Just b) -> Just $ That b
195+ (Just a, Just b) -> Just $ These a b
196+
197+appendEvents :: (Reflex t, Monoid a) => Event t a -> Event t a -> Event t a
198+appendEvents e1 e2 = fmap (mergeThese mappend) $ align e1 e2
199+
200+sequenceThese :: Monad m => These (m a) (m b) -> m (These a b)
201+sequenceThese t = case t of
202+ This ma -> liftM This ma
203+ These ma mb -> liftM2 These ma mb
204+ That mb -> liftM That mb
205+
206+instance (Semigroup a, Reflex t) => Monoid (Event t a) where
207+ mempty = never
208+ mappend a b = mconcat [a, b]
209+ mconcat = fmap sconcat . mergeList
210+
211+mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
212+mergeWith f es = fmap (Prelude.foldl1 f . map (\(Const2 _ :=> v) -> v) . DMap.toList) $ merge $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es
213+
214+leftmost :: Reflex t => [Event t a] -> Event t a
215+leftmost = mergeWith const
216+
217+mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
218+mergeList [] = never
219+mergeList es = mergeWith (<>) $ map (fmap (:|[])) es
220+
221+mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
222+mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
223+
224+fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
225+fanMap = fan . fmap mapToDMap
226+
227+-- | Switches to the new event whenever it receives one; the new event is used immediately, on the same frame that it is switched to
228+switchPromptly :: forall t m a. (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
229+switchPromptly ea0 eea = do
230+ bea <- hold ea0 eea
231+ let eLag = switch bea
232+ eCoincidences = coincidence eea
233+ return $ leftmost [eCoincidences, eLag]
234+
235+instance Reflex t => Align (Event t) where
236+ nil = never
237+ align ea eb = fmapMaybe dmapToThese $ merge $ DMap.fromList [WrapArg LeftTag :=> ea, WrapArg RightTag :=> eb]
238+
239+gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
240+gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
src/Reflex/Dynamic.hsnew file+423
@@ -0,0 +1,423 @@
1+{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RankNTypes, GADTs, ScopedTypeVariables, FunctionalDependencies, RecursiveDo, UndecidableInstances, GeneralizedNewtypeDeriving, StandaloneDeriving, EmptyDataDecls, NoMonomorphismRestriction, TypeOperators, DeriveDataTypeable, PackageImports, TemplateHaskell, LambdaCase, DataKinds, PolyKinds #-}
2+module Reflex.Dynamic ( Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update
3+ , current
4+ , updated
5+ , constDyn
6+ , holdDyn
7+ , nubDyn
8+ , count
9+ , toggle
10+ , switchPromptlyDyn
11+ , tagDyn
12+ , attachDyn
13+ , attachDynWith
14+ , attachDynWithMaybe
15+ , mapDyn
16+ , forDyn
17+ , mapDynM
18+ , foldDyn
19+ , foldDynM
20+ , combineDyn
21+ , collectDyn
22+ , mconcatDyn
23+ , distributeDMapOverDyn
24+ , joinDyn
25+ , joinDynThroughMap
26+ , traceDyn
27+ , traceDynWith
28+ , splitDyn
29+ , Demux
30+ , demux
31+ , getDemuxed
32+ -- Things that probably aren't very useful:
33+ , HList (..)
34+ , FHList (..)
35+ , distributeFHListOverDyn
36+ -- Unsafe
37+ , unsafeDynamic
38+ ) where
39+
40+import Reflex.Class
41+import Data.Functor.Misc
42+
43+import Control.Monad
44+import Control.Monad.Fix
45+import Control.Monad.Identity
46+import Data.These
47+import Data.Align
48+import Data.Map (Map)
49+import qualified Data.Map as Map
50+import Data.Dependent.Map (DMap)
51+import qualified Data.Dependent.Map as DMap
52+import Data.Dependent.Sum (DSum (..))
53+import Data.GADT.Compare (GCompare (..), GEq (..), (:~:) (..), GOrdering (..))
54+import Data.Monoid
55+--import Data.HList (HList (..), hBuild)
56+
57+data HList (l::[*]) where
58+ HNil :: HList '[]
59+ HCons :: e -> HList l -> HList (e ': l)
60+
61+infixr 2 `HCons`
62+
63+type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
64+type instance HRevApp '[] l = l
65+type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
66+
67+hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
68+hRevApp HNil l = l
69+hRevApp (HCons x l) l' = hRevApp l (HCons x l')
70+
71+hReverse l = hRevApp l HNil
72+
73+hEnd :: HList l -> HList l
74+hEnd = id
75+
76+hBuild :: (HBuild' '[] r) => r
77+hBuild = hBuild' HNil
78+
79+class HBuild' l r where
80+ hBuild' :: HList l -> r
81+
82+instance (l' ~ HRevApp l '[])
83+ => HBuild' l (HList l') where
84+ hBuild' l = hReverse l
85+
86+instance HBuild' (a ': l) r
87+ => HBuild' l (a->r) where
88+ hBuild' l x = hBuild' (HCons x l)
89+
90+
91+data Dynamic t a
92+ = Dynamic (Behavior t a) (Event t a)
93+
94+unsafeDynamic :: Behavior t a -> Event t a -> Dynamic t a
95+unsafeDynamic = Dynamic
96+
97+current :: Dynamic t a -> Behavior t a
98+current (Dynamic b _) = b
99+
100+updated :: Dynamic t a -> Event t a
101+updated (Dynamic _ e) = e
102+
103+constDyn :: Reflex t => a -> Dynamic t a
104+constDyn x = Dynamic (constant x) never
105+
106+holdDyn :: MonadHold t m => a -> Event t a -> m (Dynamic t a)
107+holdDyn v0 e = do
108+ b <- hold v0 e
109+ return $ Dynamic b e
110+
111+nubDyn :: (Reflex t, Eq a) => Dynamic t a -> Dynamic t a
112+nubDyn d =
113+ let e' = attachWithMaybe (\x x' -> if x' == x then Nothing else Just x') (current d) (updated d)
114+ in Dynamic (current d) e' --TODO: Avoid invalidating the outgoing Behavior
115+
116+{-
117+instance Reflex t => Functor (Dynamic t) where
118+ fmap f d =
119+ let e' = fmap f $ updated d
120+ eb' = push (\b' -> liftM Just $ constant b') e'
121+ b0 = fmap f $ current d
122+
123+-}
124+
125+mapDyn :: (Reflex t, MonadHold t m) => (a -> b) -> Dynamic t a -> m (Dynamic t b)
126+mapDyn f = mapDynM $ return . f
127+
128+forDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> (a -> b) -> m (Dynamic t b)
129+forDyn = flip mapDyn
130+
131+{-# INLINE mapDynM #-}
132+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)
133+mapDynM f d = do
134+ let e' = push (liftM Just . f :: a -> PushM t (Maybe b)) $ updated d
135+ eb' = fmap constant e'
136+ v0 = pull $ f =<< sample (current d)
137+ bb' :: Behavior t (Behavior t b) <- hold v0 eb'
138+ let b' = pull $ sample =<< sample bb'
139+ return $ Dynamic b' e'
140+
141+foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b)
142+foldDyn f = foldDynM (\o v -> return $ f o v)
143+
144+foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b)
145+foldDynM f z e = do
146+ rec let e' = flip push e $ \o -> do
147+ v <- sample b'
148+ liftM Just $ f o v
149+ b' <- hold z e'
150+ return $ Dynamic b' e'
151+
152+count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)
153+count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e
154+
155+toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool)
156+toggle = foldDyn (const not)
157+
158+-- | Switches to the new event whenever it receives one. Switching occurs *before* occurring the inner event.
159+switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
160+switchPromptlyDyn de =
161+ let eLag = switch $ current de
162+ eCoincidences = coincidence $ updated de
163+ in leftmost [eCoincidences, eLag]
164+
165+{-
166+
167+mergeEventsWith :: Reflex t m => (a -> a -> a) -> Event t a -> Event t a -> m (Event t a)
168+mergeEventsWith f ea eb = mapE (mergeThese f) =<< alignEvents ea eb
169+
170+firstE :: (Reflex t m) => [Event t a] -> m (Event t a)
171+firstE [] = return never
172+firstE (h:t) = mergeEventsLeftBiased h =<< firstE t
173+
174+concatEventsWith :: (Reflex t m) => (a -> a -> a) -> [Event t a] -> m (Event t a)
175+concatEventsWith _ [] = return never
176+concatEventsWith _ [e] = return e
177+concatEventsWith f es = mapEM (liftM (foldl1 f . map (\(Const2 _ :=> v) -> v) . DMap.toList) . sequenceDmap) <=< mergeEventDMap $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es
178+--concatEventsWith f (h:t) = mergeEventsWith f h =<< concatEventsWith f t
179+
180+mconcatE :: (Reflex t m, Monoid a) => [Event t a] -> m (Event t a)
181+mconcatE = concatEventsWith mappend
182+-}
183+
184+splitDyn :: (Reflex t, MonadHold t m) => Dynamic t (a, b) -> m (Dynamic t a, Dynamic t b)
185+splitDyn d = liftM2 (,) (mapDyn fst d) (mapDyn snd d)
186+
187+mconcatDyn :: forall t m a. (Reflex t, MonadHold t m, Monoid a) => [Dynamic t a] -> m (Dynamic t a)
188+mconcatDyn es = do
189+ ddm :: Dynamic t (DMap (Const2 Int a)) <- distributeDMapOverDyn $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es
190+ mapDyn (mconcat . map (\(Const2 _ :=> v) -> v) . DMap.toList) ddm
191+
192+distributeDMapOverDyn :: forall t m k. (Reflex t, MonadHold t m, GCompare k) => DMap (WrapArg (Dynamic t) k) -> m (Dynamic t (DMap k))
193+distributeDMapOverDyn dm = case DMap.toList dm of
194+ [] -> return $ constDyn DMap.empty
195+ [WrapArg k :=> v] -> mapDyn (DMap.singleton k) v
196+ _ -> do
197+ let edmPre = merge $ rewrapDMap updated dm
198+ edm :: Event t (DMap k) = flip push edmPre $ \o -> return . Just =<< do
199+ let f _ = \case
200+ This origDyn -> sample $ current origDyn
201+ That _ -> error "distributeDMapOverDyn: should be impossible to have an event occurring that is not present in the original DMap"
202+ These _ (Identity newVal) -> return newVal
203+ sequenceDmap $ combineDMapsWithKey f dm (wrapDMap Identity o)
204+ dm0 :: Behavior t (DMap k) = pull $ do
205+ liftM DMap.fromList $ forM (DMap.toList dm) $ \(WrapArg k :=> dv) -> liftM (k :=>) $ sample $ current dv
206+ bbdm :: Behavior t (Behavior t (DMap k)) <- hold dm0 $ fmap constant edm
207+ let bdm = pull $ sample =<< sample bbdm
208+ return $ Dynamic bdm edm
209+
210+combineDyn :: forall t m a b c. (Reflex t, MonadHold t m) => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> m (Dynamic t c)
211+combineDyn f da db = do
212+ let eab = align (updated da) (updated db)
213+ ec = flip push eab $ \o -> do
214+ (a, b) <- case o of
215+ This a -> do
216+ b <- sample $ current db
217+ return (a, b)
218+ That b -> do
219+ a <- sample $ current da
220+ return (a, b)
221+ These a b -> return (a, b)
222+ return $ Just $ f a b
223+ c0 :: Behavior t c = pull $ liftM2 f (sample $ current da) (sample $ current db)
224+ bbc :: Behavior t (Behavior t c) <- hold c0 $ fmap constant ec
225+ let bc :: Behavior t c = pull $ sample =<< sample bbc
226+ return $ Dynamic bc ec
227+
228+{-
229+tagInnerDyn :: Reflex t => Event t (Dynamic t a) -> Event t a
230+tagInnerDyn e =
231+ let eSlow = push (liftM Just . sample . current) e
232+ eFast = coincidence $ fmap updated e
233+ in leftmost [eFast, eSlow]
234+-}
235+
236+joinDyn :: forall t a. (Reflex t) => Dynamic t (Dynamic t a) -> Dynamic t a
237+joinDyn dd =
238+ let b' = pull $ sample . current =<< sample (current dd)
239+ eOuter :: Event t a = pushAlways (sample . current) $ updated dd
240+ eInner :: Event t a = switch $ fmap updated (current dd)
241+ eBoth :: Event t a = coincidence $ fmap updated (updated dd)
242+ e' = leftmost [eBoth, eOuter, eInner]
243+ in Dynamic b' e'
244+
245+--TODO: Generalize this to functors other than Maps
246+joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)
247+joinDynThroughMap dd =
248+ let b' = pull $ mapM (sample . current) =<< sample (current dd)
249+ eOuter :: Event t (Map k a) = pushAlways (mapM (sample . current)) $ updated dd
250+ eInner :: Event t (Map k a) = attachWith (flip Map.union) b' $ switch $ fmap (mergeMap . fmap updated) (current dd) --Note: the flip is important because Map.union is left-biased
251+ readNonFiring :: MonadSample t m => These (Dynamic t a) a -> m a
252+ readNonFiring = \case
253+ This d -> sample $ current d
254+ That a -> return a
255+ These _ a -> return a
256+ eBoth :: Event t (Map k a) = coincidence $ fmap (\m -> pushAlways (mapM readNonFiring . align m) $ mergeMap $ fmap updated m) (updated dd)
257+ e' = leftmost [eBoth, eOuter, eInner]
258+ in Dynamic b' e'
259+
260+traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a
261+traceDyn s = traceDynWith $ \x -> s <> ": " <> show x
262+
263+traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a
264+traceDynWith f d =
265+ let e' = traceEventWith f $ updated d
266+ in Dynamic (current d) e'
267+
268+tagDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
269+tagDyn = attachDynWith const
270+
271+attachDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
272+attachDyn = attachDynWith (,)
273+
274+attachDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
275+attachDynWith f = attachDynWithMaybe $ \a b -> Just $ f a b
276+
277+attachDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
278+attachDynWithMaybe f d e =
279+ let e' = attach (current d) e
280+ in fforMaybe (align e' $ updated d) $ \case
281+ This (a, b) -> f a b -- Only the tagging event is firing, so use that
282+ These (_, b) a -> f a b -- Both events are firing, so use the newer value
283+ That _ -> Nothing -- The tagging event isn't firing, so don't fire
284+
285+--------------------------------------------------------------------------------
286+-- Demux
287+--------------------------------------------------------------------------------
288+
289+data Demux t k = Demux { demuxValue :: Behavior t k
290+ , demuxSelector :: EventSelector t (Const2 k Bool)
291+ }
292+
293+demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k
294+demux k = Demux (current k) (fan $ attachWith (\k0 k1 -> if k0 == k1 then DMap.empty else DMap.fromList [Const2 k0 :=> False, Const2 k1 :=> True]) (current k) (updated k))
295+
296+--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
297+getDemuxed :: (Reflex t, MonadHold t m, Eq k) => Demux t k -> k -> m (Dynamic t Bool)
298+getDemuxed d k = do
299+ let e = select (demuxSelector d) (Const2 k)
300+ bb <- hold (liftM (==k) $ sample $ demuxValue d) $ fmap return e
301+ let b = pull $ join $ sample bb
302+ return $ Dynamic b e
303+
304+--------------------------------------------------------------------------------
305+-- collectDyn
306+--------------------------------------------------------------------------------
307+
308+--TODO: This whole section is badly in need of cleanup
309+
310+data FHList f l where
311+ FHNil :: FHList f '[]
312+ FHCons :: f e -> FHList f l -> FHList f (e ': l)
313+
314+natMap :: (forall a. f a -> g a) -> FHList f l -> FHList g l
315+natMap f = \case
316+ FHNil -> FHNil
317+ h `FHCons` t -> f h `FHCons` natMap f t
318+
319+sequenceFHList :: Monad m => FHList m l -> m (HList l)
320+sequenceFHList = \case
321+ FHNil -> return HNil
322+ h `FHCons` t -> do
323+ hResult <- h
324+ tResult <- sequenceFHList t
325+ return $ hResult `HCons` tResult
326+
327+instance GEq (HListPtr l) where
328+ HHeadPtr `geq` HHeadPtr = Just Refl
329+ HHeadPtr `geq` HTailPtr _ = Nothing
330+ HTailPtr _ `geq` HHeadPtr = Nothing
331+ HTailPtr a `geq` HTailPtr b = a `geq` b
332+
333+instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dmapTo*HList will break
334+ HHeadPtr `gcompare` HHeadPtr = GEQ
335+ HHeadPtr `gcompare` HTailPtr _ = GLT
336+ HTailPtr _ `gcompare` HHeadPtr = GGT
337+ HTailPtr a `gcompare` HTailPtr b = a `gcompare` b
338+
339+data HListPtr l a where
340+ HHeadPtr :: HListPtr (h ': t) h
341+ HTailPtr :: HListPtr t a -> HListPtr (h ': t) a
342+
343+fhlistToDMap :: forall f l. FHList f l -> DMap (WrapArg f (HListPtr l))
344+fhlistToDMap = DMap.fromList . go
345+ where go :: forall l'. FHList f l' -> [DSum (WrapArg f (HListPtr l'))]
346+ go = \case
347+ FHNil -> []
348+ FHCons h t -> (WrapArg HHeadPtr :=> h) : map (\(WrapArg p :=> v) -> WrapArg (HTailPtr p) :=> v) (go t)
349+
350+class RebuildSortedHList l where
351+ rebuildSortedFHList :: [DSum (WrapArg f (HListPtr l))] -> FHList f l
352+ rebuildSortedHList :: [DSum (HListPtr l)] -> HList l
353+
354+instance RebuildSortedHList '[] where
355+ rebuildSortedFHList [] = FHNil
356+ rebuildSortedHList [] = HNil
357+
358+instance RebuildSortedHList t => RebuildSortedHList (h ': t) where
359+ rebuildSortedFHList ((WrapArg HHeadPtr :=> h) : t) = FHCons h $ rebuildSortedFHList $ map (\(WrapArg (HTailPtr p) :=> v) -> WrapArg p :=> v) t
360+ rebuildSortedHList ((HHeadPtr :=> h) : t) = HCons h $ rebuildSortedHList $ map (\(HTailPtr p :=> v) -> p :=> v) t
361+
362+
363+dmapToFHList :: forall f l. RebuildSortedHList l => DMap (WrapArg f (HListPtr l)) -> FHList f l
364+dmapToFHList = rebuildSortedFHList . DMap.toList
365+
366+dmapToHList :: forall f l. RebuildSortedHList l => DMap (HListPtr l) -> HList l
367+dmapToHList = rebuildSortedHList . DMap.toList
368+
369+distributeFHListOverDyn :: forall t m l. (Reflex t, MonadHold t m, RebuildSortedHList l) => FHList (Dynamic t) l -> m (Dynamic t (HList l))
370+distributeFHListOverDyn l = mapDyn dmapToHList =<< distributeDMapOverDyn (fhlistToDMap l)
371+{-
372+distributeFHListOverDyn l = do
373+ let ec = undefined
374+ c0 = pull $ sequenceFHList $ natMap (sample . current) l
375+ bbc <- hold c0 $ fmap constant ec
376+ let bc = pull $ sample =<< sample bbc
377+ return $ Dynamic bc ec
378+-}
379+
380+class AllAreFunctors (f :: a -> *) (l :: [a]) where
381+ type FunctorList f l :: [*]
382+ toFHList :: HList (FunctorList f l) -> FHList f l
383+ fromFHList :: FHList f l -> HList (FunctorList f l)
384+
385+instance AllAreFunctors f '[] where
386+ type FunctorList f '[] = '[]
387+ toFHList HNil = FHNil
388+ fromFHList FHNil = HNil
389+
390+instance AllAreFunctors f t => AllAreFunctors f (h ': t) where
391+ type FunctorList f (h ': t) = f h ': FunctorList f t
392+ toFHList (a `HCons` b) = a `FHCons` toFHList b
393+ fromFHList (a `FHCons` b) = a `HCons` fromFHList b
394+
395+collectDyn :: ( RebuildSortedHList (HListElems b)
396+ , IsHList a, IsHList b
397+ , AllAreFunctors (Dynamic t) (HListElems b)
398+ , Reflex t, MonadHold t m
399+ , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
400+ ) => a -> m (Dynamic t b)
401+collectDyn ds =
402+ mapDyn fromHList =<< distributeFHListOverDyn (toFHList $ toHList ds)
403+
404+-- Poor man's Generic
405+class IsHList a where
406+ type HListElems a :: [*]
407+ toHList :: a -> HList (HListElems a)
408+ fromHList :: HList (HListElems a) -> a
409+
410+instance IsHList (a, b) where
411+ type HListElems (a, b) = [a, b]
412+ toHList (a, b) = hBuild a b
413+ fromHList (a `HCons` b `HCons` HNil) = (a, b)
414+
415+instance IsHList (a, b, c, d) where
416+ type HListElems (a, b, c, d) = [a, b, c, d]
417+ toHList (a, b, c, d) = hBuild a b c d
418+ fromHList (a `HCons` b `HCons` c `HCons` d `HCons` HNil) = (a, b, c, d)
419+
420+instance IsHList (a, b, c, d, e, f) where
421+ type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]
422+ toHList (a, b, c, d, e, f) = hBuild a b c d e f
423+ fromHList (a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil) = (a, b, c, d, e, f)
src/Reflex/Dynamic/TH.hsnew file+39
@@ -0,0 +1,39 @@
1+{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, TypeOperators, GADTs, EmptyDataDecls #-}
2+module Reflex.Dynamic.TH (qDyn, unqDyn) where
3+
4+import Reflex.Dynamic
5+
6+import Language.Haskell.TH
7+import Data.Data
8+import Control.Monad
9+import Control.Monad.State
10+
11+-- | Quote a Dynamic expression. Within the quoted expression, you can use '$(unqDyn [| x |])' to refer to any expression 'x' of type 'Dynamic t a'; the unquoted result will be of type 'a'
12+qDyn :: Q Exp -> Q Exp
13+qDyn qe = do
14+ e <- qe
15+ let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d
16+ f d = case eqT of
17+ Just (Refl :: d :~: Exp)
18+ | AppE (VarE m) eInner <- d
19+ , m == 'unqMarker
20+ -> do n <- lift $ newName "dyn"
21+ modify ((n, eInner):)
22+ return $ VarE n
23+ _ -> gmapM f d
24+ (e', exprsReversed) <- runStateT (gmapM f e) []
25+ let exprs = reverse exprsReversed
26+ arg = foldr (\a b -> ConE 'FHCons `AppE` a `AppE` b) (ConE 'FHNil) $ map snd exprs
27+ param = foldr (\a b -> ConP 'HCons [VarP a, b]) (ConP 'HNil []) $ map fst exprs
28+ [| mapDyn $(return $ LamE [param] e') =<< distributeFHListOverDyn $(return arg) |]
29+
30+unqDyn :: Q Exp -> Q Exp
31+unqDyn e = [| unqMarker $e |]
32+
33+-- | This type represents an occurrence of unqDyn before it has been processed by qDyn. If you see it in a type error, it probably means that unqDyn has been used outside of a qDyn context.
34+data UnqDyn
35+
36+-- unqMarker must not be exported; it is used only as a way of smuggling data from unqDyn to qDyn
37+--TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery
38+unqMarker :: a -> UnqDyn
39+unqMarker = error "An unqDyn expression was used outside of a qDyn expression"
src/Reflex/Host/Class.hsnew file+56
@@ -0,0 +1,56 @@
1+{-# LANGUAGE ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, FunctionalDependencies #-}
2+module Reflex.Host.Class where
3+
4+import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl)
5+
6+import Reflex.Class
7+
8+import Control.Monad.Identity hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
9+import Control.Monad.State.Strict hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
10+import Control.Monad.Reader hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
11+import Data.Dependent.Sum (DSum)
12+import Control.Monad.Ref
13+
14+class Reflex t => ReflexHost t where
15+ type EventTrigger t :: * -> *
16+ type EventHandle t :: * -> *
17+ type HostFrame t :: * -> *
18+
19+class (ReflexHost t, Monad m) => MonadReadEvent t m | m -> t where
20+ readEvent :: EventHandle t a -> m (Maybe (m a))
21+
22+class (Monad m, ReflexHost t) => MonadReflexCreateTrigger t m | m -> t where
23+ newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)
24+
25+class (Monad m, ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexHost t m | m -> t where
26+ fireEventsAndRead :: [DSum (EventTrigger t)] -> (forall m'. (MonadReadEvent t m') => m' a) -> m a
27+ subscribeEvent :: Event t a -> m (EventHandle t a) --TODO: Return a handle, and use them in fireEventsAnRead
28+ runFrame :: PushM t a -> m a
29+ runHostFrame :: HostFrame t a -> m a
30+
31+fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t)] -> m ()
32+{-# INLINE fireEvents #-}
33+fireEvents dm = fireEventsAndRead dm $ return ()
34+
35+{-# INLINE newEventWithTriggerRef #-}
36+newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
37+newEventWithTriggerRef = do
38+ rt <- newRef Nothing
39+ e <- newEventWithTrigger $ \t -> do
40+ writeRef rt $ Just t
41+ return $ writeRef rt Nothing
42+ return (e, rt)
43+
44+--------------------------------------------------------------------------------
45+-- Instances
46+--------------------------------------------------------------------------------
47+
48+instance (Reflex t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (ReaderT r m) where
49+ newEventWithTrigger initializer = do
50+ r <- ask
51+ lift $ newEventWithTrigger initializer
52+
53+instance (Reflex t, MonadReflexHost t m) => MonadReflexHost t (ReaderT r m) where
54+ fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
55+ subscribeEvent = lift . subscribeEvent
56+ runFrame = lift . runFrame
src/Reflex/Spider.hsnew file+5
@@ -0,0 +1,5 @@
1+module Reflex.Spider ( Spider
2+ , SpiderHost (..) --Temporary, until Widget no longer uses unsafePerformIO
3+ ) where
4+
5+import Reflex.Spider.Internal
src/Reflex/Spider/Internal.hsnew file+1343
@@ -0,0 +1,1343 @@
1+{-# LANGUAGE CPP, ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, LambdaCase #-}
2+module Reflex.Spider.Internal where
3+
4+import Prelude hiding (mapM, mapM_, any, sequence, concat)
5+
6+import qualified Reflex.Class as R
7+import qualified Reflex.Host.Class as R
8+
9+import Data.IORef
10+import System.Mem.Weak
11+import Data.Foldable
12+import Data.Traversable
13+import Control.Monad hiding (mapM, mapM_, forM_, forM, sequence)
14+import Control.Monad.Reader hiding (mapM, mapM_, forM_, forM, sequence)
15+import GHC.Exts
16+import Control.Applicative
17+import Data.Dependent.Map (DMap, DSum (..))
18+import qualified Data.Dependent.Map as DMap
19+import Data.GADT.Compare
20+import Data.Functor.Misc
21+import Data.Maybe
22+import Data.IntMap (IntMap)
23+import qualified Data.IntMap as IntMap
24+import Control.Lens hiding (coerce)
25+import Control.Monad.TypedId
26+import Control.Monad.Ref
27+import Data.Monoid ((<>))
28+
29+import System.IO.Unsafe
30+import Unsafe.Coerce
31+import Control.Monad.Primitive
32+
33+debugPropagate :: Bool
34+
35+debugInvalidateHeight :: Bool
36+
37+class HasNodeId a where
38+ getNodeId :: a -> Int
39+
40+showNodeId :: HasNodeId a => a -> String
41+showNodeId = ("#"<>) . show . getNodeId
42+
43+#ifdef DEBUG
44+
45+#define DEBUG_NODEIDS
46+
47+debugPropagate = True
48+
49+debugInvalidateHeight = True
50+
51+instance HasNodeId (Hold a) where
52+ getNodeId = holdNodeId
53+
54+instance HasNodeId (PushSubscribed a b) where
55+ getNodeId = pushSubscribedNodeId
56+
57+instance HasNodeId (SwitchSubscribed a) where
58+ getNodeId = switchSubscribedNodeId
59+
60+instance HasNodeId (MergeSubscribed a) where
61+ getNodeId = mergeSubscribedNodeId
62+
63+instance HasNodeId (FanSubscribed a) where
64+ getNodeId = fanSubscribedNodeId
65+
66+instance HasNodeId (CoincidenceSubscribed a) where
67+ getNodeId = coincidenceSubscribedNodeId
68+
69+#else
70+
71+debugPropagate = False
72+
73+debugInvalidateHeight = False
74+
75+instance HasNodeId a where
76+ getNodeId = const ""
77+
78+#endif
79+
80+#ifdef DEBUG_NODEIDS
81+{-# NOINLINE nextNodeIdRef #-}
82+nextNodeIdRef :: IORef Int
83+nextNodeIdRef = unsafePerformIO $ newIORef 1
84+
85+{-# NOINLINE unsafeNodeId #-}
86+unsafeNodeId :: a -> Int
87+unsafeNodeId a = unsafePerformIO $ do
88+ touch a
89+ atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
90+#endif
91+
92+--TODO: Figure out why certain things are not 'representational', then make them representational so we can use coerce
93+--type role Hold representational
94+data Hold a
95+ = Hold { holdValue :: !(IORef a)
96+ , holdInvalidators :: !(IORef [Weak Invalidator])
97+ -- We need to use 'Any' for the next two things, because otherwise Hold inherits a nominal role for its 'a' parameter, and we want to be able to use 'coerce'
98+ , holdSubscriber :: !(IORef Any) -- Keeps its subscription alive; for some reason, a regular (or strict) reference to the Subscriber itself wasn't working, so had to use an IORef
99+ , holdParent :: !(IORef Any) -- Keeps its parent alive (will be undefined until the hold is initialized --TODO: Probably shouldn't be an IORef
100+#ifdef DEBUG_NODEIDS
101+ , holdNodeId :: Int
102+#endif
103+ }
104+
105+data EventEnv
106+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment])
107+ , eventEnvHoldInits :: !(IORef [SomeHoldInit])
108+ , eventEnvClears :: !(IORef [SomeMaybeIORef])
109+ , eventEnvCurrentHeight :: !(IORef Int)
110+ , eventEnvCoincidenceInfos :: !(IORef [SomeCoincidenceInfo])
111+ , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge]))
112+ }
113+
114+runEventM :: EventM a -> EventEnv -> IO a
115+runEventM = runReaderT . unEventM
116+
117+askToAssignRef :: EventM (IORef [SomeAssignment])
118+askToAssignRef = EventM $ asks eventEnvAssignments
119+
120+askHoldInitRef :: EventM (IORef [SomeHoldInit])
121+askHoldInitRef = EventM $ asks eventEnvHoldInits
122+
123+getCurrentHeight :: EventM Int
124+getCurrentHeight = EventM $ do
125+ heightRef <- asks eventEnvCurrentHeight
126+ liftIO $ readIORef heightRef
127+
128+putCurrentHeight :: Int -> EventM ()
129+putCurrentHeight h = EventM $ do
130+ heightRef <- asks eventEnvCurrentHeight
131+ liftIO $ writeIORef heightRef h
132+
133+scheduleClear :: IORef (Maybe a) -> EventM ()
134+scheduleClear r = EventM $ do
135+ clears <- asks eventEnvClears
136+ liftIO $ modifyIORef' clears (SomeMaybeIORef r :)
137+
138+scheduleMerge :: Int -> MergeSubscribed a -> EventM ()
139+scheduleMerge height subscribed = EventM $ do
140+ delayedRef <- asks eventEnvDelayedMerges
141+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) height [DelayedMerge subscribed]
142+
143+emitCoincidenceInfo :: SomeCoincidenceInfo -> EventM ()
144+emitCoincidenceInfo sci = EventM $ do
145+ ciRef <- asks eventEnvCoincidenceInfos
146+ liftIO $ modifyIORef' ciRef (sci:)
147+
148+-- Note: hold cannot examine its event until after the phase is over
149+hold :: a -> Event a -> EventM (Behavior a)
150+hold v0 e = do
151+ holdInitRef <- askHoldInitRef
152+ liftIO $ do
153+ valRef <- newIORef v0
154+ invsRef <- newIORef []
155+ parentRef <- newIORef $ error "hold not yet initialized (parent)"
156+ subscriberRef <- newIORef $ error "hold not yet initialized (subscriber)"
157+ let h = Hold
158+ { holdValue = valRef
159+ , holdInvalidators = invsRef
160+ , holdSubscriber = subscriberRef
161+ , holdParent = parentRef
162+#ifdef DEBUG_NODEIDS
163+ , holdNodeId = unsafeNodeId (v0, e)
164+#endif
165+ }
166+ !s = SubscriberHold h
167+ writeIORef subscriberRef $ unsafeCoerce s
168+ modifyIORef' holdInitRef (SomeHoldInit e h :)
169+ return $ BehaviorHold h
170+
171+subscribeHold :: Event a -> Hold a -> EventM ()
172+subscribeHold e h = do
173+ toAssignRef <- askToAssignRef
174+ !s <- liftIO $ liftM unsafeCoerce $ readIORef $ holdSubscriber h -- This must be performed strictly so that the weak pointer points at the actual item
175+ ws <- liftIO $ mkWeakPtrWithDebug s "holdSubscriber"
176+ subd <- subscribe e $ WeakSubscriberSimple ws
177+ liftIO $ writeIORef (holdParent h) $ unsafeCoerce subd
178+ occ <- liftIO $ getEventSubscribedOcc subd
179+ case occ of
180+ Nothing -> return ()
181+ Just o -> liftIO $ modifyIORef' toAssignRef (SomeAssignment h o :)
182+
183+--type role BehaviorM representational
184+-- BehaviorM can sample behaviors
185+newtype BehaviorM a = BehaviorM { unBehaviorM :: ReaderT (Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed])) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
186+
187+data BehaviorSubscribed a
188+ = BehaviorSubscribedHold (Hold a)
189+ | BehaviorSubscribedPull (PullSubscribed a)
190+
191+data SomeBehaviorSubscribed = forall a. SomeBehaviorSubscribed (BehaviorSubscribed a)
192+
193+--type role PullSubscribed representational
194+data PullSubscribed a
195+ = PullSubscribed { pullSubscribedValue :: !a
196+ , pullSubscribedInvalidators :: !(IORef [Weak Invalidator])
197+ , pullSubscribedOwnInvalidator :: !Invalidator
198+ , pullSubscribedParents :: ![SomeBehaviorSubscribed] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
199+ }
200+
201+--type role Pull representational
202+data Pull a
203+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed a)))
204+ , pullCompute :: !(BehaviorM a)
205+ }
206+
207+data Invalidator
208+ = forall a. InvalidatorPull (Pull a)
209+ | forall a. InvalidatorSwitch (SwitchSubscribed a)
210+
211+data RootSubscribed a
212+ = RootSubscribed { rootSubscribedSubscribers :: !(IORef [WeakSubscriber a])
213+ , rootSubscribedOccurrence :: !(IORef (Maybe a)) -- Alias to rootOccurrence
214+ }
215+
216+data Root a
217+ = Root { rootOccurrence :: !(IORef (Maybe a)) -- The currently-firing occurrence of this event
218+ , rootSubscribed :: !(IORef (Maybe (RootSubscribed a)))
219+ , rootInit :: !(RootTrigger a -> IO (IO ()))
220+ }
221+
222+data SomeHoldInit = forall a. SomeHoldInit (Event a) (Hold a)
223+
224+-- EventM can do everything BehaviorM can, plus create holds
225+newtype EventM a = EventM { unEventM :: ReaderT EventEnv IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO) -- 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
226+
227+data PushSubscribed a b
228+ = PushSubscribed { pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are)
229+ , pushSubscribedHeight :: !(IORef Int)
230+ , pushSubscribedSubscribers :: !(IORef [WeakSubscriber b])
231+ , pushSubscribedSelf :: !(Subscriber a) -- Hold this in memory to ensure our WeakReferences don't die
232+ , pushSubscribedParent :: !(EventSubscribed a)
233+#ifdef DEBUG_NODEIDS
234+ , pushSubscribedNodeId :: Int
235+#endif
236+ }
237+
238+data Push a b
239+ = Push { pushCompute :: !(a -> EventM (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed
240+ , pushParent :: !(Event a)
241+ , pushSubscribed :: !(IORef (Maybe (PushSubscribed a b))) --TODO: Can we replace this with an unsafePerformIO thunk?
242+ }
243+
244+data MergeSubscribed k
245+ = MergeSubscribed { mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k)))
246+ , mergeSubscribedAccum :: !(IORef (DMap k)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
247+ , mergeSubscribedHeight :: !(IORef Int)
248+ , mergeSubscribedSubscribers :: !(IORef [WeakSubscriber (DMap k)])
249+ , mergeSubscribedSelf :: !Any -- Hold all our Subscribers in memory
250+ , mergeSubscribedParents :: !(DMap (WrapArg EventSubscribed k))
251+#ifdef DEBUG_NODEIDS
252+ , mergeSubscribedNodeId :: Int
253+#endif
254+ }
255+
256+--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
257+data Merge k
258+ = Merge { mergeParents :: !(DMap (WrapArg Event k))
259+ , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed k))) --TODO: Can we replace this with an unsafePerformIO thunk?
260+ }
261+
262+data FanSubscriberKey k a where
263+ FanSubscriberKey :: k a -> FanSubscriberKey k [WeakSubscriber a]
264+
265+instance GEq k => GEq (FanSubscriberKey k) where
266+ geq (FanSubscriberKey a) (FanSubscriberKey b) = case geq a b of
267+ Nothing -> Nothing
268+ Just Refl -> Just Refl
269+
270+instance GCompare k => GCompare (FanSubscriberKey k) where
271+ gcompare (FanSubscriberKey a) (FanSubscriberKey b) = case gcompare a b of
272+ GLT -> GLT
273+ GEQ -> GEQ
274+ GGT -> GGT
275+
276+data FanSubscribed k
277+ = FanSubscribed { fanSubscribedSubscribers :: !(IORef (DMap (FanSubscriberKey k)))
278+ , fanSubscribedParent :: !(EventSubscribed (DMap k))
279+ , fanSubscribedSelf :: !(Subscriber (DMap k))
280+#ifdef DEBUG_NODEIDS
281+ , fanSubscribedNodeId :: Int
282+#endif
283+ }
284+
285+data Fan k
286+ = Fan { fanParent :: !(Event (DMap k))
287+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed k)))
288+ }
289+
290+data SwitchSubscribed a
291+ = SwitchSubscribed { switchSubscribedOccurrence :: !(IORef (Maybe a))
292+ , switchSubscribedHeight :: !(IORef Int)
293+ , switchSubscribedSubscribers :: !(IORef [WeakSubscriber a])
294+ , switchSubscribedSelf :: !(Subscriber a)
295+ , switchSubscribedSelfWeak :: !(IORef (Weak (Subscriber a)))
296+ , switchSubscribedOwnInvalidator :: !Invalidator
297+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak Invalidator))
298+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed])
299+ , switchSubscribedParent :: !(Behavior (Event a))
300+ , switchSubscribedCurrentParent :: !(IORef (EventSubscribed a))
301+#ifdef DEBUG_NODEIDS
302+ , switchSubscribedNodeId :: Int
303+#endif
304+ }
305+
306+data Switch a
307+ = Switch { switchParent :: !(Behavior (Event a))
308+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed a)))
309+ }
310+
311+data CoincidenceSubscribed a
312+ = CoincidenceSubscribed { coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
313+ , coincidenceSubscribedSubscribers :: !(IORef [WeakSubscriber a])
314+ , coincidenceSubscribedHeight :: !(IORef Int)
315+ , coincidenceSubscribedOuter :: !(Subscriber (Event a))
316+ , coincidenceSubscribedOuterParent :: !(EventSubscribed (Event a))
317+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed a)))
318+#ifdef DEBUG_NODEIDS
319+ , coincidenceSubscribedNodeId :: Int
320+#endif
321+ }
322+
323+data Coincidence a
324+ = Coincidence { coincidenceParent :: !(Event (Event a))
325+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a)))
326+ }
327+
328+data Box a = Box { unBox :: a }
329+
330+--type WeakSubscriber a = Weak (Subscriber a)
331+data WeakSubscriber a
332+ = forall k. GCompare k => WeakSubscriberMerge !(k a) !(Weak (Box (MergeSubscribed k))) --TODO: Can we inline the GCompare?
333+ | WeakSubscriberSimple !(Weak (Subscriber a))
334+
335+showWeakSubscriberType :: WeakSubscriber a -> String
336+showWeakSubscriberType = \case
337+ WeakSubscriberMerge _ _ -> "WeakSubscriberMerge"
338+ WeakSubscriberSimple _ -> "WeakSubscriberSimple"
339+
340+deRefWeakSubscriber :: WeakSubscriber a -> IO (Maybe (Subscriber a))
341+deRefWeakSubscriber ws = case ws of
342+ WeakSubscriberSimple w -> deRefWeak w
343+ WeakSubscriberMerge k w -> liftM (fmap $ SubscriberMerge k . unBox) $ deRefWeak w
344+
345+data Subscriber a
346+ = forall b. SubscriberPush !(a -> EventM (Maybe b)) (PushSubscribed a b)
347+ | forall k. GCompare k => SubscriberMerge !(k a) (MergeSubscribed k) --TODO: Can we inline the GCompare?
348+ | forall k. (GCompare k, a ~ DMap k) => SubscriberFan (FanSubscribed k)
349+ | SubscriberHold !(Hold a)
350+ | SubscriberSwitch (SwitchSubscribed a)
351+ | forall b. a ~ Event b => SubscriberCoincidenceOuter (CoincidenceSubscribed b)
352+ | SubscriberCoincidenceInner (CoincidenceSubscribed a)
353+
354+showSubscriberType :: Subscriber a -> String
355+showSubscriberType = \case
356+ SubscriberPush _ _ -> "SubscriberPush"
357+ SubscriberMerge _ _ -> "SubscriberMerge"
358+ SubscriberFan _ -> "SubscriberFan"
359+ SubscriberHold _ -> "SubscriberHold"
360+ SubscriberSwitch _ -> "SubscriberSwitch"
361+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
362+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
363+
364+data Event a
365+ = EventRoot !(Root a)
366+ | EventNever
367+ | forall b. EventPush !(Push b a)
368+ | forall k. (GCompare k, a ~ DMap k) => EventMerge !(Merge k)
369+ | forall k. GCompare k => EventFan !(k a) !(Fan k)
370+ | EventSwitch !(Switch a)
371+ | EventCoincidence !(Coincidence a)
372+
373+showEventType :: Event a -> String
374+showEventType = \case
375+ EventRoot _ -> "EventRoot"
376+ EventNever -> "EventNever"
377+ EventPush _ -> "EventPush"
378+ EventMerge _ -> "EventMerge"
379+ EventFan _ _ -> "EventFan"
380+ EventSwitch _ -> "EventSwitch"
381+ EventCoincidence _ -> "EventCoincidence"
382+
383+data EventSubscribed a
384+ = EventSubscribedRoot !(RootSubscribed a)
385+ | EventSubscribedNever
386+ | forall b. EventSubscribedPush !(PushSubscribed b a)
387+ | forall k. (GCompare k, a ~ DMap k) => EventSubscribedMerge !(MergeSubscribed k)
388+ | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed k)
389+ | EventSubscribedSwitch !(SwitchSubscribed a)
390+ | EventSubscribedCoincidence !(CoincidenceSubscribed a)
391+
392+--type role Behavior representational
393+data Behavior a
394+ = BehaviorHold !(Hold a)
395+ | BehaviorConst !a
396+ | BehaviorPull !(Pull a)
397+
398+-- ResultM can read behaviors and events
399+type ResultM = EventM
400+
401+{-# NOINLINE unsafeNewIORef #-}
402+unsafeNewIORef :: a -> b -> IORef b
403+unsafeNewIORef _ b = unsafePerformIO $ newIORef b
404+
405+instance Functor Event where
406+ fmap f = push $ return . Just . f
407+
408+instance Functor Behavior where
409+ fmap f = pull . liftM f . readBehaviorTracked
410+
411+{-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
412+push :: (a -> EventM (Maybe b)) -> Event a -> Event b
413+push f e = EventPush $ Push
414+ { pushCompute = f
415+ , pushParent = e
416+ , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
417+ }
418+{-# RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
419+
420+{-# NOINLINE pull #-}
421+pull :: BehaviorM a -> Behavior a
422+pull a = BehaviorPull $ Pull
423+ { pullCompute = a
424+ , pullValue = unsafeNewIORef a Nothing
425+ }
426+{-# RULES "pull/pull" forall a. pull (readBehaviorTracked (pull a)) = pull a #-}
427+
428+{-# NOINLINE switch #-}
429+switch :: Behavior (Event a) -> Event a
430+switch a = EventSwitch $ Switch
431+ { switchParent = a
432+ , switchSubscribed = unsafeNewIORef a Nothing
433+ }
434+{-# RULES "switch/constB" forall e. switch (BehaviorConst e) = e #-}
435+
436+coincidence :: Event (Event a) -> Event a
437+coincidence a = EventCoincidence $ Coincidence
438+ { coincidenceParent = a
439+ , coincidenceSubscribed = unsafeNewIORef a Nothing
440+ }
441+
442+newRoot :: IO (Root a)
443+newRoot = do
444+ occRef <- newIORef Nothing
445+ subscribedRef <- newIORef Nothing
446+ return $ Root
447+ { rootOccurrence = occRef
448+ , rootSubscribed = subscribedRef
449+ , rootInit = const $ return $ return ()
450+ }
451+
452+propagateAndUpdateSubscribersRef subscribersRef a = do
453+ subscribers <- liftIO $ readIORef subscribersRef
454+ liftIO $ writeIORef subscribersRef []
455+ stillAlive <- propagate a subscribers
456+ liftIO $ modifyIORef' subscribersRef (++stillAlive)
457+
458+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
459+run :: [DSum RootTrigger] -> ResultM b -> IO b
460+run roots after = do
461+ when debugPropagate $ putStrLn "Running an event frame"
462+ result <- runFrame $ do
463+ forM_ roots $ \(RootTrigger (_, occRef) :=> a) -> do
464+ liftIO $ writeIORef occRef $ Just a
465+ scheduleClear occRef
466+ forM_ roots $ \(RootTrigger (subscribersRef, _) :=> a) -> do
467+ propagateAndUpdateSubscribersRef subscribersRef a
468+ delayedRef <- EventM $ asks eventEnvDelayedMerges
469+ let go = do
470+ delayed <- liftIO $ readIORef delayedRef
471+ case IntMap.minViewWithKey delayed of
472+ Nothing -> return ()
473+ Just ((currentHeight, current), future) -> do
474+ when debugPropagate $ liftIO $ putStrLn $ "Running height " ++ show currentHeight
475+ putCurrentHeight currentHeight
476+ liftIO $ writeIORef delayedRef future
477+ forM_ current $ \d -> case d of
478+ DelayedMerge subscribed -> do
479+ height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
480+ case height `compare` currentHeight of
481+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
482+ GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
483+ EQ -> do
484+ m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
485+ liftIO $ writeIORef (mergeSubscribedAccum subscribed) DMap.empty
486+ --TODO: Assert that m is not empty
487+ liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m
488+ scheduleClear $ mergeSubscribedOccurrence subscribed
489+ propagateAndUpdateSubscribersRef (mergeSubscribedSubscribers subscribed) m
490+ go
491+ go
492+ putCurrentHeight maxBound
493+ after
494+ when debugPropagate $ putStrLn "Done running an event frame"
495+ return result
496+
497+data SomeMaybeIORef = forall a. SomeMaybeIORef (IORef (Maybe a))
498+
499+data SomeAssignment = forall a. SomeAssignment (Hold a) a
500+
501+data DelayedMerge = forall k. DelayedMerge (MergeSubscribed k)
502+
503+debugFinalize :: Bool
504+debugFinalize = False
505+
506+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
507+mkWeakPtrWithDebug x debugNote = mkWeakPtr x $
508+ if debugFinalize
509+ then Just $ putStrLn $ "finalizing: " ++ debugNote
510+ else Nothing
511+
512+type WeakList a = [Weak a]
513+
514+--TODO: Is it faster to clean up every time, or to occasionally go through and clean up as needed?
515+traverseAndCleanWeakList_ :: Monad m => (wa -> m (Maybe a)) -> [wa] -> (a -> m ()) -> m [wa]
516+traverseAndCleanWeakList_ deRef ws f = go ws
517+ where go [] = return []
518+ go (h:t) = do
519+ ma <- deRef h
520+ case ma of
521+ Just a -> do
522+ f a
523+ t' <- go t
524+ return $ h : t'
525+ Nothing -> go t
526+
527+-- | Propagate everything at the current height
528+propagate :: a -> [WeakSubscriber a] -> EventM [WeakSubscriber a]
529+propagate a subscribers = do
530+ traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subscribers $ \s -> case s of
531+ SubscriberPush compute subscribed -> do
532+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberPush" <> showNodeId subscribed
533+ occ <- compute a
534+ case occ of
535+ Nothing -> return () -- No need to write a Nothing back into the Ref
536+ Just o -> do
537+ liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
538+ scheduleClear $ pushSubscribedOccurrence subscribed
539+ liftIO . writeIORef (pushSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (pushSubscribedSubscribers subscribed))
540+ SubscriberMerge k subscribed -> do
541+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberMerge" <> showNodeId subscribed
542+ oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
543+ liftIO $ writeIORef (mergeSubscribedAccum subscribed) $ DMap.insertWith (error "Same key fired multiple times for") k a oldM
544+ when (DMap.null oldM) $ do -- Only schedule the firing once
545+ height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
546+ --TODO: assertions about height
547+ currentHeight <- getCurrentHeight
548+ when (height <= currentHeight) $ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")"
549+ scheduleMerge height subscribed
550+ SubscriberFan subscribed -> do
551+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
552+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
553+ --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large
554+ forM_ (DMap.toList a) $ \(k :=> v) -> case DMap.lookup (FanSubscriberKey k) subs of
555+ Nothing -> do
556+ when debugPropagate $ liftIO $ putStrLn "No subscriber for key"
557+ return ()
558+ Just subsubs -> do
559+ _ <- propagate v subsubs --TODO: use the value of this
560+ return ()
561+ --TODO: The following is way too slow to do all the time
562+ subs' <- liftIO $ forM (DMap.toList subs) $ ((\(FanSubscriberKey k :=> subsubs) -> do
563+ subsubs' <- traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subsubs (const $ return ())
564+ return $ if null subsubs' then Nothing else Just $ FanSubscriberKey k :=> subsubs') :: DSum (FanSubscriberKey k) -> IO (Maybe (DSum (FanSubscriberKey k))))
565+ liftIO $ writeIORef (fanSubscribedSubscribers subscribed) $ DMap.fromDistinctAscList $ catMaybes subs'
566+ SubscriberHold h -> do
567+ invalidators <- liftIO $ readIORef $ holdInvalidators h
568+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
569+ toAssignRef <- askToAssignRef
570+ liftIO $ modifyIORef' toAssignRef (SomeAssignment h a :)
571+ SubscriberSwitch subscribed -> do
572+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberSwitch" <> showNodeId subscribed
573+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
574+ scheduleClear $ switchSubscribedOccurrence subscribed
575+ subs <- liftIO $ readIORef $ switchSubscribedSubscribers subscribed
576+ liftIO . writeIORef (switchSubscribedSubscribers subscribed) =<< propagate a subs
577+ SubscriberCoincidenceOuter subscribed -> do
578+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
579+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
580+ when debugPropagate $ liftIO $ putStrLn $ " outerHeight = " <> show outerHeight
581+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
582+ when debugPropagate $ liftIO $ putStrLn $ " isJust occ = " <> show (isJust occ)
583+ when debugPropagate $ liftIO $ putStrLn $ " innerHeight = " <> show innerHeight
584+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
585+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
586+ case occ of
587+ Nothing -> do
588+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
589+ writeIORef (coincidenceSubscribedHeight subscribed) innerHeight
590+ mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
591+ mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
592+ Just o -> do -- Since it's already firing, no need to adjust height
593+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
594+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
595+ liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed))
596+ SubscriberCoincidenceInner subscribed -> do
597+ when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceInner" <> showNodeId subscribed
598+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
599+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
600+ liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate a =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed))
601+
602+data SomeCoincidenceInfo = forall a. SomeCoincidenceInfo (Weak (Subscriber a)) (Subscriber a) (Maybe (CoincidenceSubscribed a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
603+
604+subscribeCoincidenceInner :: Event a -> Int -> CoincidenceSubscribed a -> EventM (Maybe a, Int, EventSubscribed a)
605+subscribeCoincidenceInner o outerHeight subscribedUnsafe = do
606+ let !subInner = SubscriberCoincidenceInner subscribedUnsafe
607+ wsubInner <- liftIO $ mkWeakPtrWithDebug subInner "SubscriberCoincidenceInner"
608+ innerSubd <- {-# SCC "innerSubd" #-} (subscribe o $ WeakSubscriberSimple wsubInner)
609+ innerOcc <- liftIO $ getEventSubscribedOcc innerSubd
610+ innerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef innerSubd
611+ let height = max innerHeight outerHeight
612+ emitCoincidenceInfo $ SomeCoincidenceInfo wsubInner subInner $ if height > outerHeight then Just subscribedUnsafe else Nothing
613+ return (innerOcc, height, innerSubd)
614+
615+readBehavior :: Behavior a -> IO a
616+readBehavior b = runBehaviorM (readBehaviorTracked b) Nothing --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
617+
618+runBehaviorM :: BehaviorM a -> Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]) -> IO a
619+runBehaviorM a mwi = runReaderT (unBehaviorM a) mwi
620+
621+askInvalidator :: BehaviorM (Maybe (Weak Invalidator))
622+askInvalidator = liftM (fmap fst) $ BehaviorM ask
623+
624+askParentsRef :: BehaviorM (Maybe (IORef [SomeBehaviorSubscribed]))
625+askParentsRef = liftM (fmap snd) $ BehaviorM ask
626+
627+readBehaviorTracked :: Behavior a -> BehaviorM a
628+readBehaviorTracked b = case b of
629+ BehaviorHold h -> do
630+ result <- liftIO $ readIORef $ holdValue h
631+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
632+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
633+ liftIO $ touch $ holdSubscriber h
634+ return result
635+ BehaviorConst a -> return a
636+ BehaviorPull p -> do
637+ val <- liftIO $ readIORef $ pullValue p
638+ case val of
639+ Just subscribed -> do
640+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
641+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
642+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
643+ return $ pullSubscribedValue subscribed
644+ Nothing -> do
645+ let !i = InvalidatorPull p
646+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
647+ parentsRef <- liftIO $ newIORef []
648+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) $ Just (wi, parentsRef)
649+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
650+ parents <- liftIO $ readIORef parentsRef
651+ let subscribed = PullSubscribed
652+ { pullSubscribedValue = a
653+ , pullSubscribedInvalidators = invsRef
654+ , pullSubscribedOwnInvalidator = i
655+ , pullSubscribedParents = parents
656+ }
657+ liftIO $ writeIORef (pullValue p) $ Just subscribed
658+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
659+ return a
660+
661+readEvent :: Event a -> ResultM (Maybe a)
662+readEvent e = case e of
663+ EventRoot r -> liftIO $ readIORef $ rootOccurrence r
664+ EventNever -> return Nothing
665+ EventPush p -> do
666+ subscribed <- getPushSubscribed p
667+ liftIO $ do
668+ result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid
669+ touch $ pushSubscribedSelf subscribed
670+ return result
671+ EventMerge m -> do
672+ subscribed <- getMergeSubscribed m
673+ liftIO $ do
674+ result <- readIORef $ mergeSubscribedOccurrence subscribed
675+ touch $ mergeSubscribedSelf subscribed
676+ return result
677+ EventFan k f -> do
678+ parentOcc <- readEvent $ fanParent f
679+ return $ DMap.lookup k =<< parentOcc
680+ EventSwitch s -> do
681+ subscribed <- getSwitchSubscribed s
682+ liftIO $ do
683+ result <- readIORef $ switchSubscribedOccurrence subscribed
684+ touch $ switchSubscribedSelf subscribed
685+ touch $ switchSubscribedOwnInvalidator subscribed
686+ return result
687+ EventCoincidence c -> do
688+ subscribed <- getCoincidenceSubscribed c
689+ liftIO $ do
690+ result <- readIORef $ coincidenceSubscribedOccurrence subscribed
691+ touch $ coincidenceSubscribedOuter subscribed
692+ --TODO: do we need to touch the inner subscriber?
693+ return result
694+
695+-- Always refers to 0
696+{-# NOINLINE zeroRef #-}
697+zeroRef :: IORef Int
698+zeroRef = unsafePerformIO $ newIORef 0
699+
700+getEventSubscribed :: Event a -> EventM (EventSubscribed a)
701+getEventSubscribed e = case e of
702+ EventRoot r -> liftM EventSubscribedRoot $ getRootSubscribed r
703+ EventNever -> return EventSubscribedNever
704+ EventPush p -> liftM EventSubscribedPush $ getPushSubscribed p
705+ EventFan k f -> liftM (EventSubscribedFan k) $ getFanSubscribed f
706+ EventMerge m -> liftM EventSubscribedMerge $ getMergeSubscribed m
707+ EventSwitch s -> liftM EventSubscribedSwitch $ getSwitchSubscribed s
708+ EventCoincidence c -> liftM EventSubscribedCoincidence $ getCoincidenceSubscribed c
709+
710+debugSubscribe :: Bool
711+debugSubscribe = False
712+
713+subscribeEventSubscribed :: EventSubscribed a -> WeakSubscriber a -> IO ()
714+subscribeEventSubscribed es ws = case es of
715+ EventSubscribedRoot r -> do
716+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Root"
717+ modifyIORef' (rootSubscribedSubscribers r) (ws:)
718+ EventSubscribedNever -> do
719+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Never"
720+ return ()
721+ EventSubscribedPush subscribed -> do
722+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Push"
723+ modifyIORef' (pushSubscribedSubscribers subscribed) (ws:)
724+ EventSubscribedFan k subscribed -> do
725+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Fan"
726+ modifyIORef' (fanSubscribedSubscribers subscribed) $ DMap.insertWith (++) (FanSubscriberKey k) [ws]
727+ EventSubscribedMerge subscribed -> do
728+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Merge"
729+ modifyIORef' (mergeSubscribedSubscribers subscribed) (ws:)
730+ EventSubscribedSwitch subscribed -> do
731+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Switch"
732+ modifyIORef' (switchSubscribedSubscribers subscribed) (ws:)
733+ EventSubscribedCoincidence subscribed -> do
734+ when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Coincidence"
735+ modifyIORef' (coincidenceSubscribedSubscribers subscribed) (ws:)
736+
737+getEventSubscribedOcc :: EventSubscribed a -> IO (Maybe a)
738+getEventSubscribedOcc es = case es of
739+ EventSubscribedRoot r -> readIORef $ rootSubscribedOccurrence r
740+ EventSubscribedNever -> return Nothing
741+ EventSubscribedPush subscribed -> readIORef $ pushSubscribedOccurrence subscribed
742+ EventSubscribedFan k subscribed -> do
743+ parentOcc <- getEventSubscribedOcc $ fanSubscribedParent subscribed
744+ let occ = DMap.lookup k =<< parentOcc
745+ return occ
746+ EventSubscribedMerge subscribed -> readIORef $ mergeSubscribedOccurrence subscribed
747+ EventSubscribedSwitch subscribed -> readIORef $ switchSubscribedOccurrence subscribed
748+ EventSubscribedCoincidence subscribed -> readIORef $ coincidenceSubscribedOccurrence subscribed
749+
750+eventSubscribedHeightRef :: EventSubscribed a -> IORef Int
751+eventSubscribedHeightRef es = case es of
752+ EventSubscribedRoot _ -> zeroRef
753+ EventSubscribedNever -> zeroRef
754+ EventSubscribedPush subscribed -> pushSubscribedHeight subscribed
755+ EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ fanSubscribedParent subscribed
756+ EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed
757+ EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed
758+ EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed
759+
760+subscribe :: Event a -> WeakSubscriber a -> EventM (EventSubscribed a)
761+subscribe e ws = do
762+ subd <- getEventSubscribed e
763+ liftIO $ subscribeEventSubscribed subd ws
764+ return subd
765+
766+getRootSubscribed :: Root a -> EventM (RootSubscribed a)
767+getRootSubscribed r = do
768+ mSubscribed <- liftIO $ readIORef $ rootSubscribed r
769+ case mSubscribed of
770+ Just subscribed -> return subscribed
771+ Nothing -> liftIO $ do
772+ subscribersRef <- newIORef []
773+ let !subscribed = RootSubscribed
774+ { rootSubscribedOccurrence = rootOccurrence r
775+ , rootSubscribedSubscribers = subscribersRef
776+ }
777+ -- Strangely, init needs the same stuff as a RootSubscribed has, but it must not be the same as the one that everyone's subscribing to, or it'll leak memory
778+ uninit <- rootInit r $ RootTrigger (subscribersRef, rootOccurrence r)
779+ addFinalizer subscribed $ do
780+-- putStrLn "Uninit root"
781+ uninit
782+ liftIO $ writeIORef (rootSubscribed r) $ Just subscribed
783+ return subscribed
784+
785+-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
786+getPushSubscribed :: Push a b -> EventM (PushSubscribed a b)
787+getPushSubscribed p = do
788+ mSubscribed <- liftIO $ readIORef $ pushSubscribed p
789+ case mSubscribed of
790+ Just subscribed -> return subscribed
791+ Nothing -> do -- Not yet subscribed
792+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ pushSubscribed p
793+ let !s = SubscriberPush (pushCompute p) subscribedUnsafe
794+ ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberPush"
795+ subd <- subscribe (pushParent p) $ WeakSubscriberSimple ws
796+ parentOcc <- liftIO $ getEventSubscribedOcc subd
797+ occ <- liftM join $ mapM (pushCompute p) parentOcc
798+ occRef <- liftIO $ newIORef occ
799+ when (isJust occ) $ scheduleClear occRef
800+ subscribersRef <- liftIO $ newIORef []
801+ let subscribed = PushSubscribed
802+ { pushSubscribedOccurrence = occRef
803+ , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
804+ , pushSubscribedSubscribers = subscribersRef
805+ , pushSubscribedSelf = unsafeCoerce s
806+ , pushSubscribedParent = subd
807+#ifdef DEBUG_NODEIDS
808+ , pushSubscribedNodeId = unsafeNodeId p
809+#endif
810+ }
811+ liftIO $ writeIORef (pushSubscribed p) $ Just subscribed
812+ return subscribed
813+
814+getMergeSubscribed :: forall k. GCompare k => Merge k -> EventM (MergeSubscribed k)
815+getMergeSubscribed m = {-# SCC "getMergeSubscribed.entire" #-} do
816+ mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
817+ case mSubscribed of
818+ Just subscribed -> return subscribed
819+ Nothing -> if DMap.null $ mergeParents m then emptyMergeSubscribed else do
820+ subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
821+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
822+ let !s = Box subscribedUnsafe
823+ ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberMerge"
824+ subscribers :: [(Any, Maybe (DSum k), Int, DSum (WrapArg EventSubscribed k))] <- forM (DMap.toList $ mergeParents m) $ {-# SCC "getMergeSubscribed.a" #-} \(WrapArg k :=> e) -> {-# SCC "getMergeSubscribed.a1" #-} do
825+ parentSubd <- {-# SCC "getMergeSubscribed.a.parentSubd" #-} subscribe e $ WeakSubscriberMerge k ws
826+ parentOcc <- {-# SCC "getMergeSubscribed.a.parentOcc" #-} liftIO $ getEventSubscribedOcc parentSubd
827+ height <- {-# SCC "getMergeSubscribed.a.height" #-} liftIO $ readIORef $ eventSubscribedHeightRef parentSubd
828+ return $ {-# SCC "getMergeSubscribed.a.returnVal" #-} (unsafeCoerce s :: Any, fmap (k :=>) parentOcc, height, WrapArg k :=> parentSubd)
829+ let dm = DMap.fromDistinctAscList $ catMaybes $ map (^._2) subscribers
830+ subscriberHeights = map (^._3) subscribers
831+ myHeight =
832+ if any (==invalidHeight) subscriberHeights --TODO: Replace 'any' with invalidHeight-preserving 'maximum'
833+ then invalidHeight
834+ else succ $ Prelude.maximum subscriberHeights -- This is safe because the DMap will never be empty here
835+ currentHeight <- getCurrentHeight
836+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
837+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
838+ else (Nothing, dm)
839+ when (not $ DMap.null accum) $ do
840+ scheduleMerge myHeight subscribedUnsafe
841+ occRef <- liftIO $ newIORef occ
842+ when (isJust occ) $ scheduleClear occRef
843+ accumRef <- liftIO $ newIORef accum
844+ heightRef <- liftIO $ newIORef myHeight
845+ subsRef <- liftIO $ newIORef []
846+ let subscribed = MergeSubscribed
847+ { mergeSubscribedOccurrence = occRef
848+ , mergeSubscribedAccum = accumRef
849+ , mergeSubscribedHeight = heightRef
850+ , mergeSubscribedSubscribers = subsRef
851+ , mergeSubscribedSelf = unsafeCoerce $ map (\(x, _, _, _) -> x) subscribers --TODO: Does lack of strictness make this leak?
852+ , mergeSubscribedParents = DMap.fromDistinctAscList $ map (^._4) subscribers
853+#ifdef DEBUG_NODEIDS
854+ , mergeSubscribedNodeId = unsafeNodeId m
855+#endif
856+ }
857+ liftIO $ writeIORef subscribedRef subscribed
858+ return subscribed
859+ where emptyMergeSubscribed = do --TODO: This should never happen
860+ occRef <- liftIO $ newIORef Nothing
861+ accumRef <- liftIO $ newIORef DMap.empty
862+ subsRef <- liftIO $ newIORef []
863+ return $ MergeSubscribed
864+ { mergeSubscribedOccurrence = occRef
865+ , mergeSubscribedAccum = accumRef
866+ , mergeSubscribedHeight = zeroRef
867+ , mergeSubscribedSubscribers = subsRef --TODO: This will definitely leak
868+ , mergeSubscribedSelf = unsafeCoerce ()
869+ , mergeSubscribedParents = DMap.empty
870+#ifdef DEBUG_NODEIDS
871+ , mergeSubscribedNodeId = -1
872+#endif
873+ }
874+
875+getFanSubscribed :: GCompare k => Fan k -> EventM (FanSubscribed k)
876+getFanSubscribed f = do
877+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
878+ case mSubscribed of
879+ Just subscribed -> return subscribed
880+ Nothing -> do
881+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ fanSubscribed f
882+ let !sub = SubscriberFan subscribedUnsafe
883+ wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberFan"
884+ subd <- subscribe (fanParent f) $ WeakSubscriberSimple wsub
885+ subscribersRef <- liftIO $ newIORef DMap.empty
886+ let subscribed = FanSubscribed
887+ { fanSubscribedParent = subd
888+ , fanSubscribedSubscribers = subscribersRef
889+ , fanSubscribedSelf = sub
890+#ifdef DEBUG_NODEIDS
891+ , fanSubscribedNodeId = unsafeNodeId f
892+#endif
893+ }
894+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
895+ return subscribed
896+
897+getSwitchSubscribed :: Switch a -> EventM (SwitchSubscribed a)
898+getSwitchSubscribed s = do
899+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
900+ case mSubscribed of
901+ Just subscribed -> return subscribed
902+ Nothing -> do
903+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
904+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
905+ let !i = InvalidatorSwitch subscribedUnsafe
906+ !sub = SubscriberSwitch subscribedUnsafe
907+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
908+ wiRef <- liftIO $ newIORef wi
909+ wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberSwitch"
910+ selfWeakRef <- liftIO $ newIORef wsub
911+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
912+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) $ Just (wi, parentsRef)
913+ subd <- subscribe e $ WeakSubscriberSimple wsub
914+ subdRef <- liftIO $ newIORef subd
915+ parentOcc <- liftIO $ getEventSubscribedOcc subd
916+ occRef <- liftIO $ newIORef parentOcc
917+ when (isJust parentOcc) $ scheduleClear occRef
918+ heightRef <- liftIO $ newIORef =<< readIORef (eventSubscribedHeightRef subd)
919+ subscribersRef <- liftIO $ newIORef []
920+ let subscribed = SwitchSubscribed
921+ { switchSubscribedOccurrence = occRef
922+ , switchSubscribedHeight = heightRef
923+ , switchSubscribedSubscribers = subscribersRef
924+ , switchSubscribedSelf = sub
925+ , switchSubscribedSelfWeak = selfWeakRef
926+ , switchSubscribedOwnInvalidator = i
927+ , switchSubscribedOwnWeakInvalidator = wiRef
928+ , switchSubscribedBehaviorParents = parentsRef
929+ , switchSubscribedParent = switchParent s
930+ , switchSubscribedCurrentParent = subdRef
931+#ifdef DEBUG_NODEIDS
932+ , switchSubscribedNodeId = unsafeNodeId s
933+#endif
934+ }
935+ liftIO $ writeIORef subscribedRef subscribed
936+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
937+ return subscribed
938+
939+getCoincidenceSubscribed :: forall a. Coincidence a -> EventM (CoincidenceSubscribed a)
940+getCoincidenceSubscribed c = do
941+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
942+ case mSubscribed of
943+ Just subscribed -> return subscribed
944+ Nothing -> do
945+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
946+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
947+ let !subOuter = SubscriberCoincidenceOuter subscribedUnsafe
948+ wsubOuter <- liftIO $ mkWeakPtrWithDebug subOuter "subOuter"
949+ outerSubd <- subscribe (coincidenceParent c) $ WeakSubscriberSimple wsubOuter
950+ outerOcc <- liftIO $ getEventSubscribedOcc outerSubd
951+ outerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef outerSubd
952+ (occ, height, mInnerSubd) <- case outerOcc of
953+ Nothing -> return (Nothing, outerHeight, Nothing)
954+ Just o -> do
955+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
956+ return (occ, height, Just innerSubd)
957+ occRef <- liftIO $ newIORef occ
958+ when (isJust occ) $ scheduleClear occRef
959+ heightRef <- liftIO $ newIORef height
960+ innerSubdRef <- liftIO $ newIORef mInnerSubd
961+ scheduleClear innerSubdRef
962+ subscribersRef <- liftIO $ newIORef []
963+ let subscribed = CoincidenceSubscribed
964+ { coincidenceSubscribedOccurrence = occRef
965+ , coincidenceSubscribedHeight = heightRef
966+ , coincidenceSubscribedSubscribers = subscribersRef
967+ , coincidenceSubscribedOuter = subOuter
968+ , coincidenceSubscribedOuterParent = outerSubd
969+ , coincidenceSubscribedInnerParent = innerSubdRef
970+#ifdef DEBUG_NODEIDS
971+ , coincidenceSubscribedNodeId = unsafeNodeId c
972+#endif
973+ }
974+ liftIO $ writeIORef subscribedRef subscribed
975+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
976+ return subscribed
977+
978+merge :: GCompare k => DMap (WrapArg Event k) -> Event (DMap k)
979+merge m = EventMerge $ Merge
980+ { mergeParents = m
981+ , mergeSubscribed = unsafeNewIORef m Nothing
982+ }
983+
984+newtype EventSelector k = EventSelector { select :: forall a. k a -> Event a }
985+
986+fan :: GCompare k => Event (DMap k) -> EventSelector k
987+fan e =
988+ let f = Fan
989+ { fanParent = e
990+ , fanSubscribed = unsafeNewIORef e Nothing
991+ }
992+ in EventSelector $ \k -> EventFan k f
993+
994+-- | Run an event action outside of a frame
995+runFrame :: EventM a -> IO a
996+runFrame a = do
997+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
998+ holdInitRef <- newIORef []
999+ heightRef <- newIORef 0
1000+ toClearRef <- newIORef []
1001+ coincidenceInfosRef <- newIORef []
1002+ delayedRef <- liftIO $ newIORef IntMap.empty
1003+ result <- flip runEventM (EventEnv toAssignRef holdInitRef toClearRef heightRef coincidenceInfosRef delayedRef) $ do
1004+ result <- a
1005+ let runHoldInits = do
1006+ holdInits <- liftIO $ readIORef holdInitRef
1007+ if null holdInits then return () else do
1008+ liftIO $ writeIORef holdInitRef []
1009+ forM_ holdInits $ \(SomeHoldInit e h) -> subscribeHold e h
1010+ runHoldInits
1011+ runHoldInits -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
1012+ return result
1013+ toClear <- readIORef toClearRef
1014+ forM_ toClear $ \(SomeMaybeIORef ref) -> writeIORef ref Nothing
1015+ toAssign <- readIORef toAssignRef
1016+ toReconnectRef <- newIORef []
1017+ forM_ toAssign $ \(SomeAssignment h v) -> do
1018+ writeIORef (holdValue h) v
1019+ writeIORef (holdInvalidators h) =<< invalidate toReconnectRef =<< readIORef (holdInvalidators h)
1020+ coincidenceInfos <- readIORef coincidenceInfosRef
1021+ forM_ coincidenceInfos $ \(SomeCoincidenceInfo wsubInner subInner mcs) -> do
1022+ touch subInner
1023+ finalize wsubInner
1024+ mapM_ invalidateCoincidenceHeight mcs
1025+ toReconnect <- readIORef toReconnectRef
1026+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1027+ wsub <- readIORef $ switchSubscribedSelfWeak subscribed
1028+ finalize wsub
1029+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1030+ finalize wi
1031+ let !i = switchSubscribedOwnInvalidator subscribed
1032+ wi' <- mkWeakPtrWithDebug i "wi'"
1033+ writeIORef (switchSubscribedBehaviorParents subscribed) []
1034+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed))
1035+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1036+ let !sub = switchSubscribedSelf subscribed -- Must be done strictly, or the weak pointer will refer to a useless thunk
1037+ wsub' <- mkWeakPtrWithDebug sub "wsub'"
1038+ writeIORef (switchSubscribedSelfWeak subscribed) wsub'
1039+ subd' <- runFrame $ subscribe e $ WeakSubscriberSimple wsub' --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
1040+ {-
1041+ stackTrace <- liftIO $ liftM renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1042+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1043+ EventRoot _ -> "EventRoot"
1044+ EventNever -> "EventNever"
1045+ _ -> "something else"
1046+ -}
1047+ writeIORef (switchSubscribedCurrentParent subscribed) subd'
1048+ parentHeight <- readIORef $ eventSubscribedHeightRef subd'
1049+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1050+ if parentHeight == myHeight then return () else do
1051+ writeIORef (switchSubscribedHeight subscribed) parentHeight
1052+ mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1053+ forM_ coincidenceInfos $ \(SomeCoincidenceInfo _ _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1054+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1055+ mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1056+ return result
1057+
1058+invalidHeight :: Int
1059+invalidHeight = -1000
1060+
1061+invalidateSubscriberHeight :: WeakSubscriber a -> IO ()
1062+invalidateSubscriberHeight ws = do
1063+ ms <- deRefWeakSubscriber ws
1064+ case ms of
1065+ Nothing -> return () --TODO: cleanup?
1066+ Just s -> case s of
1067+ SubscriberPush _ subscribed -> do
1068+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1069+ mapM_ invalidateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed)
1070+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1071+ SubscriberMerge _ subscribed -> do
1072+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1073+ oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1074+ when (oldHeight /= invalidHeight) $ do
1075+ writeIORef (mergeSubscribedHeight subscribed) $ invalidHeight
1076+ mapM_ invalidateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed)
1077+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1078+ SubscriberFan subscribed -> do
1079+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1080+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1081+ forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ invalidateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ())
1082+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1083+ SubscriberHold _ -> return ()
1084+ SubscriberSwitch subscribed -> do
1085+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1086+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1087+ when (oldHeight /= invalidHeight) $ do
1088+ writeIORef (switchSubscribedHeight subscribed) $ invalidHeight
1089+ mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1090+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1091+ SubscriberCoincidenceOuter subscribed -> do
1092+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1093+ invalidateCoincidenceHeight subscribed
1094+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1095+ SubscriberCoincidenceInner subscribed -> do
1096+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1097+ invalidateCoincidenceHeight subscribed
1098+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1099+
1100+invalidateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
1101+invalidateCoincidenceHeight subscribed = do
1102+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1103+ when (oldHeight /= invalidHeight) $ do
1104+ writeIORef (coincidenceSubscribedHeight subscribed) $ invalidHeight
1105+ mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
1106+
1107+--TODO: The recalculation algorithm seems a bit funky; make sure it doesn't miss stuff or hit stuff twice; also, it should probably be lazy
1108+
1109+recalculateSubscriberHeight :: WeakSubscriber a -> IO ()
1110+recalculateSubscriberHeight ws = do
1111+ ms <- deRefWeakSubscriber ws
1112+ case ms of
1113+ Nothing -> return () --TODO: cleanup?
1114+ Just s -> case s of
1115+ SubscriberPush _ subscribed -> do
1116+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1117+ mapM_ recalculateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed)
1118+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1119+ SubscriberMerge _ subscribed -> do
1120+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1121+ oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1122+ when (oldHeight == invalidHeight) $ do
1123+ height <- calculateMergeHeight subscribed
1124+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1125+ when (height /= invalidHeight) $ do -- If height == invalidHeight, that means some of the prereqs have not yet been recomputed; when they do recompute, they'll catch this node again --TODO: this is O(n*m), where n is the number of children of this noe and m is the number that have been invalidated
1126+ writeIORef (mergeSubscribedHeight subscribed) height
1127+ mapM_ recalculateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed)
1128+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1129+ SubscriberFan subscribed -> do
1130+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1131+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1132+ forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ recalculateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ())
1133+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1134+ SubscriberHold _ -> return ()
1135+ SubscriberSwitch subscribed -> do
1136+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1137+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1138+ when (oldHeight == invalidHeight) $ do
1139+ height <- calculateSwitchHeight subscribed
1140+ when (height /= invalidHeight) $ do
1141+ writeIORef (switchSubscribedHeight subscribed) height
1142+ mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1143+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1144+ SubscriberCoincidenceOuter subscribed -> do
1145+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1146+ void $ recalculateCoincidenceHeight subscribed
1147+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1148+ SubscriberCoincidenceInner subscribed -> do
1149+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1150+ void $ recalculateCoincidenceHeight subscribed
1151+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1152+
1153+recalculateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
1154+recalculateCoincidenceHeight subscribed = do
1155+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1156+ when (oldHeight == invalidHeight) $ do
1157+ height <- calculateCoincidenceHeight subscribed
1158+ when (height /= invalidHeight) $ do
1159+ writeIORef (coincidenceSubscribedHeight subscribed) height
1160+ mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: This should probably be mandatory, just like with the merge and switch ones
1161+
1162+calculateMergeHeight :: MergeSubscribed k -> IO Int
1163+calculateMergeHeight subscribed = if DMap.null (mergeSubscribedParents subscribed) then return 0 else do
1164+ heights <- forM (DMap.toList $ mergeSubscribedParents subscribed) $ \(WrapArg _ :=> es) -> do
1165+ readIORef $ eventSubscribedHeightRef es
1166+ return $ if any (== invalidHeight) heights then invalidHeight else succ $ Prelude.maximum heights --TODO: Replace 'any' with invalidHeight-preserving 'maximum'
1167+
1168+calculateSwitchHeight :: SwitchSubscribed a -> IO Int
1169+calculateSwitchHeight subscribed = readIORef . eventSubscribedHeightRef =<< readIORef (switchSubscribedCurrentParent subscribed)
1170+
1171+calculateCoincidenceHeight :: CoincidenceSubscribed a -> IO Int
1172+calculateCoincidenceHeight subscribed = do
1173+ outerHeight <- readIORef $ eventSubscribedHeightRef $ coincidenceSubscribedOuterParent subscribed
1174+ innerHeight <- maybe (return 0) (readIORef . eventSubscribedHeightRef) =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1175+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1176+
1177+{-
1178+recalculateEventSubscribedHeight :: EventSubscribed a -> IO Int
1179+recalculateEventSubscribedHeight es = case es of
1180+ EventSubscribedRoot _ -> return 0
1181+ EventSubscribedNever -> return 0
1182+ EventSubscribedPush subscribed -> recalculateEventSubscribedHeight $ pushSubscribedParent subscribed
1183+ EventSubscribedMerge subscribed -> do
1184+ oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1185+ if oldHeight /= invalidHeight then return oldHeight else do
1186+ height <- calculateMergeHeight subscribed
1187+ writeIORef (mergeSubscribedHeight subscribed) height
1188+ return height
1189+ EventSubscribedFan _ subscribed -> recalculateEventSubscribedHeight $ fanSubscribedParent subscribed
1190+ EventSubscribedSwitch subscribed -> do
1191+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1192+ if oldHeight /= invalidHeight then return oldHeight else do
1193+ height <- calculateSwitchHeight subscribed
1194+ writeIORef (switchSubscribedHeight subscribed) height
1195+ return height
1196+ EventSubscribedCoincidence subscribed -> recalculateCoincidenceHeight subscribed
1197+-}
1198+
1199+data SomeSwitchSubscribed = forall a. SomeSwitchSubscribed (SwitchSubscribed a)
1200+
1201+debugInvalidate :: Bool
1202+debugInvalidate = False
1203+
1204+invalidate :: IORef [SomeSwitchSubscribed] -> WeakList Invalidator -> IO (WeakList Invalidator)
1205+invalidate toReconnectRef wis = do
1206+ forM_ wis $ \wi -> do
1207+ mi <- deRefWeak wi
1208+ case mi of
1209+ Nothing -> do
1210+ when debugInvalidate $ liftIO $ putStrLn "invalidate Dead"
1211+ return () --TODO: Should we clean this up here?
1212+ Just i -> do
1213+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1214+ case i of
1215+ InvalidatorPull p -> do
1216+ when debugInvalidate $ liftIO $ putStrLn "invalidate Pull"
1217+ mVal <- readIORef $ pullValue p
1218+ forM_ mVal $ \val -> do
1219+ writeIORef (pullValue p) Nothing
1220+ writeIORef (pullSubscribedInvalidators val) =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1221+ InvalidatorSwitch subscribed -> do
1222+ when debugInvalidate $ liftIO $ putStrLn "invalidate Switch"
1223+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1224+ 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
1225+
1226+--------------------------------------------------------------------------------
1227+-- Reflex integration
1228+--------------------------------------------------------------------------------
1229+
1230+data Spider
1231+
1232+instance R.Reflex Spider where
1233+ newtype Behavior Spider a = SpiderBehavior { unSpiderBehavior :: Behavior a }
1234+ newtype Event Spider a = SpiderEvent { unSpiderEvent :: Event a }
1235+ type PullM Spider = BehaviorM
1236+ type PushM Spider = EventM
1237+ {-# INLINE never #-}
1238+ {-# INLINE constant #-}
1239+ never = SpiderEvent EventNever
1240+ constant = SpiderBehavior . BehaviorConst
1241+ push f = SpiderEvent. push f . unSpiderEvent
1242+ pull = SpiderBehavior . pull
1243+ merge = SpiderEvent . merge . (unsafeCoerce :: DMap (WrapArg (R.Event Spider) k) -> DMap (WrapArg Event k))
1244+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1245+ switch = SpiderEvent . switch . (unsafeCoerce :: Behavior (R.Event Spider a) -> Behavior (Event a)) . unSpiderBehavior
1246+ coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event (R.Event Spider a) -> Event (Event a)) . unSpiderEvent
1247+
1248+instance R.MonadSample Spider SpiderHost where
1249+ {-# INLINE sample #-}
1250+ sample = SpiderHost . readBehavior . unSpiderBehavior
1251+
1252+instance R.MonadHold Spider SpiderHost where
1253+ hold v0 = SpiderHost . liftM SpiderBehavior . runFrame . hold v0 . unSpiderEvent
1254+
1255+instance R.MonadSample Spider BehaviorM where
1256+ {-# INLINE sample #-}
1257+ sample = readBehaviorTracked . unSpiderBehavior
1258+
1259+instance R.MonadSample Spider EventM where
1260+ {-# INLINE sample #-}
1261+ sample = liftIO . readBehavior . unSpiderBehavior
1262+
1263+instance R.MonadHold Spider EventM where
1264+ {-# INLINE hold #-}
1265+ hold v0 e = SpiderBehavior <$> hold v0 (unSpiderEvent e)
1266+
1267+newtype RootTrigger a = RootTrigger (IORef [WeakSubscriber a], IORef (Maybe a))
1268+
1269+instance R.ReflexHost Spider where
1270+ type EventTrigger Spider = RootTrigger
1271+ type EventHandle Spider = R.Event Spider
1272+ type HostFrame Spider = SpiderHostFrame
1273+
1274+instance R.MonadReadEvent Spider ResultM where
1275+ {-# INLINE readEvent #-}
1276+ readEvent = liftM (fmap return) . readEvent . unSpiderEvent
1277+
1278+--TODO: Can probably get rid of this now that we're not using it for performEvent
1279+instance MonadTypedId EventM where
1280+ type TypedId EventM = TypedId IO
1281+ {-# INLINE getTypedId #-}
1282+ getTypedId = do
1283+ liftIO getTypedId
1284+
1285+instance MonadRef EventM where
1286+ type Ref EventM = Ref IO
1287+ {-# INLINE newRef #-}
1288+ {-# INLINE readRef #-}
1289+ {-# INLINE writeRef #-}
1290+ {-# INLINE atomicModifyRef #-}
1291+ newRef = liftIO . newRef
1292+ readRef = liftIO . readRef
1293+ writeRef r a = liftIO $ writeRef r a
1294+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
1295+
1296+newtype SpiderHost a = SpiderHost { runSpiderHost :: IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO)
1297+
1298+newtype SpiderHostFrame a = SpiderHostFrame { runSpiderHostFrame :: EventM a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO)
1299+
1300+instance R.MonadSample Spider SpiderHostFrame where
1301+ sample = SpiderHostFrame . R.sample --TODO: This can cause problems with laziness, so we should get rid of it if we can
1302+
1303+instance R.MonadHold Spider SpiderHostFrame where
1304+ {-# INLINE hold #-}
1305+ hold v0 e = SpiderHostFrame $ R.hold v0 e
1306+
1307+newEventWithTriggerIO f= do
1308+ occRef <- newIORef Nothing
1309+ subscribedRef <- newIORef Nothing
1310+ let !r = Root
1311+ { rootOccurrence = occRef
1312+ , rootSubscribed = subscribedRef
1313+ , rootInit = f
1314+ }
1315+ return $ SpiderEvent $ EventRoot r
1316+
1317+instance R.MonadReflexCreateTrigger Spider SpiderHost where
1318+ newEventWithTrigger = SpiderHost . newEventWithTriggerIO
1319+
1320+instance R.MonadReflexCreateTrigger Spider SpiderHostFrame where
1321+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . newEventWithTriggerIO
1322+
1323+instance R.MonadReflexHost Spider SpiderHost where
1324+ fireEventsAndRead es a = SpiderHost $ run es a
1325+ subscribeEvent e = SpiderHost $ do
1326+ _ <- runFrame $ getEventSubscribed $ unSpiderEvent e --TODO: The result of this should actually be used
1327+ return e
1328+ runFrame = SpiderHost . runFrame
1329+ runHostFrame = SpiderHost . runFrame . runSpiderHostFrame
1330+
1331+instance MonadRef SpiderHost where
1332+ type Ref SpiderHost = Ref IO
1333+ newRef = SpiderHost . newRef
1334+ readRef = SpiderHost . readRef
1335+ writeRef r = SpiderHost . writeRef r
1336+ atomicModifyRef r = SpiderHost . atomicModifyRef r
1337+
1338+instance MonadRef SpiderHostFrame where
1339+ type Ref SpiderHostFrame = Ref IO
1340+ newRef = SpiderHostFrame . newRef
1341+ readRef = SpiderHostFrame . readRef
1342+ writeRef r = SpiderHostFrame . writeRef r
1343+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
stylizedeleted−4
@@ -1,4 +0,0 @@
1−#!/usr/bin/env bash
2−set -euo pipefail
3−
4−for x in **/*.hs ; do stylish-haskell -i "$x" ; done
test/hlint.hsdeleted−39
@@ -1,39 +0,0 @@
1−module Main where
2−
3−import Control.Monad
4−import Language.Haskell.HLint (hlint)
5−import System.Directory
6−import System.Exit (exitFailure, exitSuccess)
7−import System.FilePath
8−import System.FilePath.Find
9−
10−main :: IO ()
11−main = do
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
39− if null ideas then exitSuccess else exitFailure
test/tests.hsdeleted−43
@@ -1,43 +0,0 @@
1−{-# LANGUAGE TemplateHaskell #-}
2−module Main where
3−
4−import Test.HUnit (runTestTT, (~:), assertEqual, errors, failures, test)
5−import Data.Patch ( Patch(apply) )
6−import Data.Patch.MapWithMove ( patchThatChangesMap )
7−import Data.Map as Map ( Map, fromList, singleton )
8−import Hedgehog (checkParallel, discover, Property, property, forAll, PropertyT, (===))
9−import Hedgehog.Gen as Gen ( int )
10−import Hedgehog.Range as Range ( linear )
11−import Control.Monad (replicateM)
12−import System.Exit (exitFailure, exitSuccess)
13−import Data.Sequence as Seq ( foldMapWithIndex, replicateM )
14−
15−main :: IO ()
16−main = do
17− counts <- runTestTT $ test [
18− "Simple Move" ~: (do
19− let mapBefore = Map.fromList [(0,1)]
20− mapAfter = Map.fromList [(0,0),(1,1)]
21− patch = patchThatChangesMap mapBefore mapAfter
22− afterPatch = apply patch mapBefore
23− assertEqual "Patch creates the same Map" (Just mapAfter) afterPatch),
24− "Property Checks" ~: propertyChecks
25− ]
26− if errors counts + failures counts == 0 then exitSuccess else exitFailure
27−
28−propertyChecks :: IO Bool
29−propertyChecks = checkParallel $$(discover)
30−
31−prop_patchThatChangesMap :: Property
32−prop_patchThatChangesMap = property $ do
33− mapBefore <- makeRandomIntMap
34− mapAfter <- makeRandomIntMap
35− let patch = patchThatChangesMap mapBefore mapAfter
36− Just mapAfter === apply patch mapBefore
37−
38−makeRandomIntMap :: Monad m => PropertyT m (Map Int Int)
39−makeRandomIntMap = do
40− let genNum = Gen.int (Range.linear 0 100)
41− length <- forAll genNum
42− listOfNumbers <- forAll $ Seq.replicateM length genNum
43− pure $ Seq.foldMapWithIndex Map.singleton listOfNumbers