on develop help sign in
88 files changed+1434−14022
since splitsnapshots
unifiedsplit
.github/workflows/haskell.yml+47 .travis.yml−171 CONTRIBUTING.md+3−3 ChangeLog.md+34−53 Quickref.md−314 README.md+41−14 bench/Main.hs−110 bench/RunAll.hs−157 cabal.haskell-ci−16 cabal.project.freeze−1 dep/reflex-platform/default.nix+7−6 dep/reflex-platform/github.json+3−2 patch.cabal+100 reflex.cabal−399 release.nix+23−32 src/Control/Monad/ReaderIO.hs−60 src/Data/AppendMap.hs−84 src/Data/FastMutableIntMap.hs−93 src/Data/FastWeakBag.hs−161 src/Data/Functor/Misc.hs+4−7 src/Data/Map/Misc.hs−71 src/Data/Monoid/DecidablyEmpty.hs+115 src/Data/Patch.hs+95 src/Reflex/Patch/Class.hs → src/Data/Patch/Class.hs+14−3 src/Reflex/Patch/DMap.hs → src/Data/Patch/DMap.hs+16−5 src/Reflex/Patch/DMapWithMove.hs → src/Data/Patch/DMapWithMove.hs+20−12 src/Reflex/Patch/IntMap.hs → src/Data/Patch/IntMap.hs+31−14 src/Reflex/Patch/Map.hs → src/Data/Patch/Map.hs+38−21 src/Data/Patch/MapWithMove.hs+312 src/Data/Patch/MapWithPatchingMove.hs+432 src/Data/Semigroup/Additive.hs+54 src/Data/WeakBag.hs−126 src/Reflex.hs−35 src/Reflex/Adjustable/Class.hs−139 src/Reflex/BehaviorWriter/Base.hs−202 src/Reflex/BehaviorWriter/Class.hs−25 src/Reflex/Class.hs−1676 src/Reflex/Collection.hs−225 src/Reflex/Dynamic.hs−530 src/Reflex/Dynamic/TH.hs−106 src/Reflex/Dynamic/Uniq.hs−105 src/Reflex/DynamicWriter.hs−7 src/Reflex/DynamicWriter/Base.hs−237 src/Reflex/DynamicWriter/Class.hs−28 src/Reflex/EventWriter.hs−7 src/Reflex/EventWriter/Base.hs−306 src/Reflex/EventWriter/Class.hs−26 src/Reflex/FastWeak.hs−200 src/Reflex/FunctorMaybe.hs−47 src/Reflex/Host/Class.hs−279 src/Reflex/Network.hs−45 src/Reflex/NotReady/Class.hs−77 src/Reflex/Optimizer.hs−65 src/Reflex/Patch.hs−46 src/Reflex/Patch/MapWithMove.hs−270 src/Reflex/PerformEvent/Base.hs−179 src/Reflex/PerformEvent/Class.hs−63 src/Reflex/PostBuild/Base.hs−197 src/Reflex/PostBuild/Class.hs−41 src/Reflex/Profiled.hs−227 src/Reflex/Pure.hs−212 src/Reflex/Query/Base.hs−335 src/Reflex/Query/Class.hs−118 src/Reflex/Requester/Base.hs−537 src/Reflex/Requester/Class.hs−72 src/Reflex/Spider.hs−20 src/Reflex/Spider/Internal.hs−2716 src/Reflex/Time.hs−384 src/Reflex/TriggerEvent/Base.hs−148 src/Reflex/TriggerEvent/Class.hs−49 src/Reflex/Widget/Basic.hs−44 src/Reflex/Workflow.hs−50 test/EventWriterT.hs−134 test/GC.hs−101 test/QueryT.hs−142 test/Reflex/Bench/Focused.hs−381 test/Reflex/Plan/Pure.hs−72 test/Reflex/Plan/Reflex.hs−135 test/Reflex/Test.hs−66 test/Reflex/Test/CrossImpl.hs−262 test/Reflex/Test/Micro.hs−346 test/Reflex/TestPlan.hs−52 test/RequesterT.hs−174 test/Test/Run.hs−74 test/hlint.hs+2−1 test/rootCleanup.hs−25 test/semantics.hs−47 test/tests.hs+43
.github/workflows/haskell.ymlnew file+47
@@ -0,0 +1,47 @@
1+name: github-action
2+
3+on: [push, pull_request]
4+
5+jobs:
6+ build:
7+ strategy:
8+ matrix:
9+ ghc: ['8.0.2', '8.2.2', '8.4.4', '8.6.5', '8.8.4', '8.10.2']
10+ os: ['ubuntu-latest', 'macos-latest']
11+ exclude:
12+ # There are some linker warnings in 802 on darwin that
13+ # cause compilation to fail
14+ # See https://github.com/NixOS/nixpkgs/issues/25139
15+ - ghc: '8.0.2'
16+ os: 'macos-latest'
17+ runs-on: ${{ matrix.os }}
18+
19+ name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20+ steps:
21+ - uses: actions/checkout@v2
22+ - uses: actions/setup-haskell@v1
23+ with:
24+ ghc-version: ${{ matrix.ghc }}
25+ - name: Cache
26+ uses: actions/cache@v1
27+ env:
28+ cache-name: cache-cabal
29+ with:
30+ path: ~/.cabal
31+ key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32+ restore-keys: |
33+ ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34+ ${{ runner.os }}-${{ matrix.ghc }}-build-
35+ ${{ runner.os }}-${{ matrix.ghc }}-
36+ ${{ runner.os }}
37+
38+ - name: Install dependencies
39+ run: |
40+ cabal update
41+ cabal build --only-dependencies --enable-tests --enable-benchmarks
42+ - name: Build
43+ run: cabal build --enable-tests --enable-benchmarks all
44+ - name: Run tests
45+ run: cabal test --enable-tests all
46+ - name: Build Docs
47+ run: cabal haddock
.travis.ymldeleted−171
@@ -1,171 +0,0 @@
1−# This Travis job script has been generated by a script via
2−#
3−# haskell-ci '--config=cabal.haskell-ci' 'cabal.project'
4−#
5−# For more information, see https://github.com/haskell-CI/haskell-ci
6−#
7−# version: 0.3.20190814
8−#
9−language: c
10−dist: xenial
11−sudo: required
12−git:
13− # whether to recursively clone submodules
14− submodules: false
15−cache:
16− directories:
17− - $HOME/.cabal/packages
18− - $HOME/.cabal/store
19−before_cache:
20− - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log
21− # remove files that are regenerated by 'cabal update'
22− - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.*
23− - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json
24− - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache
25− - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar
26− - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx
27− - rm -rfv $CABALHOME/packages/head.hackage
28−matrix:
29− include:
30− - compiler: ghcjs-8.4
31− addons: {"apt":{"sources":["hvr-ghc"],"packages":["cabal-install-3.0"]}}
32− - compiler: ghc-8.6.5
33− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-2.4"]}}
34− - compiler: ghc-8.4.4
35− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-2.4"]}}
36− - compiler: ghc-8.2.2
37− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-2.4"]}}
38− - compiler: ghc-8.0.2
39− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-2.4"]}}
40−before_install:
41− - |
42− if [ "$TRAVIS_OS_NAME" = "linux" ]; then
43− sudo add-apt-repository -y ppa:hvr/ghcjs;
44− curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
45− sudo apt-add-repository 'https://deb.nodesource.com/node_8.x xenial main'
46− sudo apt-get update;
47− sudo apt-get install $CC cabal-install-3.0 nodejs;
48− fi
49− - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//')
50− - WITHCOMPILER="-w $HC"
51− - |
52− if echo $CC | grep -q ghcjs; then
53− GHCJS=true
54− HC=${HC}js
55− WITHCOMPILER="--ghcjs ${WITHCOMPILER}js"
56− else
57− GHCJS=false;
58− fi
59− - if $GHCJS ; then sudo apt-get install -y ghc-8.4.4 ; fi
60− - if $GHCJS ; then PATH="/opt/ghc/8.4.4/bin:$PATH" ; fi
61− - HCPKG="$HC-pkg"
62− - unset CC
63− - CABAL=/opt/ghc/bin/cabal
64− - CABALHOME=$HOME/.cabal
65− - export PATH="$CABALHOME/bin:$PATH"
66− - TOP=$(pwd)
67− - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')"
68− - echo $HCNUMVER
69− - CABAL="$CABAL -vnormal+nowrap+markoutput"
70− - set -o pipefail
71− - |
72− echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk
73− echo 'BEGIN { state = "output"; }' >> .colorful.awk
74− echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk
75− echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk
76− echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk
77− echo ' if (state == "cabal") {' >> .colorful.awk
78− echo ' print blue($0)' >> .colorful.awk
79− echo ' } else {' >> .colorful.awk
80− echo ' print $0' >> .colorful.awk
81− echo ' }' >> .colorful.awk
82− echo '}' >> .colorful.awk
83− - cat .colorful.awk
84− - |
85− color_cabal_output () {
86− awk -f $TOP/.colorful.awk
87− }
88− - echo text | color_cabal_output
89−install:
90− - ${CABAL} --version
91− - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"
92− - node --version
93− - echo $GHCJS
94− - TEST=--enable-tests
95− - BENCH=--enable-benchmarks
96− - BENCH=--disable-benchmarks
97− - HEADHACKAGE=false
98− - rm -f $CABALHOME/config
99− - |
100− echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config
101− echo "remote-build-reporting: anonymous" >> $CABALHOME/config
102− echo "write-ghc-environment-files: always" >> $CABALHOME/config
103− echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config
104− echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config
105− echo "world-file: $CABALHOME/world" >> $CABALHOME/config
106− echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config
107− echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config
108− echo "installdir: $CABALHOME/bin" >> $CABALHOME/config
109− echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config
110− echo "store-dir: $CABALHOME/store" >> $CABALHOME/config
111− echo "install-dirs user" >> $CABALHOME/config
112− echo " prefix: $CABALHOME" >> $CABALHOME/config
113− echo "repository hackage.haskell.org" >> $CABALHOME/config
114− echo " url: http://hackage.haskell.org/" >> $CABALHOME/config
115− - cat $CABALHOME/config
116− - rm -fv cabal.project cabal.project.local cabal.project.freeze
117− - travis_retry ${CABAL} v2-update -v
118− - if $GHCJS ; then (cd /tmp && ${CABAL} v2-install -w ghc-8.4.4 happy) ; fi
119− # Generate cabal.project
120− - rm -rf cabal.project cabal.project.local cabal.project.freeze
121− - touch cabal.project
122− - |
123− echo "packages: ." >> cabal.project
124− - |
125− - cat cabal.project || true
126− - cat cabal.project.local || true
127− - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi
128− - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output
129− - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'"
130− - rm cabal.project.freeze
131−script:
132− - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)
133− # Packaging...
134− - ${CABAL} v2-sdist all | color_cabal_output
135− # Unpacking...
136− - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/
137− - cd ${DISTDIR} || false
138− - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \;
139− - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \;
140− - PKGDIR_reflex="$(find . -maxdepth 1 -type d -regex '.*/reflex-[0-9.]*')"
141− # Generate cabal.project
142− - rm -rf cabal.project cabal.project.local cabal.project.freeze
143− - touch cabal.project
144− - |
145− echo "packages: ${PKGDIR_reflex}" >> cabal.project
146− - |
147− - cat cabal.project || true
148− - cat cabal.project.local || true
149− # Building...
150− # this builds all libraries and executables (without tests/benchmarks)
151− - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all | color_cabal_output
152− # Building with tests and benchmarks...
153− # build & run tests, build benchmarks
154− - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output
155− # Testing...
156− - if ! $GHCJS ; then ${CABAL} v2-test $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output ; fi
157− # cabal check...
158− - (cd ${PKGDIR_reflex} && ${CABAL} -vnormal check)
159− # haddock...
160− - if ! $GHCJS ; then ${CABAL} v2-haddock $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output ; fi
161− # Constraint sets
162− - rm -rf cabal.project.local
163− # Constraint set no-th
164− - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --constraint='reflex -use-template-haskell' all | color_cabal_output
165− # Constraint set old-these
166− - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --constraint='these <1' all | color_cabal_output
167− # Constraint set old-witherable
168− - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --constraint='witherable <0.3.2' all | color_cabal_output
169−
170−# REGENDATA ["--config=cabal.haskell-ci","cabal.project"]
171−# EOF
CONTRIBUTING.md+3−3
@@ -15,8 +15,8 @@ Before opening an issue, please check whether your issue has already been report
1515
1616* Describe the issue you're encountering or the suggestion you're making
1717* 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 reflex you were using. If you're using a github checkout, provide the git hash.
19−* Describe how you're building reflex (i.e., via reflex-platform, cabal install, stack, obelisk, etc.). If you're using reflex-platform or obelisk, provide the git hash of your checkout.
18+* Let us know what version of patch you were using. If you're using a github checkout, provide the git hash.
19+* Describe how you're building patch (i.e., via reflex-platform, cabal install, stack, obelisk, etc.). If you're using reflex-platform or obelisk, provide the git hash of your checkout.
2020
2121## Submitting Changes
2222
@@ -47,7 +47,7 @@ Make sure the project builds and that the tests pass! This will generally also b
4747
4848#### Dependencies
4949
50−Include version bounds whenever adding a dependency to the library stanza of the cabal file. Note that libraries added to reflex.cabal also need to be added to default.nix.
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.
5151
5252### Documentation
5353
ChangeLog.md+34−53
@@ -1,80 +1,61 @@
1−# Revision history for reflex
1+# Revision history for patch
22
3−## 0.6.3
3+## Unreleased
44
5−* `Data.WeakBag.traverse` and `Data.FastWeakBag.traverse` have been deprecated.
6− They are replaced with `Data.WeakBag.traverse_` and `Data.FastWeakBag.traverse_`, respectively.
5+* New dep of `data-orphans` for old GHC to get instances honestly instead of
6+ via `monoidal-containers`.
77
8−* Fixes a bug in `Reflex.Patch.MapWithMove.patchThatSortsMapWith` that was producing invalid `PatchMapWithMove`.
8+## 0.0.5.0 - 2021-12-17
99
10−* Add missing `NotReady` instances:
11− - `instance NotReady (SpiderTimeline x) (SpiderHost x)`
12− - `instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x))`
10+* `Additive` now lives in `Data.Semigroup.Additive`, but is still reexported
11+ from `Data.Patch` for compatability.
1312
14−## 0.6.2.4
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.
1518
16−* Update to monoidal-containers 0.6
19+## 0.0.4.0 - 2021-04-20
1720
18−## 0.6.2.3
21+* Enable PolyKinds
1922
20−* Add an upper-bound to witherable
23+## 0.0.3.2 - 2020-11-06
2124
22−## 0.6.2.2
25+* Update version bounds
2326
24−* Support these >= 1. Add `split-these` flag to control whether to use new these/semialign combination or not.
27+## 0.0.3.1 - 2020-02-05
2528
26−* Update version bounds to fix some CI failures
29+* Replace `fromJust` with something easier to debug.
2730
28−* Add travis CI configuration
31+## 0.0.3.0 - 2020-02-05
2932
30−## 0.6.2.1
33+* Create `PatchMapWithPatchingMove` variant which supports moves with a patch.
3134
32−* Generalize `fan` to `fanG` to take a `DMap` with non-`Identity`
33− functor:
34− * `fan` to `fanG`
35− * `EventSelectorG` for `fanG` result selector.
35+* Create `DecidablyEmpty` subclass of `Monoid`.
3636
37−* Reduce the amount of unsafeCoerce in coercing newtypes under Event/Dynamic/Behavior.
38− * Add fused ReaderIO for the purpose of coercion (ReaderT's third argument has nominal role preventing automated coerce)
39− * Add incrementalCoercion/coerceIncremental to go with dynamicCoercion/coerceDynamic
37+## 0.0.2.0 - 2020-01-17
4038
41−* Generalize merging functions:
42− `merge` to `mergeG`,
43− `mergeIncremental` to `mergeIncrementalG`,
44− `mergeIncrementalWithMove` to `mergeIncrementalWithMoveG`.
39+* Consistently provide:
4540
46−* Generalize distribute function:
47− `distributeDMapOverDynPure` to `distributeDMapOverDynPureG`,
41+ - `Wrapped` instances
4842
49−## 0.6.2.0
43+ - `*WithIndex` instances
5044
51−* Fix `holdDyn` so that it is lazy in its event argument
52− These produce `DMap`s whose values needn't be `Identity`.
45+ - `un*` newtype unwrappers
5346
54−* Stop using the now-deprecated `*Tag` classes (e.g., `ShowTag`).
47+ for `PatchMap`, `PatchIntMap`, and `PatchMapWithMove`.
5548
56−* Fix `holdDyn` so that it is lazy in its event argument.
49+## 0.0.1.0 - 2020-01-09
5750
58−## 0.6.1.0
51+* Support older GHCs with `split-these` flag.
5952
60−* Re-export all of `Data.Map.Monoidal`
53+* Additional instances for the `Group` class for basic types.
6154
62−* Fix `QueryT` and `RequesterT` tests
55+## 0.0.0.1 - 2020-01-08
6356
64−## 0.6.0.0 -- 2019-03-20
57+* Remove unneeded dependencies
6558
66−* Deprecate `FunctorMaybe` in favor of `Data.Witherable.Filterable`. We still export `fmapMaybe`, `ffilter`, etc., but they all rely on `Filterable` now.
59+## 0.0.0.0 - 2020-01-08
6760
68−* Rename `MonadDynamicWriter` to `DynamicWriter` and add a deprecation for the old name.
69−
70−* Remove many deprecated functions.
71−
72−* Add a `Num` instance for `Dynamic`.
73−
74−* Add `matchRequestsWithResponses` to make it easier to use `Requester` with protocols that don't do this matching for you.
75−
76−* Add `withRequesterT` to map functions over the request and response of a `RequesterT`.
77−
78−* Suppress nil patches in `QueryT` as an optimization. The `Query` type must now have an `Eq` instance.
79−
80−* Add `throttleBatchWithLag` to `Reflex.Time`. See that module for details.
61+* Extract patching functionality from Reflex.
Quickref.mddeleted−314
@@ -1,314 +0,0 @@
1−# Reflex Quick(ish) Reference
2−
3−## Typeclasses
4−
5−Many Reflex functions operate in monadic context `m a`, where the monad 'm' supports various additional typeclasses such as MonadWidget, MonadHold, or MonadSample in addition to Monad itself. The actual 'm' in use will be determined by the top-level entry point of the FRP host (such as Reflex-Dom -- see the bottom of the Reflex-Dom quick reference for details).
6−
7−The function signatures here have been simplified by removing many typeclass constraints and adding simple annotations to each function. Also the ubiquitous 't' type parameter has been removed.
8−
9−Some of these functions are *pure*: They operate on Events, Behaviors, or Dynamics uniformly without regard to the "current time". Other functions must operate in some monadic context, because they produce a result "as of now" (e.g., any function that takes an "initial" value, or returns a "current" value). Annotations are used to distinguish these cases:
10−
11−```haskell
12−[ ] -- Pure function
13−[S] -- Function runs in any monad supporting MonadSample
14−[H] -- Function runs in any monad supporting MonadHold
15−```
16−Since MonadHold depends on MonadSample, any [S] function also runs in [H] context.
17−
18−## Functions producing Event
19−
20−```haskell
21−-- Trivial Event
22−[ ] never :: Event a
23−
24−-- Extract Event from Dynamic
25−[ ] updated :: Dynamic a -> Event a
26−
27−-- Transform Event to Event using function
28−[ ] fmap :: (a -> b) -> Event a -> Event b
29−[ ] fmapMaybe :: (a -> Maybe b) -> Event a -> Event b
30−[ ] ffilter :: (a -> Bool) -> Event a -> Event a
31−[ ] ffor :: Event a -> (a -> b) -> Event b
32−[ ] fforMaybe :: Event a -> (a -> Maybe b) -> Event b
33−[ ] <$ :: a -> Event b -> Event a
34−
35−-- Event to identical Event with debug trace. (Only prints if Event is ultimately used.)
36−[ ] traceEvent :: Show a => String -> Event a -> Event a
37−[ ] traceEventWith :: (a -> String) -> Event a -> Event a
38−
39−-- Transform Event to Event by sampling Behavior or Dynamic
40−[ ] gate :: Behavior Bool -> Event a -> Event a
41−[ ] tag :: Behavior a -> Event b -> Event a
42−[ ] tagPromptlyDyn :: Dynamic a -> Event b -> Event a
43−[ ] attach :: Behavior a -> Event b -> Event (a, b)
44−[ ] attachPromptlyDyn :: Dynamic a -> Event b -> Event (a, b)
45−[ ] attachWith :: (a -> b -> c) -> Behavior a -> Event b -> Event c
46−[ ] attachPromptlyDynWith :: (a -> b -> c) -> Dynamic a -> Event b -> Event c
47−[ ] attachWithMaybe :: (a -> b -> Maybe c) -> Behavior a -> Event b -> Event c
48−[ ] attachPromptlyDynWithMaybe :: (a -> b -> Maybe c) -> Dynamic a -> Event b -> Event c
49−[ ] <@> :: Behavior (a -> b) -> Event a -> Event b
50−[ ] <@ :: Behavior a -> Event b -> Event a
51−
52−-- Combine multiple Events
53−[ ] <> :: Semigroup a => Event a -> Event a -> Event a
54−[ ] difference :: Event a -> Event b -> Event a
55−[ ] align :: Event a -> Event b -> Event (These a b)
56−[ ] alignWith :: (These a b -> c) -> Event a -> Event b -> Event c
57−[ ] mergeWith :: (a -> a -> a) -> [Event a] -> Event a
58−[ ] leftmost :: [Event a] -> Event a
59−[ ] mergeList :: [Event a] -> Event (NonEmpty a)
60−[ ] merge :: GCompare k => DMap k Event -> Event (DMap k Identity)
61−[ ] mergeMap :: Ord k => Map k (Event a) -> Event (Map k a)
62−
63−-- Efficient one-to-many fanout
64−[ ] fanMap :: Ord k => Event (Map k a) -> EventSelector (Const2 k a)
65−[ ] fan :: GCompare k => Event (DMap k Identity) -> EventSelector k
66−[ ] select :: EventSelector k -> k a -> Event a
67−[ ] fanEither :: Event (Either a b) -> (Event a, Event b)
68−[ ] fanThese :: Event (These a b) -> (Event a, Event b)
69−
70−-- Event to Event via function that can sample current values
71−[ ] push :: (a -> m (Maybe b)) -> Event a -> Event b
72−[ ] pushAlways :: (a -> m b ) -> Event a -> Event b
73− -- Note supplied function operates in [H] context
74−
75−-- Split Event into next occurrence and all other future occurrences, as of now.
76−[H] headE :: Event a -> m (Event a)
77−[H] tailE :: Event a -> m (Event a)
78−[H] headTailE :: Event a -> m (Event a, Event a)
79−```
80−
81−## Functions producing Behavior
82−
83−```haskell
84−-- Trivial Behavior
85−[ ] constant :: a -> Behavior a
86−
87−-- Extract Behavior from Dynamic
88−[ ] current :: Dynamic a -> Behavior a
89−
90−-- Create Behavior with given initial value, updated when the Event fires.
91−[H] hold :: a -> Event a -> m (Behavior a)
92−
93−-- Transform Behavior to Behavior using function
94−[ ] fmap :: (a -> b) -> Behavior a -> Behavior b
95−[ ] ffor :: Behavior a -> (a -> b) -> Behavior b
96−[ ] <*> :: Behavior (a -> b) -> Behavior a -> Behavior b
97−[ ] >>= :: Behavior a -> (a -> Behavior b) -> Behavior b
98−[ ] <> :: Monoid a => Behavior a -> Behavior a -> Behavior a
99−-- ... plus many more due to typeclass membership
100−
101−-- Combine multiple behaviors via applicative instance
102−[ ] ffor2 :: Behavior a -> Behavior b -> (a -> b -> c) -> Behavior c
103−[ ] ffor3 :: Behavior a -> Behavior b -> Behavior c -> (a -> b -> c -> d) -> Behavior d
104−
105−-- Behavior to Behavior by sampling current values
106−[S] sample :: Behavior a -> m a
107−[ ] pull :: m a -> Behavior a
108− -- Note supplied value is in [S] context
109−```
110−
111−## Functions producing Dynamic
112−
113−```haskell
114−-- Trivial Dynamic
115−[ ] constDyn :: a -> Dynamic a
116−
117−-- Create Dynamic with given initial value, updated (various ways) when the Event fires.
118−[H] holdDyn :: a -> Event a -> m (Dynamic a)
119−[H] foldDyn :: (a -> b -> b ) -> b -> Event a -> m (Dynamic b)
120−[H] foldDynMaybe :: (a -> b -> Maybe b ) -> b -> Event a -> m (Dynamic b)
121−[H] foldDynM :: (a -> b -> m' b ) -> b -> Event a -> m (Dynamic b)
122−[H] foldDynMaybeM :: (a -> b -> m' (Maybe b)) -> b -> Event a -> m (Dynamic b)
123− -- Note m' supplies [H] context
124−
125−-- Initial value is 0; counts Event firings from now.
126−[H] count :: Num b => Event a -> m (Dynamic b)
127−-- Initial Bool value is supplied; toggles at each Event firing.
128−[H] toggle :: Bool -> Event a -> m (Dynamic Bool)
129−
130−-- Transform Dynamic to Dynamic using function
131−[ ] ffor :: Dynamic a -> (a -> b) -> Dynamic b
132−[ ] fmap :: (a -> b) -> Dynamic a -> Dynamic b
133−[ ] splitDynPure :: Dynamic (a, b) -> (Dynamic a, Dynamic b)
134−
135−-- Combine multiple Dynamics
136−[ ] mconcat :: Monoid a => [Dynamic a] -> Dynamic a
137−[ ] distributeDMapOverDynPure :: GCompare k => DMap (WrapArg Dynamic k) -> Dynamic (DMap k)
138−[ ] <*> :: Dynamic (a -> b) -> Dynamic a -> Dynamic b
139−[ ] >>= :: Dynamic a -> (a -> Dynamic b) -> Dynamic b
140−[ ] zipDynWith :: (a -> b -> c) -> Dynamic a -> Dynamic b -> Dynamic c
141−
142−-- Combine multiple dynamics via applicative instance
143−[ ] ffor2 :: Dynamic a -> Dynamic b -> (a -> b -> c) -> Dynamic c
144−[ ] ffor3 :: Dynamic a -> Dynamic b -> Dynamic c -> (a -> b -> c -> d) -> Dynamic d
145−
146−-- Efficient one-to-many fanout
147−[ ] demux :: Ord k => Dynamic k -> Demux k
148−[ ] demuxed :: Eq k => Demux k -> k -> Dynamic Bool
149−
150−-- Dynamic to Dynamic, removing updates w/o value change
151−[H] holdUniqDyn :: Eq a => Dynamic a -> m (Dynamic a)
152−[H] holdUniqDynBy :: (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
153−
154−-- Dynamic to identical Dynamic with debug trace. (Only prints if Dynamic is ultimately used.)
155−[ ] traceDyn :: Show a => String -> Dynamic a -> Dynamic a
156−[ ] traceDynWith :: (a -> String) -> Dynamic a -> Dynamic a
157−```
158−
159−## Flattening functions
160−
161−These functions flatten nested types such as Event-of-Event, Behavior-of-Event, Event-of-Behavior etc, removing the outer wrapper.
162−
163−For Events, the returned Event fires whenever the latest Event supplied by the wrapper fires. There are differences in how the functions handle *coincidences* -- situations where the old or new Event fires at the same instant that we switch from old to new. In some cases, the output Event tracks the old Event at the instant of switchover, while in other cases it tracks the new Event.
164−
165−```haskell
166−-- Flatten Behavior-of-Event to Event. Old Event is used during switchover.
167−[ ] switch :: Behavior (Event a) -> Event a
168−
169−-- Flatten Dynamic-of-Event to Event. New Event is used immediately.
170−[ ] switchDyn :: Dynamic (Event a) -> Event a
171−
172−-- Flatten Event-of-Event to Event that fires when both wrapper AND new Event fire.
173−[ ] coincidence :: Event (Event a) -> Event a
174−
175−-- Flatten Behavior-of-Behavior to Behavior. Behavior is an instance of Monad,
176−-- so the 'join' function from 'Control.Monad' suffices. The output of 'join' is
177−-- a Behavior whose value is equal to the current value of the current value of
178−-- the input.
179−[ ] join :: Behavior (Behavior a) -> Behavior a
180−
181−
182−-- Flatten Dynamic-of-Dynamic to Dynamic. New Dynamic is used immediately.
183−-- Output updated whenever inner OR outer Dynamic updates.
184−[ ] join :: Dynamic (Dynamic a) -> Dynamic a
185−[ ] joinDynThroughMap :: Ord k => Dynamic (Map k (Dynamic a)) -> Dynamic (Map k a)
186−
187−-- Analogous to 'hold': Create a Behavior that is initially identical to the
188−-- supplied Behavior. Updated to track a new Behavior whenever the Event fires.
189−[H] switcher :: Behavior a -> Event (Behavior a) -> m (Behavior a)
190−
191−-- Similar to above, for Events. Created Event initially tracks the first argument.
192−-- At switchover, the output Event immediately tracks the new Event.
193−[H] switchHold :: Event a -> Event (Event a) -> m (Event a)
194−```
195−
196−## Typeclasses to introspect and modify an FRP network.
197−
198−The functions mentioned above are used to create a static FRP network.
199−There are additional typeclasses that can be used to modify the FRP network, to have it interact with IO action, or to introspect the building of the network.
200−
201−The typeclasses and their associated annotations include:
202−
203−- `PostBuild`
204− Fire an Event when an FRP network has been set up.
205− ```haskell
206− [B] -- Function runs in any monad supporting PostBuild
207− ```
208−
209−- `Adjustable`
210− Use Events to add or remove pieces of an FRP network.
211− ```haskell
212− [A] -- Function runs in any monad supporting Adjustable
213− ```
214−
215−- `TriggerEvent`
216− Create new externally-fired Events from within an FRP network.
217− ```haskell
218− [T] -- Function runs in any monad supporting TriggerEvent
219− ```
220−
221−- `PerformEvent`
222− Use Events to trigger IO actions and to collect their results.
223− ```haskell
224− [P] -- Function runs in any monad supporting PerformEvent
225− ```
226−
227−## Startup
228−
229−```haskell
230−-- One-shot Event that is triggered once the FRP network has been built
231−[B] getPostBuild :: m (Event ())
232−```
233−
234−## Collection management functions
235−
236−```haskell
237−-- Turn a Dynamic key/value map into a set of dynamically-changing widgets.
238−[H,A,B] listWithKey :: Ord k =>
239− Dynamic (Map k v) -> (k -> Dynamic v -> m a ) -> m (Dynamic (Map k a))
240−
241−-- Same as above where the widget constructor doesn't care about the key.
242−[H,A,B] list :: Ord k =>
243− Dynamic (Map k v) -> ( Dynamic v -> m a ) -> m (Dynamic (Map k a))
244−
245−-- Even simpler version where there are no keys and we just use a list.
246−[H,A,B] simpleList ::
247− Dynamic [v] -> ( Dynamic v -> m a ) -> m (Dynamic [a])
248−
249−-- Like listWithKey specialized for widgets returning (Event a).
250−[H,A,B] listViewWithKey :: Ord k =>
251− Dynamic (Map k v) -> (k -> Dynamic v -> m (Event a)) -> m (Event (Map k a))
252−
253−-- Create a dynamically-changing set of widgets, one of which is selected at any time.
254−[H,A,B] selectViewListWithKey_ :: Ord k => Dynamic k ->
255− Dynamic (Map k v) -> (k -> Dynamic v -> Dynamic Bool -> m (Event a)) -> m (Event k)
256−
257−-- Same as listWithKey, but takes initial values and an updates Event instead of a Dynamic.
258−[H,A] listWithKeyShallowDiff :: Ord k =>
259− Map k v -> Event (Map k (Maybe v)) -> (k -> v -> Event v -> m a) -> m (Dynamic (Map k a))
260−```
261−
262−## Creating new events from within an FRP network.
263−
264−```haskell
265−-- Create a new Event and a function that will cause the Event to fire, from within an FRP network
266−[T] newTriggerEvent :: m (Event a, a -> IO ())
267−```
268−
269−## Connecting to the real world (I/O)
270−
271−```haskell
272−-- Run side-effecting actions in Event when it occurs; returned Event contains
273−-- results. Side effects run in the (Performable m) monad which is associated with
274−-- the (PerformEvent t m) typeclass constraint.
275−-- This allows for working with IO when a ((MonadIO (Performable m)) constraint is available.
276−[P] performEvent :: Event (Performable m a ) -> m (Event a)
277−
278−-- Just run side-effects; no return Event
279−[P] performEvent_ :: Event (Performable m ()) -> m ()
280−
281−-- Actions run asynchronously; actions are given a callback to send return values
282−[P,T] performEventAsync :: Event ((a -> IO ()) -> Performable m ()) -> m (Event a)
283−```
284−
285−### Time
286−
287−```haskell
288−-- Create Event at given interval with given basis time.
289−[P,T] tickLossy :: NominalDiffTime -> UTCTime -> m (Event t TickInfo)
290−
291−-- Delay an Event's occurrences by a given amount in seconds.
292−[P,T] delay :: NominalDiffTime -> Event t a -> m (Event t a)
293−```
294−
295−## Networks
296−
297−```haskell
298−-- Functions from Reflex.Adjustable / Reflex.Network used to deal with Dynamics/Events carrying (m a)
299−
300−[A] runWithReplace :: m a -> Event t (m b) -> m (a, Event t b)
301−
302−-- Given a Dynamic of network-creating actions, create a network that is recreated whenever the Dynamic updates.
303−-- The returned Event of network results occurs when the Dynamic does. Note: Often, the type a is an Event,
304−-- in which case the return value is an Event-of-Events that would typically be flattened (via switchHold).
305−[P,A] networkView :: Dynamic (m a) -> m (Event a)
306−
307−-- Given an initial network and an Event of network-creating actions, create a network that is recreated whenever the
308−-- Event fires. The returned Dynamic of network results occurs when the Event does. Note: Often, the type a is an
309−-- Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
310−[H,A] networkHold :: m a -> Event (m a) -> m (Dynamic a)
311−
312−-- Render a placeholder network to be shown while another network is not yet done building
313−[P,A] untilReady :: m a -> m b -> m (a, Event b)
314−```
README.md+41−14
@@ -1,25 +1,52 @@
1−## [Reflex](https://reflex-frp.org/)
1+# patch
22
3−[![Hackage](https://img.shields.io/hackage/v/reflex.svg)](http://hackage.haskell.org/package/reflex)
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)
44
5−### Practical Functional Reactive Programming
5+Data structures for describing changes to other data structures.
66
7−Reflex is a fully-deterministic, higher-order Functional Reactive Programming (FRP) interface and an engine that efficiently implements that interface.
7+A `Patch` type represents a kind of change made to a data structure.
88
9−[Reflex-DOM](https://github.com/reflex-frp/reflex-dom) is a framework built on Reflex that facilitates the development of web pages, including highly-interactive single-page apps.
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+```
1016
11−A summary of Reflex functions is available in the [quick reference](Quickref.md).
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).
1219
13−**Visit https://reflex-frp.org/ for more information, tutorials, documentation and [examples](https://examples.reflex-frp.org/).**
20+`PatchMap` is defined as:
1421
15−### Resources
16−[Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
22+```haskell
23+newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
24+```
1725
18−[/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
26+The `Maybe` around the value is used to represent insertion/updates or deletion of the element at a given key.
1927
20−[irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
28+Its `Patch` instance begins with:
2129
22−### Hacking
30+```haskell
31+instance Ord k => Patch (PatchMap k v) where
32+ type PatchTarget (PatchMap k v) = Map k v
33+ ...
34+```
2335
24−Use the `./scripts/hack-on reflex` script in [Reflex Platform](https://github.com/reflex-frp/reflex-platform) to checkout the source code of `reflex` locally in `reflex-platform/reflex` directory.
25−Then do modifications to the source in place, and use the `./try-reflex` or `./scripts/work-on` scripts to create the shell to test your changes.
36+When a `PatchMap` is applied to its `PatchTarget`, the following changes can occur:
37+
38+- If the key is present in the `Patch` and the `PatchTarget`...
39+
40+ - And the `Patch` value at that key is `Nothing`: delete that key from the `PatchTarget`.
41+
42+ - And the `Patch` value at that key is `Just x`: update the value at that key in the `PatchTarget` to `x`.
43+
44+- If the key is present in the `Patch` and not present in the `PatchTarget`...
45+
46+ - And the `Patch` value at that key is `Nothing`: do nothing because we're trying to delete a key that doesn't exist in the target in the first place.
47+
48+ - And the `Patch` value at that key is `Just x`: insert the key and the value `x` into the `PatchTarget`
49+
50+- If the key is *not* present in the `Patch` but present in the `PatchTarget`: do nothing.
51+
52+There are, of course, more complicated ways of patching maps involving, for example, moving values from one key to another. You can find the code for that in `Data.Patch.PatchMapWithMove`. Note that the `PatchTarget` type associated with the `PatchMapWithMove` patch instance is still `Map k v`!
bench/Main.hsdeleted−110
@@ -1,110 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−{-# LANGUAGE TupleSections #-}
5−{-# LANGUAGE TypeFamilies #-}
6−
7−-- The instance for NFData (TVar a) is an orphan, but necessary here
8−{-# OPTIONS_GHC -fno-warn-orphans #-}
9−
10−module Main where
11−
12−import Control.Concurrent.STM
13−import Control.DeepSeq
14−import Control.Exception (evaluate)
15−import Control.Monad.Identity
16−import Control.Monad.IO.Class
17−import Criterion.Main
18−import Data.Dependent.Map (DMap)
19−import qualified Data.Dependent.Map as DMap
20−import Data.Dependent.Sum
21−import Data.Functor.Misc
22−import Data.IORef
23−import Data.Maybe (fromJust)
24−import Reflex
25−import Reflex.Host.Class
26−
27−main :: IO ()
28−main = defaultMain
29− [ bgroup "micro" micros ]
30−
31−#if !(MIN_VERSION_deepseq(1,4,2))
32−instance NFData (IORef a) where
33− rnf x = seq x ()
34−#endif
35−
36−instance NFData (TVar a) where
37− rnf x = seq x ()
38−
39−newtype WHNF a = WHNF a
40−instance NFData (WHNF a) where
41− rnf (WHNF a) = seq a ()
42−
43−withSetup :: NFData b => String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
44−withSetup name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
45− bench name . nfIO $ runSpiderHost (action a)
46−
47−withSetupWHNF :: String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
48−withSetupWHNF name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
49− bench name . whnfIO $ runSpiderHost (action a)
50−
51−micros :: [Benchmark]
52−micros =
53− [ bench "newIORef" $ whnfIO $ void $ newIORef ()
54− , env (newIORef (42 :: Int)) (bench "readIORef" . whnfIO . readIORef)
55− , bench "newTVar" $ whnfIO $ void $ newTVarIO ()
56− , env (newTVarIO (42 :: Int)) (bench "readTVar" . whnfIO . readTVarIO)
57− , bench "newEventWithTrigger" $ whnfIO . void $ runSpiderHost $ newEventWithTrigger $
58− \trigger -> return () <$ evaluate trigger
59− , bench "newEventWithTriggerRef" $ whnfIO . void $ runSpiderHost newEventWithTriggerRef
60− , withSetupWHNF "subscribeEvent" newEventWithTriggerRef $ subscribeEvent . fst
61− , withSetupWHNF "subscribeSwitch"
62− (join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)
63− (subscribeEvent . switch)
64− , withSetupWHNF "subscribeMerge(1)" (setupMerge 1) $ \(ev,_) -> subscribeEvent ev
65− , withSetupWHNF "subscribeMerge(100)" (setupMerge 100) (subscribeEvent . fst)
66− , withSetupWHNF "subscribeMerge(10000)" (setupMerge 10000) (subscribeEvent . fst)
67− , bench "runHostFrame" $ whnfIO $ runSpiderHost $ runHostFrame $ return ()
68− , withSetupWHNF "fireEventsAndRead(single/single)"
69− (newEventWithTriggerRef >>= subscribePair)
70− (\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)
71− , withSetupWHNF "fireEventsOnly"
72− (newEventWithTriggerRef >>= subscribePair)
73− (\(_, trigger) -> do
74− key <- fromJust <$> liftIO (readIORef trigger)
75− fireEvents [key :=> Identity (42 :: Int)])
76− , withSetupWHNF "fireEventsAndRead(head/merge1)"
77− (setupMerge 1 >>= subscribePair)
78− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
79− , withSetupWHNF "fireEventsAndRead(head/merge100)"
80− (setupMerge 100 >>= subscribePair)
81− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
82− , withSetupWHNF "fireEventsAndRead(head/merge10000)"
83− (setupMerge 10000 >>= subscribePair)
84− (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
85− , withSetupWHNF "fireEventsOnly(head/merge100)"
86− (setupMerge 100 >>= subscribePair)
87− (\(_, t:_) -> do
88− key <- fromJust <$> liftIO (readIORef t)
89− fireEvents [key :=> Identity (42 :: Int)])
90− , withSetupWHNF "hold" newEventWithTriggerRef $ \(ev, _) -> hold (42 :: Int) ev
91− , withSetupWHNF "sample" (newEventWithTriggerRef >>= hold (42 :: Int) . fst) sample
92− ]
93−
94−setupMerge :: Int
95− -> SpiderHost Global ( Event (SpiderTimeline Global) (DMap (Const2 Int a) Identity)
96− , [IORef (Maybe (EventTrigger Spider a))]
97− )
98−setupMerge num = do
99− (evs, triggers) <- unzip <$> replicateM num newEventWithTriggerRef
100− let !m = DMap.fromList [Const2 i :=> v | (i,v) <- zip [0..] evs]
101− pure (merge m, triggers)
102−
103−subscribePair :: (Event (SpiderTimeline Global) a, b) -> SpiderHost Global (EventHandle (SpiderTimeline Global) a, b)
104−subscribePair (ev, b) = (,b) <$> subscribeEvent ev
105−
106−fireAndRead :: IORef (Maybe (EventTrigger (SpiderTimeline Global) a)) -> a -> EventHandle (SpiderTimeline Global) b
107− -> SpiderHost Global (Maybe b)
108−fireAndRead trigger val subd = do
109− key <- fromJust <$> liftIO (readIORef trigger)
110− fireEventsAndRead [key :=> Identity val] $ readEvent subd >>= sequence
bench/RunAll.hsdeleted−157
@@ -1,157 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE ForeignFunctionInterface #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE PatternSynonyms #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TemplateHaskell #-}
13−{-# LANGUAGE TupleSections #-}
14−{-# LANGUAGE TypeSynonymInstances #-}
15−{-# LANGUAGE ViewPatterns #-}
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−
18−module Main where
19−
20−import Criterion.Main
21−import Criterion.Types
22−
23−import Reflex
24−import Reflex.Host.Class
25−
26−import Reflex.Plan.Reflex
27−import Reflex.TestPlan
28−
29−import qualified Reflex.Bench.Focused as Focused
30−import Reflex.Spider.Internal (SpiderEventHandle)
31−
32−import Control.Applicative
33−import Control.DeepSeq (NFData (..))
34−
35−import Prelude
36−import System.IO
37−import System.Mem
38−
39−import Control.Arrow
40−import Control.Concurrent
41−import Control.Concurrent.STM
42−import Control.Exception
43−import Control.Monad
44−import Control.Monad.Trans
45−import Data.Bool
46−import Data.Function
47−import Data.Int
48−import Data.IORef
49−import Data.Monoid
50−import Data.Time.Clock
51−import Debug.Trace.LocationTH
52−import GHC.Stats
53−import System.Environment
54−import System.Mem.Weak
55−import System.Process
56−import Text.Read
57−
58−import Unsafe.Coerce
59−
60−import Data.Map (Map)
61−import qualified Data.Map as Map
62−
63−type MonadReflexHost' t m = (MonadReflexHost t m, MonadIORef m, MonadIORef (HostFrame t))
64−
65−
66−setupFiring :: (MonadReflexHost t m, MonadIORef m) => Plan t (Event t a) -> m (EventHandle t a, Schedule t)
67−setupFiring p = do
68− (e, s) <- runPlan p
69− h <- subscribeEvent e
70− return (h, s)
71−
72−-- Hack to avoid the NFData constraint for EventHandle which is a synonym
73−newtype Ignore a = Ignore a
74−instance NFData (Ignore a) where
75− rnf !_ = ()
76−
77−instance NFData (SpiderEventHandle x a) where
78− rnf !_ = ()
79−
80−instance NFData (Behavior t a) where
81− rnf !_ = ()
82−
83−instance NFData (Firing t) where
84− rnf !_ = ()
85−
86−-- Measure the running time
87−benchFiring :: forall t m. (MonadReflexHost' t m, MonadSample t m) => (forall a. m a -> IO a) -> TestCase -> Int -> IO ()
88−benchFiring runHost tc n = runHost $ do
89− let runIterations :: m a -> m ()
90− runIterations test = replicateM_ (10*n) $ do
91− result <- test
92− liftIO $ evaluate result
93− case tc of
94− TestE p -> do
95− (h, s) <- setupFiring p
96− runIterations $ readSchedule_ s $ readEvent' h
97− TestB p -> do
98− (b, s) <- runPlan p
99− runIterations $ readSchedule_ (makeDense s) $ sample b
100−
101−waitForFinalizers :: IO ()
102−waitForFinalizers = do
103− performGC
104− x <- getCurrentTime
105− isFinalized <- newIORef False
106− mkWeakPtr x $ Just $ writeIORef isFinalized True
107− performGC
108− fix $ \loop -> do
109− f <- readIORef isFinalized
110− unless f $ do
111− threadDelay 1
112− loop
113−
114−benchmarks :: [(String, Int -> IO ())]
115−benchmarks = implGroup "spider" runSpiderHost cases
116− where
117− implGroup :: (MonadReflexHost' t m, MonadSample t m) => String -> (forall a. m a -> IO a) -> [(String, TestCase)] -> [(String, Int -> IO ())]
118− implGroup name runHost = group name . fmap (second (benchFiring runHost))
119− group name = fmap $ first ((name <> "/") <>)
120− sub n frames = group ("subscribing " ++ show (n, frames)) $ Focused.subscribing n frames
121− firing n = group ("firing " <> show n) $ Focused.firing n
122− merging n = group ("merging " <> show n) $ Focused.merging n
123− dynamics n = group ("dynamics " <> show n) $ Focused.dynamics n
124− cases = concat
125− [ sub 100 40
126− , dynamics 100
127− , dynamics 1000
128− , firing 1000
129− , firing 10000
130− , merging 10
131− , merging 50
132− , merging 100
133− , merging 200
134− ]
135−
136−pattern RunTestCaseFlag = "--run-test-case"
137−
138−spawnBenchmark :: String -> Benchmark
139−spawnBenchmark name = bench name . toBenchmarkable $ \n -> do
140− self <- getExecutablePath
141− callProcess self [RunTestCaseFlag, name, show n, "+RTS", "-N1"]
142−
143−foreign import ccall unsafe "myCapabilityHasOtherRunnableThreads" myCapabilityHasOtherRunnableThreads :: IO Bool
144−
145−main :: IO ()
146−main = do
147− args <- getArgs
148− case args of
149− RunTestCaseFlag : t -> case t of
150− [name, readMaybe -> Just count] -> do
151− case lookup name benchmarks of
152− Just testCase -> testCase count
153− performGC
154− fix $ \loop -> bool (return ()) (yield >> loop) =<< myCapabilityHasOtherRunnableThreads
155− return ()
156− _ -> $failure "--run-test-case: expected test name and iteration count to follow"
157− _ -> defaultMainWith (defaultConfig { timeLimit = 20, csvFile = Just "dmap-original.csv", reportFile = Just "report.html" }) $ fmap (spawnBenchmark . fst) benchmarks
cabal.haskell-cideleted−16
@@ -1,16 +0,0 @@
1−distribution: xenial
2−benchmarks: False
3−unconstrained: False
4−installed: -all
5−
6−-- https://github.com/haskell/cabal/issues/6106
7−install-dependencies: False
8−
9−constraint-set no-th
10− constraints: reflex -use-template-haskell
11−
12−constraint-set old-these
13− constraints: these <1
14−
15−constraint-set old-witherable
16− constraints: witherable <0.3.2
cabal.project.freezedeleted−1
@@ -1 +0,0 @@
1−constraints: any.text < 1.2.4.0
dep/reflex-platform/default.nix+7−6
@@ -1,7 +1,8 @@
11# DO NOT HAND-EDIT THIS FILE
2−import ((import <nixpkgs> {}).fetchFromGitHub (
3− let json = builtins.fromJSON (builtins.readFile ./github.json);
4− in { inherit (json) owner repo rev sha256;
5− private = json.private or false;
6− }
7−))
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.json+3−2
@@ -2,6 +2,7 @@
22 "owner": "reflex-frp",
33 "repo": "reflex-platform",
44 "branch": "master",
5− "rev": "510b990d0b11f0626afbec5fe8575b5b2395391b",
6− "sha256": "09cmahsbxr0963wq171c7j139iyzz49hramr4v9nsf684wcwkngv"
5+ "private": false,
6+ "rev": "c9d11db1b98855fe8ab24a3ff6a5dbe0ad902ad9",
7+ "sha256": "0sfzkqdvyah5mwvmli0wq1nl0b8cvk2cmfgfy4rz57wv42x3099y"
78}
patch.cabalnew file+100
@@ -0,0 +1,100 @@
1+Name: patch
2+Version: 0.0.5.0
3+Synopsis: Data structures for describing changes to other data structures.
4+Description:
5+ Data structures for describing changes to other data structures.
6+ .
7+ In this library, a patch is something which can be applied, analogous to a
8+ function, and which distinguishes returning the argument it was provided from
9+ returning something else.
10+License: BSD3
11+License-file: LICENSE
12+Author: Ryan Trinkle
13+Maintainer: maintainer@obsidian.systems
14+Stability: Experimental
15+Category: FRP
16+Build-type: Simple
17+Cabal-version: >=1.10
18+homepage: https://obsidian.systems
19+bug-reports: https://github.com/reflex-frp/patch/issues
20+extra-source-files:
21+ README.md
22+ ChangeLog.md
23+
24+tested-with:
25+ GHC ==8.0.2 || ==8.2.2 || ==8.4.4 || ==8.6.5 || ==8.8.1
26+ GHCJS ==8.4
27+
28+flag split-these
29+ description: Use split these/semialign packages
30+ manual: False
31+ default: True
32+
33+library
34+ hs-source-dirs: src
35+ default-language: Haskell2010
36+ build-depends: base >= 4.9 && < 4.15
37+ , constraints-extras >= 0.3 && < 0.4
38+ , containers >= 0.6 && < 0.7
39+ , dependent-map >= 0.3 && < 0.5
40+ , dependent-sum >= 0.6 && < 0.8
41+ , lens >= 4.7 && < 5
42+ , semigroupoids >= 4.0 && < 6
43+ , transformers >= 0.5.6.0 && < 0.6
44+ , witherable >= 0.3 && < 0.5
45+
46+ if impl(ghc < 8.6) -- really, if base < 8.12
47+ build-depends: base-orphans >= 0.8 && < 0.9
48+
49+ exposed-modules: Data.Functor.Misc
50+ , Data.Monoid.DecidablyEmpty
51+ , Data.Patch
52+ , Data.Patch.Class
53+ , Data.Patch.DMap
54+ , Data.Patch.DMapWithMove
55+ , Data.Patch.IntMap
56+ , Data.Patch.Map
57+ , Data.Patch.MapWithMove
58+ , Data.Patch.MapWithPatchingMove
59+ , Data.Semigroup.Additive
60+
61+ ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs
62+ default-extensions: PolyKinds
63+
64+ if flag(split-these)
65+ build-depends: these >= 1 && <1.2
66+ , semialign >=1 && <1.2
67+ , monoidal-containers >= 0.6 && < 0.7
68+ else
69+ build-depends: these >= 0.4 && <0.9
70+ , monoidal-containers == 0.4.0.0
71+
72+test-suite tests
73+ default-language: Haskell2010
74+ type: exitcode-stdio-1.0
75+ main-is: tests.hs
76+ hs-source-dirs: test
77+ build-depends: base
78+ , patch
79+ , containers
80+ , hedgehog
81+ , HUnit
82+ if impl(ghcjs)
83+ buildable: False
84+
85+test-suite hlint
86+ default-language: Haskell2010
87+ type: exitcode-stdio-1.0
88+ main-is: hlint.hs
89+ hs-source-dirs: test
90+ build-depends: base
91+ , directory
92+ , filepath
93+ , filemanip
94+ , hlint (< 2.1 || >= 2.2.2) && < 3.3
95+ if impl(ghcjs)
96+ buildable: False
97+
98+source-repository head
99+ type: git
100+ location: https://github.com/reflex-frp/patch
reflex.cabaldeleted−399
@@ -1,399 +0,0 @@
1−Name: reflex
2−Version: 0.6.3
3−Synopsis: Higher-order Functional Reactive Programming
4−Description: Reflex is a high-performance, deterministic, higher-order Functional Reactive Programming system
5−License: BSD3
6−License-file: LICENSE
7−Author: Ryan Trinkle
8−Maintainer: ryan.trinkle@gmail.com
9−Stability: Experimental
10−Category: FRP
11−Build-type: Simple
12−Cabal-version: >=1.9.2
13−homepage: https://reflex-frp.org
14−bug-reports: https://github.com/reflex-frp/reflex/issues
15−extra-source-files:
16− README.md
17− Quickref.md
18− ChangeLog.md
19−
20−tested-with:
21− GHC ==8.0.2 || ==8.2.2 || ==8.4.4 || ==8.6.5,
22− GHCJS ==8.4
23−
24−flag use-reflex-optimizer
25− description: Use the GHC plugin Reflex.Optimizer on some of the modules in the package. This is still experimental.
26− default: False
27− manual: True
28−
29−flag use-template-haskell
30− description: Use template haskell to generate lenses
31− default: True
32− manual: True
33−
34−flag debug-trace-events
35− description: Add instrumentation that outputs the stack trace of the definition of an event whenever it is subscribed to. Warning: It is very slow!
36− default: False
37− manual: True
38−
39−flag fast-weak
40− description: Use the primitive implementation of FastWeak in GHCJS; note that this requires GHCJS to be built with FastWeak and FastWeakBag present in the RTS, which is not the default
41− default: False
42− manual: True
43−
44−flag split-these
45− description: Use split these/semialign packages
46− manual: False
47− default: True
48−
49−library
50− hs-source-dirs: src
51− build-depends:
52− MemoTrie == 0.6.*,
53− base >= 4.9 && < 4.13,
54− bifunctors >= 5.2 && < 5.6,
55− comonad >= 5.0.4 && < 5.1,
56− constraints-extras >= 0.3 && < 0.4,
57− containers >= 0.6 && < 0.7,
58− data-default >= 0.5 && < 0.8,
59− dependent-map >= 0.3 && < 0.4,
60− exception-transformers == 0.4.*,
61− lens >= 4.7 && < 5,
62− monad-control >= 1.0.1 && < 1.1,
63− mtl >= 2.1 && < 2.3,
64− prim-uniq >= 0.1.0.1 && < 0.2,
65− primitive >= 0.5 && < 0.8,
66− profunctors >= 5.3 && < 5.5,
67− random == 1.1.*,
68− ref-tf == 0.4.*,
69− reflection == 2.1.*,
70− semigroupoids >= 4.0 && < 6,
71− stm >= 2.4 && < 2.6,
72− syb >= 0.5 && < 0.8,
73− time >= 1.4 && < 1.9,
74− transformers >= 0.5.6.0 && < 0.6,
75− unbounded-delays >= 0.1.0.0 && < 0.2,
76− witherable >= 0.3 && < 0.3.2
77−
78− if flag(split-these)
79− build-depends: these >= 1 && <1.1,
80− semialign >=1 && <1.2,
81− monoidal-containers >= 0.6 && < 0.7
82− else
83− build-depends: these >= 0.4 && <0.9,
84− monoidal-containers == 0.4.0.0
85−
86− exposed-modules:
87− Control.Monad.ReaderIO
88− Data.AppendMap,
89− Data.FastMutableIntMap,
90− Data.FastWeakBag,
91− Data.Functor.Misc,
92− Data.Map.Misc,
93− Data.WeakBag,
94− Reflex,
95− Reflex.Class,
96− Reflex.Adjustable.Class,
97− Reflex.BehaviorWriter.Base,
98− Reflex.BehaviorWriter.Class,
99− Reflex.Collection,
100− Reflex.Dynamic,
101− Reflex.Dynamic.Uniq,
102− Reflex.DynamicWriter,
103− Reflex.DynamicWriter.Base,
104− Reflex.DynamicWriter.Class,
105− Reflex.EventWriter,
106− Reflex.EventWriter.Base,
107− Reflex.EventWriter.Class,
108− Reflex.FastWeak,
109− Reflex.FunctorMaybe,
110− Reflex.Host.Class,
111− Reflex.Network,
112− Reflex.NotReady.Class,
113− Reflex.Patch,
114− Reflex.Patch.Class,
115− Reflex.Patch.DMap,
116− Reflex.Patch.DMapWithMove,
117− Reflex.Patch.IntMap,
118− Reflex.Patch.Map,
119− Reflex.Patch.MapWithMove,
120− Reflex.PerformEvent.Base,
121− Reflex.PerformEvent.Class,
122− Reflex.PostBuild.Base,
123− Reflex.PostBuild.Class,
124− Reflex.Profiled,
125− Reflex.Pure,
126− Reflex.Query.Base,
127− Reflex.Query.Class,
128− Reflex.Requester.Base,
129− Reflex.Requester.Class,
130− Reflex.Spider,
131− Reflex.Spider.Internal,
132− Reflex.Time,
133− Reflex.TriggerEvent.Base,
134− Reflex.TriggerEvent.Class,
135− Reflex.Widget.Basic,
136− Reflex.Workflow
137−
138− ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs -funbox-strict-fields -O2 -fspecialise-aggressively
139−
140− if flag(debug-trace-events)
141− cpp-options: -DDEBUG_TRACE_EVENTS
142− build-depends: bytestring
143−
144− if flag(use-reflex-optimizer)
145− cpp-options: -DUSE_REFLEX_OPTIMIZER
146− build-depends: ghc
147− exposed-modules: Reflex.Optimizer
148−
149− if flag(use-template-haskell)
150− cpp-options: -DUSE_TEMPLATE_HASKELL
151− build-depends:
152− dependent-sum >= 0.6 && < 0.7,
153− haskell-src-exts >= 1.16 && < 1.22,
154− haskell-src-meta >= 0.6 && < 0.9,
155− template-haskell >= 2.9 && < 2.15
156− exposed-modules:
157− Reflex.Dynamic.TH
158− other-extensions: TemplateHaskell
159− else
160− build-depends:
161− dependent-sum >= 0.6 && < 0.7
162−
163− if flag(fast-weak) && impl(ghcjs)
164− cpp-options: -DGHCJS_FAST_WEAK
165−
166− if impl(ghcjs)
167− build-depends: ghcjs-base
168−
169−test-suite semantics
170− type: exitcode-stdio-1.0
171− main-is: semantics.hs
172− hs-source-dirs: test
173− ghc-options: -O2 -Wall -rtsopts
174− build-depends:
175− base,
176− bifunctors,
177− containers,
178− deepseq,
179− dependent-map,
180− dependent-sum,
181− mtl,
182− ref-tf,
183− reflex,
184− split,
185− transformers
186− other-modules:
187− Reflex.Bench.Focused
188− Reflex.Plan.Pure
189− Reflex.Plan.Reflex
190− Reflex.Test
191− Reflex.Test.Micro
192− Reflex.TestPlan
193−
194−test-suite CrossImpl
195− type: exitcode-stdio-1.0
196− main-is: Reflex/Test/CrossImpl.hs
197− hs-source-dirs: test
198− ghc-options: -O2 -Wall -rtsopts
199− build-depends:
200− base,
201− containers,
202− dependent-map,
203− dependent-sum,
204− deepseq,
205− mtl,
206− transformers,
207− ref-tf,
208− reflex
209− other-modules:
210− Reflex.Test
211− Reflex.TestPlan
212− Reflex.Plan.Reflex
213− Reflex.Plan.Pure
214−
215−test-suite hlint
216− type: exitcode-stdio-1.0
217− main-is: hlint.hs
218− hs-source-dirs: test
219− build-depends: base
220− , directory
221− , filepath
222− , filemanip
223− , hlint < 2.1 || >= 2.2.2
224− if impl(ghcjs)
225− buildable: False
226−
227−test-suite EventWriterT
228− type: exitcode-stdio-1.0
229− main-is: EventWriterT.hs
230− hs-source-dirs: test
231− build-depends: base
232− , containers
233− , deepseq
234− , dependent-map
235− , dependent-sum
236− , lens
237− , mtl
238− , these
239− , transformers
240− , reflex
241− , ref-tf
242−
243− if flag(split-these)
244− build-depends: these-lens
245−
246− other-modules:
247− Reflex.Test
248− Reflex.TestPlan
249− Reflex.Plan.Reflex
250− Reflex.Plan.Pure
251− Test.Run
252−
253−
254−test-suite RequesterT
255− type: exitcode-stdio-1.0
256− main-is: RequesterT.hs
257− hs-source-dirs: test
258− build-depends: base
259− , containers
260− , deepseq
261− , dependent-sum
262− , dependent-map
263− , lens
264− , mtl
265− , these
266− , transformers
267− , reflex
268− , ref-tf
269−
270− if flag(split-these)
271− build-depends: these-lens
272−
273− other-modules:
274− Reflex.TestPlan
275− Reflex.Plan.Pure
276− Test.Run
277−
278−test-suite QueryT
279− type: exitcode-stdio-1.0
280− main-is: QueryT.hs
281− hs-source-dirs: test
282− build-depends: base
283− , containers
284− , dependent-map
285− , dependent-sum
286− , deepseq
287− , lens
288− , monoidal-containers
289− , mtl
290− , ref-tf
291− , reflex
292− , these
293− , transformers
294−
295− if flag(split-these)
296− build-depends: semialign, these-lens
297−
298− other-modules:
299− Test.Run
300− Reflex.TestPlan
301− Reflex.Plan.Reflex
302− Reflex.Plan.Pure
303−
304−test-suite GC-Semantics
305− type: exitcode-stdio-1.0
306− main-is: GC.hs
307− hs-source-dirs: test
308− build-depends: base
309− , containers
310− , dependent-sum
311− , dependent-map
312− , deepseq
313− , mtl
314− , these
315− , transformers
316− , reflex
317− , ref-tf
318−
319− if flag(split-these)
320− build-depends: semialign
321−
322− other-modules:
323− Reflex.Plan.Pure
324− Reflex.Plan.Reflex
325− Reflex.TestPlan
326− Test.Run
327−
328−test-suite rootCleanup
329− type: exitcode-stdio-1.0
330− main-is: rootCleanup.hs
331− hs-source-dirs: test
332− build-depends: base
333− , containers
334− , deepseq
335− , dependent-sum
336− , mtl
337− , reflex
338− , ref-tf
339− , these
340− other-modules:
341− Reflex.Plan.Pure
342− Reflex.TestPlan
343− Test.Run
344−
345−benchmark spider-bench
346− type: exitcode-stdio-1.0
347− hs-source-dirs: bench test
348− main-is: Main.hs
349− ghc-options: -Wall -O2 -rtsopts
350− build-depends:
351− base,
352− containers,
353− criterion,
354− deepseq,
355− dependent-map,
356− dependent-sum,
357− ref-tf,
358− mtl,
359− primitive,
360− reflex,
361− split,
362− stm,
363− transformers
364− other-modules:
365− Reflex.TestPlan
366− Reflex.Plan.Reflex
367− Reflex.Bench.Focused
368−
369−benchmark saulzar-bench
370− type: exitcode-stdio-1.0
371− hs-source-dirs: bench test
372− c-sources: bench-cbits/checkCapability.c
373− main-is: RunAll.hs
374− ghc-options: -Wall -O2 -rtsopts -threaded
375− build-depends:
376− base,
377− containers,
378− criterion,
379− deepseq,
380− dependent-map,
381− dependent-sum,
382− loch-th,
383− mtl,
384− primitive,
385− process,
386− ref-tf,
387− reflex,
388− split,
389− stm,
390− time,
391− transformers
392− other-modules:
393− Reflex.TestPlan
394− Reflex.Plan.Reflex
395− Reflex.Bench.Focused
396−
397−source-repository head
398− type: git
399− location: https://github.com/reflex-frp/reflex
release.nix+23−32
@@ -17,42 +17,33 @@ let
1717 ] ++ lib.optionals (reflex-platform.iosSupport) [
1818 "ghcIosAarch64"
1919 ];
20− variations = map (v: "reflex" + v) [
21− "-dontUseTemplateHaskell"
22− ""
23− ];
2420 compilerPkgs = lib.genAttrs compilers (ghc: let
25− variationPkgs = lib.genAttrs variations (variation: let
26− reflex-platform = reflex-platform-fun {
27− inherit system;
28− __useTemplateHaskell = variation == "reflex"; # TODO hack
29− haskellOverlays = [
30− # Use this package's source for reflex
31− (self: super: {
32− _dep = super._dep // {
33− reflex = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
34− "release.nix"
35− ".git"
36− "dist"
37− "cabal.haskell-ci"
38− "cabal.project"
39− ".travis.yml"
40− ])) ./.;
41− };
42− })
43− ];
44− };
45− in reflex-platform.${ghc}.reflex);
46− in variationPkgs // {
47− cache = reflex-platform.pinBuildInputs "reflex-${system}-${ghc}"
48− (builtins.attrValues variationPkgs);
49− });
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);
5041 in compilerPkgs // {
51− cache = reflex-platform.pinBuildInputs "reflex-${system}"
52− (map (a: a.cache) (builtins.attrValues compilerPkgs));
42+ cache = reflex-platform.pinBuildInputs "patch-${system}"
43+ (builtins.attrValues compilerPkgs);
5344 });
5445
55− metaCache = native-reflex-platform.pinBuildInputs "reflex-everywhere"
46+ metaCache = native-reflex-platform.pinBuildInputs "patch-everywhere"
5647 (map (a: a.cache) (builtins.attrValues perPlatform));
5748
5849in perPlatform // { inherit metaCache; }
src/Control/Monad/ReaderIO.hsdeleted−60
@@ -1,60 +0,0 @@
1−{-# language RoleAnnotations #-}
2−{-# language MultiParamTypeClasses #-}
3−{-# language FlexibleInstances #-}
4−{-# language CPP #-}
5−module Control.Monad.ReaderIO
6− (
7− ReaderIO (..)
8− )
9− where
10−
11−import Control.Monad.Fix
12−#if MIN_VERSION_base(4,10,0)
13−import Control.Applicative
14−#endif
15−import Control.Monad
16−import Control.Monad.Reader.Class
17−import Control.Monad.IO.Class
18−
19−-- | An approximate clone of @RIO@ from the @rio@ package, but not based on
20−-- @ReaderT@. The trouble with @ReaderT@ is that its third type argument has a
21−-- @nominal@ role, so we can't coerce through it when it's wrapped in some
22−-- other @data@ type. Ugh.
23−newtype ReaderIO e a = ReaderIO { runReaderIO :: e -> IO a }
24−type role ReaderIO representational representational
25−
26−instance Functor (ReaderIO e) where
27− fmap = liftM
28− {-# INLINE fmap #-}
29− a <$ m = m >> pure a
30− {-# INLINE (<$) #-}
31−
32−instance Applicative (ReaderIO e) where
33− pure a = ReaderIO $ \_ -> pure a
34− {-# INLINE pure #-}
35− (<*>) = ap
36− {-# INLINE (<*>) #-}
37−#if MIN_VERSION_base(4,10,0)
38− liftA2 = liftM2
39− {-# INLINE liftA2 #-}
40−#endif
41− (*>) = (>>)
42− {-# INLINE (*>) #-}
43−
44−instance Monad (ReaderIO e) where
45− ReaderIO q >>= f = ReaderIO $ \e -> q e >>= \a -> runReaderIO (f a) e
46− {-# INLINE (>>=) #-}
47−
48−instance MonadFix (ReaderIO e) where
49− mfix f = ReaderIO $ \e -> mfix $ \r -> runReaderIO (f r) e
50− {-# INLINE mfix #-}
51−
52−instance MonadIO (ReaderIO e) where
53− liftIO m = ReaderIO $ \_ -> m
54− {-# INLINE liftIO #-}
55−
56−instance MonadReader e (ReaderIO e) where
57− ask = ReaderIO pure
58− {-# INLINE ask #-}
59− local f (ReaderIO m) = ReaderIO (m . f)
60− {-# INLINE local #-}
src/Data/AppendMap.hsdeleted−84
@@ -1,84 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE PatternSynonyms #-}
6−{-# LANGUAGE RoleAnnotations #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# OPTIONS_GHC -fno-warn-orphans #-}
10−-- |
11−-- Module:
12−-- Data.AppendMap
13−-- Description:
14−-- Instances and convenience functions for 'Data.Map.Monoidal'. We use
15−-- monoidal-containers to take advantage of its better monoid instance.
16−-- 'Data.Map' has @mappend = union@, which is left-biased. 'MonoidalMap'
17−-- has @mappend = unionWith mappend@ instead.
18−module Data.AppendMap
19− ( module Data.AppendMap
20− , module Data.Map.Monoidal
21− ) where
22−
23−import Prelude hiding (null)
24−
25−import Data.Coerce
26−import Data.Default
27−import Data.Map (Map)
28−#if MIN_VERSION_containers(0,5,11)
29−import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith)
30−#else
31−import qualified Data.Map as Map (showTree, showTreeWith)
32−#endif
33−import qualified Data.Witherable as W
34−import Data.Map.Monoidal
35−import qualified Data.Map.Monoidal as MonoidalMap
36−
37−
38−{-# DEPRECATED AppendMap "Use 'MonoidalMap' instead" #-}
39−-- | AppendMap is a synonym for 'Data.Map.Monoidal.MonoidalMap'
40−type AppendMap = MonoidalMap
41−
42−{-# DEPRECATED _unAppendMap "Use 'getMonoidalMap' instead" #-}
43−-- | A synonym for 'getMonoidalMap'
44−_unAppendMap :: MonoidalMap k v -> Map k v
45−_unAppendMap = getMonoidalMap
46−
47−-- | Pattern synonym for 'MonoidalMap'
48−pattern AppendMap :: Map k v -> MonoidalMap k v
49−pattern AppendMap m = MonoidalMap m
50−
51−#if !MIN_VERSION_witherable(0,3,2)
52−instance W.Filterable (MonoidalMap k) where
53− mapMaybe = MonoidalMap.mapMaybe
54−#endif
55−
56−-- | Deletes a key, returning 'Nothing' if the result is empty.
57−nonEmptyDelete :: Ord k => k -> MonoidalMap k a -> Maybe (MonoidalMap k a)
58−nonEmptyDelete k vs =
59− let deleted = delete k vs
60− in if null deleted
61− then Nothing
62− else Just deleted
63−
64−-- | Like 'mapMaybe' but indicates whether the resulting container is empty
65−mapMaybeNoNull :: (a -> Maybe b)
66− -> MonoidalMap token a
67− -> Maybe (MonoidalMap token b)
68−mapMaybeNoNull f as =
69− let bs = mapMaybe f as
70− in if null bs
71− then Nothing
72− else Just bs
73−
74−-- TODO: Move instances to `Reflex.Patch`
75−-- | Displays a 'MonoidalMap' as a tree. See 'Data.Map.Lazy.showTree' for details.
76−showTree :: forall k a. (Show k, Show a) => MonoidalMap k a -> String
77−showTree = coerce (Map.showTree :: Map k a -> String)
78−
79−-- | Displays a 'MonoidalMap' as a tree, using the supplied function to convert nodes to string.
80−showTreeWith :: forall k a. (k -> a -> String) -> Bool -> Bool -> MonoidalMap k a -> String
81−showTreeWith = coerce (Map.showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String)
82−
83−instance Default (MonoidalMap k a) where
84− def = empty
src/Data/FastMutableIntMap.hsdeleted−93
@@ -1,93 +0,0 @@
1−{-# LANGUAGE TypeFamilies #-}
2−-- |
3−-- Module:
4−-- Data.FastMutableIntMap
5−-- Description:
6−-- A mutable version of 'IntMap'
7−module Data.FastMutableIntMap
8− ( FastMutableIntMap
9− , new
10− , newEmpty
11− , insert
12− , isEmpty
13− , getFrozenAndClear
14− , size
15− , applyPatch
16− , PatchIntMap (..)
17− , traverseIntMapPatchWithKey
18− , lookup
19− , forIntersectionWithImmutable_
20− , for_
21− , patchIntMapNewElements
22− , patchIntMapNewElementsMap
23− , getDeletions
24− ) where
25−
26−--TODO: Pure JS version
27−--TODO: Fast copy to FastIntMap
28−--TODO: Fast patch type
29−
30−import Prelude hiding (lookup)
31−
32−import Control.Monad.IO.Class
33−import Data.Foldable (traverse_)
34−import Data.IntMap.Strict (IntMap)
35−import qualified Data.IntMap.Strict as IntMap
36−import Data.IORef
37−import Reflex.Patch.Class
38−import Reflex.Patch.IntMap
39−
40−-- | A 'FastMutableIntMap' holds a map of values of type @a@ and allows low-overhead modifications via IO.
41−-- Operations on 'FastMutableIntMap' run in IO.
42−newtype FastMutableIntMap a = FastMutableIntMap (IORef (IntMap a))
43−
44−-- | Create a new 'FastMutableIntMap' out of an 'IntMap'
45−new :: IntMap a -> IO (FastMutableIntMap a)
46−new m = FastMutableIntMap <$> newIORef m
47−
48−-- | Create a new empty 'FastMutableIntMap'
49−newEmpty :: IO (FastMutableIntMap a)
50−newEmpty = FastMutableIntMap <$> newIORef IntMap.empty
51−
52−-- | Insert an element into a 'FastMutableIntMap' at the given key
53−insert :: FastMutableIntMap a -> Int -> a -> IO ()
54−insert (FastMutableIntMap r) k v = modifyIORef' r $ IntMap.insert k v
55−
56−-- | Attempt to lookup an element by key in a 'FastMutableIntMap'
57−lookup :: FastMutableIntMap a -> Int -> IO (Maybe a)
58−lookup (FastMutableIntMap r) k = IntMap.lookup k <$> readIORef r
59−
60−-- | Runs the provided action over the intersection of a 'FastMutableIntMap' and an 'IntMap'
61−forIntersectionWithImmutable_ :: MonadIO m => FastMutableIntMap a -> IntMap b -> (a -> b -> m ()) -> m ()
62−forIntersectionWithImmutable_ (FastMutableIntMap r) b f = do
63− a <- liftIO $ readIORef r
64− traverse_ (uncurry f) $ IntMap.intersectionWith (,) a b
65−
66−-- | Runs the provided action over the values of a 'FastMutableIntMap'
67−for_ :: MonadIO m => FastMutableIntMap a -> (a -> m ()) -> m ()
68−for_ (FastMutableIntMap r) f = do
69− a <- liftIO $ readIORef r
70− traverse_ f a
71−
72−-- | Checks whether a 'FastMutableIntMap' is empty
73−isEmpty :: FastMutableIntMap a -> IO Bool
74−isEmpty (FastMutableIntMap r) = IntMap.null <$> readIORef r
75−
76−-- | Retrieves the size of a 'FastMutableIntMap'
77−size :: FastMutableIntMap a -> IO Int
78−size (FastMutableIntMap r) = IntMap.size <$> readIORef r
79−
80−-- | Make an immutable snapshot of the datastructure and clear it
81−getFrozenAndClear :: FastMutableIntMap a -> IO (IntMap a)
82−getFrozenAndClear (FastMutableIntMap r) = do
83− result <- readIORef r
84− writeIORef r IntMap.empty
85− return result
86−
87−-- | Updates the value of a 'FastMutableIntMap' with the given patch (see 'Reflex.Patch.IntMap'),
88−-- and returns an 'IntMap' with the modified keys and values.
89−applyPatch :: FastMutableIntMap a -> PatchIntMap a -> IO (IntMap a)
90−applyPatch (FastMutableIntMap r) p@(PatchIntMap m) = do
91− v <- readIORef r
92− writeIORef r $! applyAlways p v
93− return $ IntMap.intersection v m
src/Data/FastWeakBag.hsdeleted−161
@@ -1,161 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−#ifdef USE_REFLEX_OPTIMIZER
4−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5−#endif
6−#ifdef GHCJS_FAST_WEAK
7−{-# LANGUAGE ForeignFunctionInterface #-}
8−{-# LANGUAGE JavaScriptFFI #-}
9−#endif
10−-- | This module defines the 'FastWeakBag' type, which represents a mutable
11−-- collection of items that does not cause the items to be retained in memory.
12−-- This is useful for situations where a value needs to be inspected or modified
13−-- if it is still alive, but can be ignored if it is dead.
14−module Data.FastWeakBag
15− ( FastWeakBag
16− , FastWeakBagTicket
17− , empty
18− , isEmpty
19− , insert
20− , traverse
21− , traverse_
22− , remove
23− -- * Internal functions
24− -- These will not always be available.
25−#ifndef GHCJS_FAST_WEAK
26− , _weakBag_children --TODO: Don't export this
27−#endif
28− ) where
29−
30−import Prelude hiding (traverse)
31−
32−import Control.Monad
33−import Control.Monad.IO.Class
34−
35−#ifdef GHCJS_FAST_WEAK
36−import GHCJS.Types
37−import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)
38−#else
39−import Control.Exception
40−import Data.IntMap.Strict (IntMap)
41−import qualified Data.IntMap.Strict as IntMap
42−import Data.IORef
43−import System.Mem.Weak
44−#endif
45−
46−-- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them -
47−-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
48−-- alive, the 'FastWeakBag' will continue to refer to them.
49−#ifdef GHCJS_FAST_WEAK
50−newtype FastWeakBag a = FastWeakBag JSVal
51−#else
52−data FastWeakBag a = FastWeakBag
53− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
54− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'
55− }
56−#endif
57−
58−-- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned. If
59−-- the caller retains the ticket, the item is guranteed to stay in memory (and
60−-- thus in the 'FastWeakBag'). The ticket can also be used to remove the item from
61−-- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.
62−#ifdef GHCJS_FAST_WEAK
63−newtype FastWeakBagTicket a = FastWeakBagTicket JSVal
64−#else
65−data FastWeakBagTicket a = FastWeakBagTicket
66− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
67− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
68− }
69−#endif
70−
71−-- | Insert an item into a 'FastWeakBag'.
72−{-# INLINE insert #-}
73−insert :: a -- ^ The item
74− -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into
75− -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item
76− -- is retained and allows the item to be removed.
77−#ifdef GHCJS_FAST_WEAK
78−insert a wb = js_insert (unsafeToRawJSVal a) wb
79−foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)
80−#else
81−insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do
82− a' <- evaluate a
83− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
84− let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())
85− wa <- mkWeakPtr a' $ Just cleanup
86− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
87− return $ FastWeakBagTicket
88− { _weakBagTicket_weakItem = wa
89− , _weakBagTicket_item = a'
90− }
91−#endif
92−
93−-- | Create an empty 'FastWeakBag'.
94−{-# INLINE empty #-}
95−empty :: IO (FastWeakBag a)
96−#ifdef GHCJS_FAST_WEAK
97−empty = js_empty
98−foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)
99−#else
100−empty = {-# SCC "empty" #-} do
101− nextId <- newIORef 1
102− children <- newIORef IntMap.empty
103− let bag = FastWeakBag
104− { _weakBag_nextId = nextId
105− , _weakBag_children = children
106− }
107− return bag
108−#endif
109−
110−-- | Check whether a 'FastWeakBag' is empty.
111−{-# INLINE isEmpty #-}
112−isEmpty :: FastWeakBag a -> IO Bool
113−#ifdef GHCJS_FAST_WEAK
114−isEmpty = js_isEmpty
115−foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time
116−#else
117−isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)
118−#endif
119−
120−{-# INLINE traverse_ #-}
121−-- | Visit every node in the given list. If new nodes are appended during the
122−-- traversal, they will not be visited. Every live node that was in the list
123−-- when the traversal began will be visited exactly once; however, no guarantee
124−-- is made about the order of the traversal.
125−traverse_ :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
126−#ifdef GHCJS_FAST_WEAK
127−traverse_ wb f = do
128− let go cursor = when (not $ js_isNull cursor) $ do
129− val <- liftIO $ js_getTicketValue cursor
130− f $ unsafeFromRawJSVal val
131− go =<< liftIO (js_getNext (FastWeakBagTicket cursor))
132− go =<< liftIO (js_getInitial wb)
133−foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
134−foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal
135−--TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag
136−foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
137−#else
138−traverse_ (FastWeakBag _ children) f = {-# SCC "traverse_" #-} do
139− cs <- liftIO $ readIORef children
140− forM_ cs $ \c -> do
141− ma <- liftIO $ deRefWeak c
142− mapM_ f ma
143−#endif
144−
145−{-# DEPRECATED traverse "Use 'traverse_' instead" #-}
146−traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
147−traverse = traverse_
148−
149−-- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times
150−-- on the same 'FastWeakBagTicket'.
151−{-# INLINE remove #-}
152−remove :: FastWeakBagTicket a -> IO ()
153−#ifdef GHCJS_FAST_WEAK
154−remove = js_remove
155−foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here
156−#else
157−remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w
158−#endif
159−--TODO: Should 'remove' also drop the reference to the item?
160−
161−--TODO: can/should we provide a null FastWeakBagTicket?
src/Data/Functor/Misc.hs+4−7
@@ -6,14 +6,10 @@
66{-# LANGUAGE GADTs #-}
77{-# LANGUAGE LambdaCase #-}
88{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE PatternSynonyms #-}
109{-# LANGUAGE PolyKinds #-}
1110{-# LANGUAGE RankNTypes #-}
1211{-# LANGUAGE ScopedTypeVariables #-}
1312{-# LANGUAGE StandaloneDeriving #-}
14−#ifdef USE_REFLEX_OPTIMIZER
15−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
16−#endif
1713-- | This module provides types and functions with no particular theme, but
1814-- which are relevant to the use of 'Functor'-based datastructures like
1915-- 'Data.Dependent.Map.DMap'.
@@ -41,18 +37,19 @@ module Data.Functor.Misc
4137 ) where
4238
4339import Control.Applicative ((<$>))
44−import Control.Monad.Identity
4540import Data.Dependent.Map (DMap)
4641import qualified Data.Dependent.Map as DMap
4742import Data.Dependent.Sum
43+import Data.Functor.Identity
4844import Data.GADT.Compare
4945import Data.GADT.Show
5046import Data.IntMap (IntMap)
5147import qualified Data.IntMap as IntMap
5248import Data.Map (Map)
5349import qualified Data.Map as Map
54−import Data.Some (Some(Some))
50+import Data.Some (Some, mkSome)
5551import Data.These
52+import Data.Type.Equality ((:~:)(Refl))
5653import Data.Typeable hiding (Refl)
5754
5855--------------------------------------------------------------------------------
@@ -119,7 +116,7 @@ intMapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=
119116-- | Convert a 'DMap' to a regular 'Map' by forgetting the types associated with
120117-- the keys, using a function to remove the wrapping 'Functor'
121118weakenDMapWith :: (forall a. v a -> v') -> DMap k v -> Map (Some k) v'
122−weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (Some k, f v)) . DMap.toAscList
119+weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (mkSome k, f v)) . DMap.toAscList
123120
124121--------------------------------------------------------------------------------
125122-- WrapArg
src/Data/Map/Misc.hsdeleted−71
@@ -1,71 +0,0 @@
1−{-# LANGUAGE LambdaCase #-}
2−-- | Additional functions for manipulating 'Map's.
3−module Data.Map.Misc
4− (
5− -- * Working with Maps
6− diffMapNoEq
7− , diffMap
8− , applyMap
9− , mapPartitionEithers
10− , applyMapKeysSet
11− ) where
12−
13−import Data.Align
14−import Data.Map (Map)
15−import qualified Data.Map as Map
16−import Data.Maybe
17−import Data.Set (Set)
18−import qualified Data.Set as Set
19−import Data.These
20−
21−-- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new@ respectively. @Just@ represents an association present in @new@ and @Nothing@
22−-- represents an association only present in @old@ but no longer present in @new@.
23−--
24−-- Similar to 'diffMap' but doesn't require 'Eq' on the values, thus can't tell if a value has changed or not.
25−diffMapNoEq :: (Ord k) => Map k v -> Map k v -> Map k (Maybe v)
26−diffMapNoEq olds news = flip Map.mapMaybe (align olds news) $ \case
27− This _ -> Just Nothing
28− These _ new -> Just $ Just new
29− That new -> Just $ Just new
30−
31−-- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new respectively. @Just@ represents an association present in @new@ and either not
32−-- present in @old@ or where the value has changed. @Nothing@ represents an association only present in @old@ but no longer present in @new@.
33−--
34−-- See also 'diffMapNoEq' for a similar but weaker version which does not require 'Eq' on the values but thus can't indicated a value not changing between
35−-- @old@ and @new@ with @Nothing@.
36−diffMap :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (Maybe v)
37−diffMap olds news = flip Map.mapMaybe (align olds news) $ \case
38− This _ -> Just Nothing
39− These old new
40− | old == new -> Nothing
41− | otherwise -> Just $ Just new
42− That new -> Just $ Just new
43−
44−-- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new map from the given input @'Map' k v@.
45−--
46−-- See also 'Reflex.Patch.Map' and 'Reflex.Patch.MapWithMove'.
47−applyMap :: Ord k => Map k (Maybe v) -> Map k v -> Map k v
48−applyMap patch old = insertions `Map.union` (old `Map.difference` deletions)
49− where (deletions, insertions) = Map.mapEither maybeToEither patch
50− maybeToEither = \case
51− Nothing -> Left ()
52− Just r -> Right r
53−
54−-- |Split a @'Map' k (Either a b)@ into @Map k a@ and @Map k b@, equivalent to @'Map.mapEither' id@
55−{-# DEPRECATED mapPartitionEithers "Use 'mapEither' instead" #-}
56−mapPartitionEithers :: Map k (Either a b) -> (Map k a, Map k b)
57−mapPartitionEithers = Map.mapEither id
58−
59−-- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new @'Set' k@ from the given input set.
60−--
61−-- Equivalent to:
62−--
63−-- @
64−-- applyMapKeysSet patch ('Map.keysSet' m) == 'Map.keysSet' ('applyMap' patch m)
65−-- @
66−--
67−-- but avoids the intervening @Map@ and needs no values.
68−applyMapKeysSet :: Ord k => Map k (Maybe v) -> Set k -> Set k
69−applyMapKeysSet patch old = Map.keysSet insertions `Set.union` (old `Set.difference` Map.keysSet deletions)
70− where (insertions, deletions) = Map.partition isJust patch
71−
src/Data/Monoid/DecidablyEmpty.hsnew file+115
@@ -0,0 +1,115 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DefaultSignatures #-}
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE StandaloneDeriving #-}
5+{-# LANGUAGE TypeOperators #-}
6+
7+-- TODO upstream somwhere else?
8+module Data.Monoid.DecidablyEmpty where
9+
10+import Data.Functor.Identity
11+import Data.Functor.Const
12+import Data.Monoid
13+import Data.Maybe (isNothing)
14+#if MIN_VERSION_base(4,11,0)
15+import Data.Ord
16+#endif
17+import Data.Proxy
18+import Data.Semigroup hiding (First, Last)
19+#if MIN_VERSION_base(4,12,0)
20+import GHC.Generics
21+#endif
22+
23+import qualified Data.IntSet as IntSet
24+import qualified Data.IntMap as IntMap
25+import qualified Data.Map as Map
26+import qualified Data.Sequence as Seq
27+import qualified Data.Set as Set
28+
29+import Data.GADT.Compare
30+import qualified Data.Dependent.Map as DMap
31+
32+-- | A 'DecidablyEmpty' is one where it can be computed whether or not an
33+-- arbitrary value is 'mempty'.
34+--
35+-- By using this class rather than 'Eq', we avoid unnecessary constraining the
36+-- contents of 'Functor's. This makes it possible to efficiently combine and/or
37+-- nest patch maps with 'Eq'-lacking values (e.g. functions) at the leaves.
38+class Monoid a => DecidablyEmpty a where
39+ isEmpty :: a -> Bool
40+ default isEmpty :: Eq a => a -> Bool
41+ isEmpty = (==) mempty
42+
43+-- base
44+
45+instance DecidablyEmpty Ordering
46+instance DecidablyEmpty ()
47+instance DecidablyEmpty Any
48+instance DecidablyEmpty All
49+-- instance DecidablyEmpty Lifetime
50+-- instance DecidablyEmpty Event
51+instance DecidablyEmpty [a] where
52+ isEmpty = null
53+instance
54+#if MIN_VERSION_base(4,11,0)
55+ Semigroup a
56+#else
57+ Monoid a
58+#endif
59+ => DecidablyEmpty (Maybe a) where
60+ isEmpty = isNothing
61+deriving instance (Num a, DecidablyEmpty a) => DecidablyEmpty (Product a)
62+deriving instance (DecidablyEmpty a, Num a) => DecidablyEmpty (Sum a)
63+deriving instance DecidablyEmpty a => DecidablyEmpty (Dual a)
64+instance DecidablyEmpty (First a) where
65+ isEmpty (First a) = isNothing a
66+instance DecidablyEmpty (Last a) where
67+ isEmpty (Last a) = isNothing a
68+deriving instance DecidablyEmpty a => DecidablyEmpty (Identity a)
69+instance Semigroup a => DecidablyEmpty (Option a) where
70+ isEmpty (Option a) = isNothing a
71+deriving instance DecidablyEmpty m => DecidablyEmpty (WrappedMonoid m)
72+instance (Ord a, Bounded a) => DecidablyEmpty (Max a)
73+instance (Ord a, Bounded a) => DecidablyEmpty (Min a)
74+instance DecidablyEmpty (Proxy s)
75+deriving instance DecidablyEmpty a => DecidablyEmpty (Const a b)
76+#if MIN_VERSION_base(4,11,0)
77+deriving instance DecidablyEmpty a => DecidablyEmpty (Down a)
78+#endif
79+#if MIN_VERSION_base(4,12,0)
80+deriving instance DecidablyEmpty p => DecidablyEmpty (Par1 p)
81+instance DecidablyEmpty (U1 p)
82+deriving instance DecidablyEmpty (f p) => DecidablyEmpty (Rec1 f p)
83+deriving instance DecidablyEmpty (f p) => DecidablyEmpty (M1 i c f p)
84+deriving instance DecidablyEmpty c => DecidablyEmpty (K1 i c p)
85+instance (DecidablyEmpty (f p), DecidablyEmpty (g p)) => DecidablyEmpty ((f :*: g) p) where
86+ isEmpty (x :*: y) = isEmpty x && isEmpty y
87+deriving instance DecidablyEmpty (f (g p)) => DecidablyEmpty ((f :.: g) p)
88+#endif
89+
90+instance (DecidablyEmpty a, DecidablyEmpty b) => DecidablyEmpty (a, b) where
91+ isEmpty (a, b) = isEmpty a && isEmpty b
92+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c) => DecidablyEmpty (a, b, c) where
93+ isEmpty (a, b, c) = isEmpty a && isEmpty b && isEmpty c
94+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d) => DecidablyEmpty (a, b, c, d) where
95+ isEmpty (a, b, c, d) = isEmpty a && isEmpty b && isEmpty c && isEmpty d
96+instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d, DecidablyEmpty e) => DecidablyEmpty (a, b, c, d, e) where
97+ isEmpty (a, b, c, d, e) = isEmpty a && isEmpty b && isEmpty c && isEmpty d && isEmpty e
98+
99+-- containers
100+
101+instance DecidablyEmpty IntSet.IntSet where
102+ isEmpty = IntSet.null
103+instance DecidablyEmpty (IntMap.IntMap v) where
104+ isEmpty = IntMap.null
105+instance Ord k => DecidablyEmpty (Map.Map k v) where
106+ isEmpty = Map.null
107+instance DecidablyEmpty (Seq.Seq v) where
108+ isEmpty = Seq.null
109+instance Ord k => DecidablyEmpty (Set.Set k) where
110+ isEmpty = Set.null
111+
112+-- dependent-map
113+
114+instance GCompare k => DecidablyEmpty (DMap.DMap k v) where
115+ isEmpty = DMap.null
src/Data/Patch.hsnew file+95
@@ -0,0 +1,95 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE StandaloneDeriving #-}
4+{-# LANGUAGE TypeFamilies #-}
5+{-# LANGUAGE TypeOperators #-}
6+-- |
7+-- Module:
8+-- Data.Patch
9+-- Description:
10+-- This module defines the 'Patch' class.
11+module Data.Patch
12+ ( module Data.Patch
13+ , module X
14+ ) where
15+
16+import Control.Applicative
17+import Data.Functor.Const (Const (..))
18+import Data.Functor.Identity
19+import Data.Map.Monoidal (MonoidalMap)
20+import Data.Proxy
21+#if !MIN_VERSION_base(4,11,0)
22+import Data.Semigroup (Semigroup (..))
23+#endif
24+import GHC.Generics
25+
26+import Data.Semigroup.Additive as X
27+import Data.Patch.Class as X
28+import Data.Patch.DMap as X hiding (getDeletions)
29+import Data.Patch.DMapWithMove as X
30+ ( PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove
31+ , patchDMapWithMoveToPatchMapWithMoveWith
32+ , traversePatchDMapWithMoveWithKey, unPatchDMapWithMove
33+ , unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith
34+ )
35+import Data.Patch.IntMap as X hiding (getDeletions)
36+import Data.Patch.Map as X
37+import Data.Patch.MapWithMove as X
38+ ( PatchMapWithMove, patchMapWithMoveNewElements
39+ , patchMapWithMoveNewElementsMap, unPatchMapWithMove
40+ , unsafePatchMapWithMove
41+ )
42+
43+-- | A 'Group' is a 'Monoid' where every element has an inverse.
44+class (Semigroup q, Monoid q) => Group q where
45+ negateG :: q -> q
46+ (~~) :: q -> q -> q
47+ r ~~ s = r <> negateG s
48+
49+-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
50+newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
51+
52+instance Additive p => Patch (AdditivePatch p) where
53+ type PatchTarget (AdditivePatch p) = p
54+ apply (AdditivePatch p) q = Just $ p <> q
55+
56+instance (Ord k, Group q) => Group (MonoidalMap k q) where
57+ negateG = fmap negateG
58+
59+-- | Trivial group.
60+instance Group () where
61+ negateG _ = ()
62+ _ ~~ _ = ()
63+
64+-- | Product group. A Pair of groups gives rise to a group
65+instance (Group a, Group b) => Group (a, b) where
66+ negateG (a, b) = (negateG a, negateG b)
67+ (a, b) ~~ (c, d) = (a ~~ c, b ~~ d)
68+
69+-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
70+-- Base does not define Monoid (Compose f g a) so this is the best we can
71+-- really do for functor composition.
72+instance Group (f (g a)) => Group ((f :.: g) a) where
73+ negateG (Comp1 xs) = Comp1 (negateG xs)
74+ Comp1 xs ~~ Comp1 ys = Comp1 (xs ~~ ys)
75+
76+-- | Product of groups, Functor style.
77+instance (Group (f a), Group (g a)) => Group ((f :*: g) a) where
78+ negateG (a :*: b) = negateG a :*: negateG b
79+ (a :*: b) ~~ (c :*: d) = (a ~~ c) :*: (b ~~ d)
80+
81+-- | Trivial group, Functor style
82+instance Group (Proxy x) where
83+ negateG _ = Proxy
84+ _ ~~ _ = Proxy
85+
86+-- | Const lifts groups into a functor.
87+deriving instance Group a => Group (Const a x)
88+
89+-- | Identity lifts groups pointwise (at only one point)
90+deriving instance Group a => Group (Identity a)
91+
92+-- | Functions lift groups pointwise.
93+instance Group b => Group (a -> b) where
94+ negateG f = negateG . f
95+ (~~) = liftA2 (~~)
src/Reflex/Patch/Class.hs → src/Data/Patch/Class.hsrenamed+14−3
@@ -1,17 +1,23 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
13{-# LANGUAGE TypeFamilies #-}
24-- | The interface for types which represent changes made to other types
3−module Reflex.Patch.Class where
5+module Data.Patch.Class where
46
5−import Control.Monad.Identity
7+import Data.Functor.Identity
8+import Data.Kind (Type)
69import Data.Maybe
10+#if !MIN_VERSION_base(4,11,0)
711import Data.Semigroup (Semigroup(..))
12+#endif
13+import Data.Proxy
814
915-- | A 'Patch' type represents a kind of change made to a datastructure.
1016--
1117-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
1218-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
1319class Patch p where
14− type PatchTarget p :: *
20+ type PatchTarget p :: Type
1521 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
1622 -- 'Nothing'.
1723 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
@@ -25,6 +31,11 @@ instance Patch (Identity a) where
2531 type PatchTarget (Identity a) = a
2632 apply (Identity a) _ = Just a
2733
34+-- | 'Proxy' can be used as a 'Patch' that does nothing.
35+instance forall (a :: Type). Patch (Proxy a) where
36+ type PatchTarget (Proxy a) = a
37+ apply ~Proxy _ = Nothing
38+
2839-- | Like '(.)', but composes functions that return patches rather than
2940-- functions that return new values. The Semigroup instance for patches must
3041-- apply patches right-to-left, like '(.)'.
src/Reflex/Patch/DMap.hs → src/Data/Patch/DMap.hsrenamed+16−5
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE GeneralizedNewtypeDeriving #-}
23{-# LANGUAGE LambdaCase #-}
34{-# LANGUAGE PolyKinds #-}
@@ -5,20 +6,26 @@
56{-# LANGUAGE ScopedTypeVariables #-}
67{-# LANGUAGE StandaloneDeriving #-}
78{-# LANGUAGE TypeFamilies #-}
9+
810-- | 'Patch'es on 'DMap' that consist only of insertions (or overwrites) and deletions.
9−module Reflex.Patch.DMap where
11+module Data.Patch.DMap where
1012
11−import Reflex.Patch.Class
12−import Reflex.Patch.IntMap
13−import Reflex.Patch.Map
13+import Data.Patch.Class
14+import Data.Patch.IntMap
15+import Data.Patch.Map
1416
15−import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
17+import Data.Dependent.Map (DMap)
18+import Data.Dependent.Sum (DSum (..))
19+import Data.GADT.Compare (GCompare (..))
1620import qualified Data.Dependent.Map as DMap
1721import Data.Functor.Constant
1822import Data.Functor.Misc
1923import qualified Data.IntMap as IntMap
2024import qualified Data.Map as Map
25+import Data.Monoid.DecidablyEmpty
26+#if !MIN_VERSION_base(4,11,0)
2127import Data.Semigroup (Semigroup (..))
28+#endif
2229import Data.Some (Some)
2330
2431-- | A set of changes to a 'DMap'. Any element may be inserted/updated or deleted.
@@ -30,6 +37,10 @@ deriving instance GCompare k => Semigroup (PatchDMap k v)
3037
3138deriving instance GCompare k => Monoid (PatchDMap k v)
3239
40+-- It won't let me derive for some reason
41+instance GCompare k => DecidablyEmpty (PatchDMap k v) where
42+ isEmpty (PatchDMap m) = DMap.null m
43+
3344-- | Apply the insertions or deletions to a given 'DMap'.
3445instance GCompare k => Patch (PatchDMap k v) where
3546 type PatchTarget (PatchDMap k v) = DMap k v
src/Reflex/Patch/DMapWithMove.hs → src/Data/Patch/DMapWithMove.hsrenamed+20−12
@@ -13,24 +13,28 @@
1313
1414-- |Module containing @'PatchDMapWithMove' k v@ and associated functions, which represents a 'Patch' to a @'DMap' k v@ which can insert, update, delete, and
1515-- move values between keys.
16−module Reflex.Patch.DMapWithMove where
16+module Data.Patch.DMapWithMove where
1717
18−import Reflex.Patch.Class
19−import Reflex.Patch.MapWithMove (PatchMapWithMove (..))
20−import qualified Reflex.Patch.MapWithMove as MapWithMove
18+import Data.Patch.Class
19+import Data.Patch.MapWithMove (PatchMapWithMove (..))
20+import qualified Data.Patch.MapWithMove as MapWithMove
2121
2222import Data.Constraint.Extras
23−import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
23+import Data.Dependent.Map (DMap)
24+import Data.Dependent.Sum (DSum (..))
2425import qualified Data.Dependent.Map as DMap
2526import Data.Functor.Constant
2627import Data.Functor.Misc
2728import Data.Functor.Product
28−import Data.GADT.Compare (GEq (..))
29+import Data.GADT.Compare (GEq (..), GCompare (..))
2930import Data.GADT.Show (GShow, gshow)
3031import qualified Data.Map as Map
3132import Data.Maybe
32−import Data.Semigroup (Semigroup (..), (<>))
33−import Data.Some (Some(Some))
33+import Data.Monoid.DecidablyEmpty
34+#if !MIN_VERSION_base(4,11,0)
35+import Data.Semigroup (Semigroup (..))
36+#endif
37+import Data.Some (Some, mkSome)
3438import Data.These
3539
3640-- | 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
@@ -42,6 +46,10 @@ import Data.These
4246-- * A move should always be represented with both the destination key (as a 'From_Move') and the source key (as a @'ComposeMaybe' ('Just' destination)@)
4347newtype PatchDMapWithMove k v = PatchDMapWithMove (DMap k (NodeInfo k v))
4448
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+
4553-- |Structure which represents what changes apply to a particular key. @_nodeInfo_from@ specifies what happens to this key, and in particular what other key
4654-- the current key is moving from, while @_nodeInfo_to@ specifies what key the current key is moving to if involved in a move.
4755data NodeInfo k v a = NodeInfo
@@ -212,8 +220,8 @@ moveDMapKey src dst = case src `geq` dst of
212220-- @
213221-- let aMay = DMap.lookup a dmap
214222-- bMay = DMap.lookup b dmap
215−-- in maybe id (DMap.insert a) (bMay `mplus` aMay)
216−-- . maybe id (DMap.insert b) (aMay `mplus` bMay)
223+-- in maybe id (DMap.insert a) (bMay <> aMay)
224+-- . maybe id (DMap.insert b) (aMay <> bMay)
217225-- . DMap.delete a . DMap.delete b $ dmap
218226-- @
219227swapDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
@@ -310,8 +318,8 @@ weakenPatchDMapWithMoveWith f (PatchDMapWithMove p) = PatchMapWithMove $ weakenD
310318 { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
311319 From_Insert v -> MapWithMove.From_Insert $ f v
312320 From_Delete -> MapWithMove.From_Delete
313− From_Move k -> MapWithMove.From_Move $ Some k
314− , MapWithMove._nodeInfo_to = Some <$> getComposeMaybe (_nodeInfo_to ni)
321+ From_Move k -> MapWithMove.From_Move $ mkSome k
322+ , MapWithMove._nodeInfo_to = mkSome <$> getComposeMaybe (_nodeInfo_to ni)
315323 }
316324
317325-- |"Weaken" a @'PatchDMapWithMove' (Const2 k a) v@ to a @'PatchMapWithMove' k v'@. Weaken is in scare quotes because the 'Const2' has already disabled any
src/Reflex/Patch/IntMap.hs → src/Data/Patch/IntMap.hsrenamed+31−14
@@ -1,22 +1,41 @@
1−{-# LANGUAGE DeriveFoldable #-}
2−{-# LANGUAGE DeriveFunctor #-}
1+{-# LANGUAGE CPP #-}
32{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleInstances #-}
44{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE StandaloneDeriving #-}
7+{-# LANGUAGE TemplateHaskell #-}
58{-# LANGUAGE TypeFamilies #-}
9+
610-- | Module containing 'PatchIntMap', a 'Patch' for 'IntMap' which allows for
711-- insert/update or delete of associations.
8−module Reflex.Patch.IntMap where
12+module Data.Patch.IntMap where
913
14+import Control.Lens
1015import Data.IntMap.Strict (IntMap)
1116import qualified Data.IntMap.Strict as IntMap
1217import Data.Maybe
13−import Data.Semigroup
14−import Reflex.Patch.Class
18+import Data.Monoid.DecidablyEmpty
19+#if !MIN_VERSION_base(4,11,0)
20+import Data.Semigroup (Semigroup (..))
21+#endif
22+import Data.Patch.Class
1523
1624-- | 'Patch' for 'IntMap' which represents insertion or deletion of keys in the mapping.
1725-- Internally represented by 'IntMap (Maybe a)', where @Just@ means insert/update
1826-- and @Nothing@ means delete.
19−newtype PatchIntMap a = PatchIntMap (IntMap (Maybe a)) deriving (Functor, Foldable, Traversable, Monoid)
27+newtype PatchIntMap a = PatchIntMap { unPatchIntMap :: IntMap (Maybe a) }
28+ deriving ( Show, Read, Eq, Ord
29+ , Functor, Foldable, Traversable
30+ , Monoid, DecidablyEmpty
31+ )
32+
33+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
34+-- If the same key is modified by both patches, the one on the left will take
35+-- precedence.
36+deriving instance Semigroup (PatchIntMap v)
37+
38+makeWrapped ''PatchIntMap
2039
2140-- | Apply the insertions or deletions to a given 'IntMap'.
2241instance Patch (PatchIntMap a) where
@@ -26,13 +45,11 @@ instance Patch (PatchIntMap a) where
2645 adds = IntMap.mapMaybe id p
2746 in IntMap.union adds $ v `IntMap.difference` removes
2847
29−-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
30−-- If the same key is modified by both patches, the one on the left will take
31−-- precedence.
32−instance Semigroup (PatchIntMap v) where
33− PatchIntMap a <> PatchIntMap b = PatchIntMap $ a `mappend` b --TODO: Add a semigroup instance for Map
34− -- PatchMap is idempotent, so stimes n is id for every n
35− stimes = stimesIdempotentMonoid
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
3653
3754-- | Map a function @Int -> a -> b@ over all @a@s in the given @'PatchIntMap' a@
3855-- (that is, all inserts/updates), producing a @PatchIntMap b@.
@@ -42,7 +59,7 @@ mapIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap $ IntMap.mapWithKey (\ k m
4259-- | Map an effectful function @Int -> a -> f b@ over all @a@s in the given @'PatchIntMap' a@
4360-- (that is, all inserts/updates), producing a @f (PatchIntMap b)@.
4461traverseIntMapPatchWithKey :: Applicative f => (Int -> a -> f b) -> PatchIntMap a -> f (PatchIntMap b)
45−traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (\k mv -> traverse (f k) mv) m
62+traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (traverse . f) m
4663
4764-- | Extract all @a@s inserted/updated by the given @'PatchIntMap' a@.
4865patchIntMapNewElements :: PatchIntMap a -> [a]
src/Reflex/Patch/Map.hs → src/Data/Patch/Map.hsrenamed+38−21
@@ -1,21 +1,48 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
15{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE StandaloneDeriving #-}
8+{-# LANGUAGE TemplateHaskell #-}
29{-# LANGUAGE TypeFamilies #-}
10+
311-- | 'Patch'es on 'Map' that consist only of insertions (including overwrites)
412-- and deletions
5−module Reflex.Patch.Map where
13+module Data.Patch.Map where
614
7−import Reflex.Patch.Class
15+import Data.Patch.Class
816
17+import Control.Lens
918import Data.Map (Map)
1019import qualified Data.Map as Map
1120import Data.Maybe
12−import Data.Semigroup
21+import Data.Monoid.DecidablyEmpty
22+import Data.Semigroup (Semigroup (..), stimesIdempotentMonoid)
1323
1424-- | A set of changes to a 'Map'. Any element may be inserted/updated or
1525-- deleted. Insertions are represented as values wrapped in 'Just', while
1626-- deletions are represented as 'Nothing's
1727newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
18− deriving (Show, Read, Eq, Ord)
28+ deriving ( Show, Read, Eq, Ord
29+ , Foldable, Traversable
30+ , DecidablyEmpty
31+ )
32+
33+-- | 'fmap'ping a 'PatchMap' will alter all of the values it will insert.
34+-- Deletions are unaffected.
35+deriving instance Functor (PatchMap k)
36+-- | The empty 'PatchMap' contains no insertions or deletions
37+deriving instance Ord k => Monoid (PatchMap k v)
38+
39+-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
40+-- If the same key is modified by both patches, the one on the left will take
41+-- precedence.
42+instance Ord k => Semigroup (PatchMap k v) where
43+ PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
44+ -- PatchMap is idempotent, so stimes n is id for every n
45+ stimes = stimesIdempotentMonoid
1946
2047-- | Apply the insertions or deletions to a given 'Map'.
2148instance Ord k => Patch (PatchMap k v) where
@@ -28,23 +55,11 @@ instance Ord k => Patch (PatchMap k v) where
2855 Nothing -> Just ()
2956 Just _ -> Nothing
3057
31−-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
32−-- If the same key is modified by both patches, the one on the left will take
33−-- precedence.
34−instance Ord k => Semigroup (PatchMap k v) where
35− PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
36− -- PatchMap is idempotent, so stimes n is id for every n
37− stimes = stimesIdempotentMonoid
38−
39−-- | The empty 'PatchMap' contains no insertions or deletions
40−instance Ord k => Monoid (PatchMap k v) where
41− mempty = PatchMap mempty
42− mappend = (<>)
43−
44−-- | 'fmap'ping a 'PatchMap' will alter all of the values it will insert.
45−-- Deletions are unaffected.
46−instance Functor (PatchMap k) where
47− fmap f = PatchMap . fmap (fmap f) . unPatchMap
58+instance FunctorWithIndex k (PatchMap k)
59+instance FoldableWithIndex k (PatchMap k)
60+instance TraversableWithIndex k (PatchMap k) where
61+ itraverse = itraversed . Indexed
62+ itraversed = _Wrapped .> itraversed <. traversed
4863
4964-- | Returns all the new elements that will be added to the 'Map'
5065patchMapNewElements :: PatchMap k v -> [v]
@@ -53,3 +68,5 @@ patchMapNewElements (PatchMap p) = catMaybes $ Map.elems p
5368-- | Returns all the new elements that will be added to the 'Map'
5469patchMapNewElementsMap :: PatchMap k v -> Map k v
5570patchMapNewElementsMap (PatchMap p) = Map.mapMaybe id p
71+
72+makeWrapped ''PatchMap
src/Data/Patch/MapWithMove.hsnew file+312
@@ -0,0 +1,312 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveTraversable #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6+{-# LANGUAGE LambdaCase #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE PatternGuards #-}
9+{-# LANGUAGE PatternSynonyms #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE StandaloneDeriving #-}
12+{-# LANGUAGE TemplateHaskell #-}
13+{-# LANGUAGE TypeApplications #-}
14+{-# LANGUAGE TypeFamilies #-}
15+{-# LANGUAGE ViewPatterns #-}
16+
17+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
18+-- another
19+module Data.Patch.MapWithMove
20+ ( PatchMapWithMove
21+ ( PatchMapWithMove
22+ , unPatchMapWithMove
23+ , ..
24+ )
25+ , patchMapWithMove
26+ , patchMapWithMoveInsertAll
27+ , insertMapKey
28+ , moveMapKey
29+ , swapMapKey
30+ , deleteMapKey
31+ , unsafePatchMapWithMove
32+ , patchMapWithMoveNewElements
33+ , patchMapWithMoveNewElementsMap
34+ , patchThatSortsMapWith
35+ , patchThatChangesAndSortsMapWith
36+ , patchThatChangesMap
37+
38+ -- * Node Info
39+ , NodeInfo
40+ ( NodeInfo
41+ , _nodeInfo_to
42+ , _nodeInfo_from
43+ , ..
44+ )
45+ , bitraverseNodeInfo
46+ , nodeInfoMapFrom
47+ , nodeInfoMapMFrom
48+ , nodeInfoSetTo
49+
50+ -- * From
51+ , From
52+ ( From_Insert
53+ , From_Delete
54+ , From_Move
55+ , ..
56+ )
57+ , bitraverseFrom
58+
59+ -- * To
60+ , To
61+ ) where
62+
63+import Data.Coerce
64+import Data.Kind (Type)
65+import Data.Patch.Class
66+import Data.Patch.MapWithPatchingMove (PatchMapWithPatchingMove(..), To)
67+import qualified Data.Patch.MapWithPatchingMove as PM -- already a transparent synonym
68+
69+import Control.Lens
70+import Data.List
71+import Data.Map (Map)
72+import qualified Data.Map as Map
73+import Data.Proxy
74+#if !MIN_VERSION_base(4,11,0)
75+import Data.Semigroup (Semigroup (..))
76+#endif
77+import Data.Traversable (foldMapDefault)
78+
79+-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
80+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
81+-- and vice versa. There should never be any unpaired From/To keys.
82+newtype PatchMapWithMove k (v :: Type) = PatchMapWithMove'
83+ { -- | Extract the underlying 'PatchMapWithPatchingMove k (Proxy v)'
84+ unPatchMapWithMove' :: PatchMapWithPatchingMove k (Proxy v)
85+ }
86+ deriving ( Show, Read, Eq, Ord
87+-- Haddock cannot handle documentation here before GHC 8.6
88+ ,
89+#if __GLASGOW_HASKELL__ >= 806
90+ -- | Compose patches having the same effect as applying the
91+ -- patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p .
92+ -- 'applyAlways' q@
93+#endif
94+ Semigroup
95+ , Monoid
96+ )
97+
98+pattern Coerce :: Coercible a b => a -> b
99+pattern Coerce x <- (coerce -> x)
100+ where Coerce x = coerce x
101+
102+{-# COMPLETE PatchMapWithMove #-}
103+pattern PatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
104+-- | Extract the representation of the 'PatchMapWithMove' as a map of
105+-- 'NodeInfo'.
106+unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
107+pattern PatchMapWithMove { unPatchMapWithMove } = PatchMapWithMove' (PatchMapWithPatchingMove (Coerce unPatchMapWithMove))
108+
109+_PatchMapWithMove
110+ :: Iso
111+ (PatchMapWithMove k0 v0)
112+ (PatchMapWithMove k1 v1)
113+ (Map k0 (NodeInfo k0 v0))
114+ (Map k1 (NodeInfo k1 v1))
115+_PatchMapWithMove = iso unPatchMapWithMove PatchMapWithMove
116+
117+instance Functor (PatchMapWithMove k) where
118+ fmap f = runIdentity . traverse (Identity . f)
119+
120+instance Foldable (PatchMapWithMove k) where
121+ foldMap = foldMapDefault
122+
123+instance Traversable (PatchMapWithMove k) where
124+ traverse =
125+ _PatchMapWithMove .
126+ traverse .
127+ traverse
128+
129+instance FunctorWithIndex k (PatchMapWithMove k)
130+instance FoldableWithIndex k (PatchMapWithMove k)
131+instance TraversableWithIndex k (PatchMapWithMove k) where
132+ itraverse = itraversed . Indexed
133+ itraversed =
134+ _PatchMapWithMove .>
135+ itraversed <.
136+ traverse
137+
138+-- | Create a 'PatchMapWithMove', validating it
139+patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
140+patchMapWithMove = fmap PatchMapWithMove' . PM.patchMapWithPatchingMove . coerce
141+
142+-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
143+patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
144+patchMapWithMoveInsertAll = PatchMapWithMove' . PM.patchMapWithPatchingMoveInsertAll
145+
146+-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
147+insertMapKey :: k -> v -> PatchMapWithMove k v
148+insertMapKey k v = PatchMapWithMove' $ PM.insertMapKey k v
149+
150+-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
151+--
152+-- @
153+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
154+-- @
155+moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
156+moveMapKey src dst = PatchMapWithMove' $ PM.moveMapKey src dst
157+
158+-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
159+--
160+-- @
161+-- let aMay = Map.lookup a map
162+-- bMay = Map.lookup b map
163+-- in maybe id (Map.insert a) (bMay <> aMay)
164+-- . maybe id (Map.insert b) (aMay <> bMay)
165+-- . Map.delete a . Map.delete b $ map
166+-- @
167+swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
168+swapMapKey src dst = PatchMapWithMove' $ PM.swapMapKey src dst
169+
170+-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
171+deleteMapKey :: k -> PatchMapWithMove k v
172+deleteMapKey = PatchMapWithMove' . PM.deleteMapKey
173+
174+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
175+--
176+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
177+unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
178+unsafePatchMapWithMove = coerce PM.unsafePatchMapWithPatchingMove
179+
180+-- | Apply the insertions, deletions, and moves to a given 'Map'
181+instance Ord k => Patch (PatchMapWithMove k v) where
182+ type PatchTarget (PatchMapWithMove k v) = Map k v
183+ apply (PatchMapWithMove' p) = apply p
184+
185+-- | Returns all the new elements that will be added to the 'Map'.
186+patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
187+patchMapWithMoveNewElements = PM.patchMapWithPatchingMoveNewElements . unPatchMapWithMove'
188+
189+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
190+patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
191+patchMapWithMoveNewElementsMap = PM.patchMapWithPatchingMoveNewElementsMap . unPatchMapWithMove'
192+
193+-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
194+-- its values using the given ordering function. The set keys of the 'Map' is
195+-- not changed.
196+patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
197+patchThatSortsMapWith cmp = PatchMapWithMove' . PM.patchThatSortsMapWith cmp
198+
199+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
200+-- will produce a 'Map' with the same values as the second 'Map' but with the
201+-- values sorted with the given ordering function.
202+patchThatChangesAndSortsMapWith :: (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
203+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
204+ where newList = Map.toList newByIndexUnsorted
205+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
206+
207+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
208+-- will produce the second 'Map'.
209+patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
210+patchThatChangesMap oldByIndex newByIndex = PatchMapWithMove' $
211+ PM.patchThatChangesMap oldByIndex newByIndex
212+
213+--
214+-- NodeInfo
215+--
216+
217+-- | Holds the information about each key: where its new value should come from,
218+-- and where its old value should go to
219+newtype NodeInfo k (v :: Type) = NodeInfo' { unNodeInfo' :: PM.NodeInfo k (Proxy v) }
220+
221+deriving instance (Show k, Show p) => Show (NodeInfo k p)
222+deriving instance (Read k, Read p) => Read (NodeInfo k p)
223+deriving instance (Eq k, Eq p) => Eq (NodeInfo k p)
224+deriving instance (Ord k, Ord p) => Ord (NodeInfo k p)
225+
226+{-# COMPLETE NodeInfo #-}
227+pattern NodeInfo :: To k -> From k v -> NodeInfo k v
228+_nodeInfo_to :: NodeInfo k v -> To k
229+_nodeInfo_from :: NodeInfo k v -> From k v
230+pattern NodeInfo { _nodeInfo_to, _nodeInfo_from } = NodeInfo'
231+ PM.NodeInfo
232+ { PM._nodeInfo_to = _nodeInfo_to
233+ , PM._nodeInfo_from = Coerce _nodeInfo_from
234+ }
235+
236+_NodeInfo
237+ :: Iso
238+ (NodeInfo k0 v0)
239+ (NodeInfo k1 v1)
240+ (PM.NodeInfo k0 (Proxy v0))
241+ (PM.NodeInfo k1 (Proxy v1))
242+_NodeInfo = iso unNodeInfo' NodeInfo'
243+
244+instance Functor (NodeInfo k) where
245+ fmap f = runIdentity . traverse (Identity . f)
246+
247+instance Foldable (NodeInfo k) where
248+ foldMap = foldMapDefault
249+
250+instance Traversable (NodeInfo k) where
251+ traverse = bitraverseNodeInfo pure
252+
253+bitraverseNodeInfo
254+ :: Applicative f
255+ => (k0 -> f k1)
256+ -> (v0 -> f v1)
257+ -> NodeInfo k0 v0 -> f (NodeInfo k1 v1)
258+bitraverseNodeInfo fk fv = fmap NodeInfo'
259+ . PM.bitraverseNodeInfo fk (\ ~Proxy -> pure Proxy) fv
260+ . coerce
261+
262+-- | Change the 'From' value of a 'NodeInfo'
263+nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
264+nodeInfoMapFrom f = coerce $ PM.nodeInfoMapFrom (unFrom' . f . From')
265+
266+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
267+-- 'Applicative', 'Monad', etc.) action to get the new value
268+nodeInfoMapMFrom
269+ :: Functor f
270+ => (From k v -> f (From k v))
271+ -> NodeInfo k v -> f (NodeInfo k v)
272+nodeInfoMapMFrom f = fmap NodeInfo'
273+ . PM.nodeInfoMapMFrom (fmap unFrom' . f . From')
274+ . coerce
275+
276+-- | Set the 'To' field of a 'NodeInfo'
277+nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
278+nodeInfoSetTo = coerce . PM.nodeInfoSetTo
279+
280+--
281+-- From
282+--
283+
284+-- | Describe how a key's new value should be produced
285+newtype From k (v :: Type) = From' { unFrom' :: PM.From k (Proxy v) }
286+
287+{-# COMPLETE From_Insert, From_Delete, From_Move #-}
288+
289+-- | Insert the given value here
290+pattern From_Insert :: v -> From k v
291+pattern From_Insert v = From' (PM.From_Insert v)
292+
293+-- | Delete the existing value, if any, from here
294+pattern From_Delete :: From k v
295+pattern From_Delete = From' PM.From_Delete
296+
297+-- | Move the value here from the given key
298+pattern From_Move :: k -> From k v
299+pattern From_Move k = From' (PM.From_Move k Proxy)
300+
301+bitraverseFrom
302+ :: Applicative f
303+ => (k0 -> f k1)
304+ -> (v0 -> f v1)
305+ -> From k0 v0 -> f (From k1 v1)
306+bitraverseFrom fk fv = fmap From'
307+ . PM.bitraverseFrom fk (\ ~Proxy -> pure Proxy) fv
308+ . coerce
309+
310+makeWrapped ''PatchMapWithMove
311+makeWrapped ''NodeInfo
312+makeWrapped ''From
src/Data/Patch/MapWithPatchingMove.hsnew file+432
@@ -0,0 +1,432 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE PatternGuards #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE StandaloneDeriving #-}
10+{-# LANGUAGE TemplateHaskell #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+
14+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15+-- another
16+module Data.Patch.MapWithPatchingMove
17+ ( PatchMapWithPatchingMove (..)
18+ , patchMapWithPatchingMove
19+ , patchMapWithPatchingMoveInsertAll
20+ , insertMapKey
21+ , moveMapKey
22+ , swapMapKey
23+ , deleteMapKey
24+ , unsafePatchMapWithPatchingMove
25+ , patchMapWithPatchingMoveNewElements
26+ , patchMapWithPatchingMoveNewElementsMap
27+ , patchThatSortsMapWith
28+ , patchThatChangesAndSortsMapWith
29+ , patchThatChangesMap
30+
31+ -- * Node Info
32+ , NodeInfo (..)
33+ , bitraverseNodeInfo
34+ , nodeInfoMapFrom
35+ , nodeInfoMapMFrom
36+ , nodeInfoSetTo
37+
38+ -- * From
39+ , From(..)
40+ , bitraverseFrom
41+
42+ -- * To
43+ , To
44+
45+ -- TODO internals module
46+ , Fixup (..)
47+ ) where
48+
49+import Data.Patch.Class
50+
51+import Control.Lens hiding (from, to)
52+import Control.Lens.TH (makeWrapped)
53+import Data.Align (align)
54+import Data.Foldable (toList)
55+import Data.Function
56+import Data.List
57+import Data.Map (Map)
58+import qualified Data.Map as Map
59+import Data.Maybe
60+#if !MIN_VERSION_base(4,11,0)
61+import Data.Semigroup (Semigroup (..))
62+#endif
63+import Data.Monoid.DecidablyEmpty
64+import Data.Set (Set)
65+import qualified Data.Set as Set
66+import Data.These (These (..))
67+
68+-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
69+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
70+-- and vice versa. There should never be any unpaired From/To keys.
71+newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
72+ { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
73+ unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
74+ }
75+
76+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
77+deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
78+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
79+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
80+
81+deriving instance ( Ord k
82+#if !MIN_VERSION_base(4,11,0)
83+ , Semigroup p
84+#endif
85+ , DecidablyEmpty p
86+ , Patch p
87+ ) => DecidablyEmpty (PatchMapWithPatchingMove k p)
88+
89+-- | Create a 'PatchMapWithPatchingMove', validating it
90+patchMapWithPatchingMove
91+ :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
92+patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
93+ where valid = forwardLinks == backwardLinks
94+ forwardLinks = Map.mapMaybe _nodeInfo_to m
95+ backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
96+ case _nodeInfo_from p of
97+ From_Move from _ -> Just (from, to)
98+ _ -> Nothing
99+
100+-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
101+patchMapWithPatchingMoveInsertAll
102+ :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
103+patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
104+ { _nodeInfo_from = From_Insert v
105+ , _nodeInfo_to = Nothing
106+ }
107+
108+-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
109+insertMapKey
110+ :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
111+insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
112+
113+-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
114+--
115+-- @
116+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
117+-- @
118+moveMapKey
119+ :: ( DecidablyEmpty p
120+#if !MIN_VERSION_base(4,11,0)
121+ , Semigroup p
122+#endif
123+ , Patch p
124+ )
125+ => Ord k => k -> k -> PatchMapWithPatchingMove k p
126+moveMapKey src dst
127+ | src == dst = mempty
128+ | otherwise =
129+ PatchMapWithPatchingMove $ Map.fromList
130+ [ (dst, NodeInfo (From_Move src mempty) Nothing)
131+ , (src, NodeInfo From_Delete (Just dst))
132+ ]
133+
134+-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
135+--
136+-- @
137+-- let aMay = Map.lookup a map
138+-- bMay = Map.lookup b map
139+-- in maybe id (Map.insert a) (bMay <> aMay)
140+-- . maybe id (Map.insert b) (aMay <> bMay)
141+-- . Map.delete a . Map.delete b $ map
142+-- @
143+swapMapKey
144+ :: ( DecidablyEmpty p
145+#if !MIN_VERSION_base(4,11,0)
146+ , Semigroup p
147+#endif
148+ , Patch p
149+ )
150+ => Ord k => k -> k -> PatchMapWithPatchingMove k p
151+swapMapKey src dst
152+ | src == dst = mempty
153+ | otherwise =
154+ PatchMapWithPatchingMove $ Map.fromList
155+ [ (dst, NodeInfo (From_Move src mempty) (Just src))
156+ , (src, NodeInfo (From_Move dst mempty) (Just dst))
157+ ]
158+
159+-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160+-- the mapping, equivalent to 'Map.delete'.
161+deleteMapKey
162+ :: k -> PatchMapWithPatchingMove k v
163+deleteMapKey k = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo From_Delete Nothing
164+
165+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithPatchingMove' k v@, without checking any invariants.
166+--
167+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithPatchingMove' are preserved; they will not be checked.
168+unsafePatchMapWithPatchingMove
169+ :: Map k (NodeInfo k p) -> PatchMapWithPatchingMove k p
170+unsafePatchMapWithPatchingMove = PatchMapWithPatchingMove
171+
172+-- | Apply the insertions, deletions, and moves to a given 'Map'
173+instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
174+ type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
175+ -- TODO: return Nothing sometimes
176+ -- Note: the strict application here is critical to ensuring that incremental
177+ -- merges don't hold onto all their prerequisite events forever; can we make
178+ -- this more robust?
179+ apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
180+ where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
181+ From_Insert v -> Just v
182+ From_Move k p -> applyAlways p <$> Map.lookup k old
183+ From_Delete -> Nothing
184+ deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
185+ From_Delete -> Just ()
186+ _ -> Nothing
187+
188+-- | Returns all the new elements that will be added to the 'Map'
189+patchMapWithPatchingMoveNewElements
190+ :: PatchMapWithPatchingMove k p -> [PatchTarget p]
191+patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
192+
193+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
194+patchMapWithPatchingMoveNewElementsMap
195+ :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
196+patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
197+ where f ni = case _nodeInfo_from ni of
198+ From_Insert v -> Just v
199+ From_Move _ _ -> Nothing
200+ From_Delete -> Nothing
201+
202+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
203+-- its values using the given ordering function. The set keys of the 'Map' is
204+-- not changed.
205+patchThatSortsMapWith
206+ :: (Ord k, Monoid p)
207+ => (PatchTarget p -> PatchTarget p -> Ordering)
208+ -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
209+patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
210+ where unsorted = Map.toList m
211+ sorted = sortBy (cmp `on` snd) unsorted
212+ f (to, _) (from, _) = if to == from then Nothing else
213+ Just (from, to)
214+ reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
215+ g (to, _) (from, _) = if to == from then Nothing else
216+ let Just movingTo = Map.lookup from reverseMapping
217+ in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
218+
219+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
220+-- will produce a 'Map' with the same values as the second 'Map' but with the
221+-- values sorted with the given ordering function.
222+patchThatChangesAndSortsMapWith
223+ :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
224+ => (PatchTarget p -> PatchTarget p -> Ordering)
225+ -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
226+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
227+ where newList = Map.toList newByIndexUnsorted
228+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
229+
230+-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
231+-- will produce the second 'Map'.
232+-- Note: this will never produce a patch on a value.
233+patchThatChangesMap
234+ :: forall k p
235+ . (Ord k, Ord (PatchTarget p), Monoid p)
236+ => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
237+patchThatChangesMap oldByIndex newByIndex = patch
238+ where invert :: Map k (PatchTarget p) -> Map (PatchTarget p) (Set k)
239+ invert = Map.fromListWith (<>) . fmap (\(k, v) -> (v, Set.singleton k)) . Map.toList
240+ -- In the places where we use unionDistinct, a non-distinct key indicates a bug in this function
241+ unionDistinct :: forall k' v'. Ord k' => Map k' v' -> Map k' v' -> Map k' v'
242+ unionDistinct = Map.unionWith (error "patchThatChangesMap: non-distinct keys")
243+ unionPairDistinct :: (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k))
244+ unionPairDistinct (oldFroms, oldTos) (newFroms, newTos) = (unionDistinct oldFroms newFroms, unionDistinct oldTos newTos)
245+ -- Generate patch info for a single value
246+ -- Keys that are found in both the old and new sets will not be patched
247+ -- Keys that are found in only the old set will be moved to a new position if any are available; otherwise they will be deleted
248+ -- Keys that are found in only the new set will be populated by moving an old key if any are available; otherwise they will be inserted
249+ patchSingleValue :: PatchTarget p -> Set k -> Set k -> (Map k (From k p), Map k (To k))
250+ patchSingleValue v oldKeys newKeys = foldl' unionPairDistinct mempty $ align (toList $ oldKeys `Set.difference` newKeys) (toList $ newKeys `Set.difference` oldKeys) <&> \case
251+ This oldK -> (mempty, Map.singleton oldK Nothing) -- There's nowhere for this value to go, so we know we are deleting it
252+ That newK -> (Map.singleton newK $ From_Insert v, mempty) -- There's nowhere fo this value to come from, so we know we are inserting it
253+ These oldK newK -> (Map.singleton newK $ From_Move oldK mempty, Map.singleton oldK $ Just newK)
254+ -- Run patchSingleValue on a These. Missing old or new sets are considered empty
255+ patchSingleValueThese :: PatchTarget p -> These (Set k) (Set k) -> (Map k (From k p), Map k (To k))
256+ patchSingleValueThese v = \case
257+ This oldKeys -> patchSingleValue v oldKeys mempty
258+ That newKeys -> patchSingleValue v mempty newKeys
259+ These oldKeys newKeys -> patchSingleValue v oldKeys newKeys
260+ -- Generate froms and tos for all values, then merge them together
261+ (froms, tos) = foldl' unionPairDistinct mempty $ Map.mapWithKey patchSingleValueThese $ align (invert oldByIndex) (invert newByIndex)
262+ patch = unsafePatchMapWithPatchingMove $ align froms tos <&> \case
263+ This from -> NodeInfo from Nothing -- Since we don't have a 'to' record for this key, that must mean it isn't being moved anywhere, so it should be deleted.
264+ That to -> NodeInfo From_Delete to -- Since we don't have a 'from' record for this key, it must be getting deleted
265+ These from to -> NodeInfo from to
266+
267+--
268+-- NodeInfo
269+--
270+
271+-- | Holds the information about each key: where its new value should come from,
272+-- and where its old value should go to
273+data NodeInfo k p = NodeInfo
274+ { _nodeInfo_from :: !(From k p)
275+ -- ^ Where do we get the new value for this key?
276+ , _nodeInfo_to :: !(To k)
277+ -- ^ If the old value is being kept (i.e. moved rather than deleted or
278+ -- replaced), where is it going?
279+ }
280+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
281+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
282+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
283+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
284+
285+-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
286+-- the type families here, this doesn't it any bi- or tri-traversal class.
287+bitraverseNodeInfo
288+ :: Applicative f
289+ => (k0 -> f k1)
290+ -> (p0 -> f p1)
291+ -> (PatchTarget p0 -> f (PatchTarget p1))
292+ -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
293+bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
294+ <$> bitraverseFrom fk fp fpt from
295+ <*> traverse fk to
296+
297+-- | Change the 'From' value of a 'NodeInfo'
298+nodeInfoMapFrom
299+ :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
300+nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
301+
302+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
303+-- 'Applicative', 'Monad', etc.) action to get the new value
304+nodeInfoMapMFrom
305+ :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
306+nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
307+
308+-- | Set the 'To' field of a 'NodeInfo'
309+nodeInfoSetTo
310+ :: To k -> NodeInfo k v -> NodeInfo k v
311+nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
312+
313+--
314+-- From
315+--
316+
317+-- | Describe how a key's new value should be produced
318+data From k p
319+ = From_Insert (PatchTarget p) -- ^ Insert the given value here
320+ | From_Delete -- ^ Delete the existing value, if any, from here
321+ | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
322+
323+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
324+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
325+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
326+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
327+
328+-- | Traverse the 'From' over the key, patch, and patch target. Because of
329+-- the type families here, this doesn't it any bi- or tri-traversal class.
330+bitraverseFrom
331+ :: Applicative f
332+ => (k0 -> f k1)
333+ -> (p0 -> f p1)
334+ -> (PatchTarget p0 -> f (PatchTarget p1))
335+ -> From k0 p0 -> f (From k1 p1)
336+bitraverseFrom fk fp fpt = \case
337+ From_Insert pt -> From_Insert <$> fpt pt
338+ From_Delete -> pure From_Delete
339+ From_Move k p -> From_Move <$> fk k <*> fp p
340+
341+--
342+-- To
343+--
344+
345+-- | Describe where a key's old value will go. If this is 'Just', that means
346+-- the key's old value will be moved to the given other key; if it is 'Nothing',
347+-- that means it will be deleted.
348+type To = Maybe
349+
350+--
351+-- Fixup
352+--
353+
354+-- | Helper data structure used for composing patches using the monoid instance.
355+data Fixup k v
356+ = Fixup_Delete
357+ | Fixup_Update (These (From k v) (To k))
358+
359+-- | Compose patches having the same effect as applying the patches in turn:
360+-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
361+instance ( Ord k
362+#if !MIN_VERSION_base(4,11,0)
363+ , Semigroup p
364+#endif
365+ , DecidablyEmpty p
366+ , Patch p
367+ ) => Semigroup (PatchMapWithPatchingMove k p) where
368+ PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
369+ where
370+ connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
371+ h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
372+ h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
373+ (Just toAfter, From_Move fromBefore p)
374+ | fromBefore == toAfter && isEmpty p
375+ -> [(toAfter, Fixup_Delete)]
376+ | otherwise
377+ -> [ (toAfter, Fixup_Update (This editBefore))
378+ , (fromBefore, Fixup_Update (That mToAfter))
379+ ]
380+ (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
381+ (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
382+ (Nothing, _) -> []
383+ mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
384+ mergeFixups _ (Fixup_Update a) (Fixup_Update b)
385+ | This x <- a, That y <- b
386+ = Fixup_Update $ These x y
387+ | That y <- a, This x <- b
388+ = Fixup_Update $ These x y
389+ mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
390+ fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
391+ combineNodeInfos _ nia nib = NodeInfo
392+ { _nodeInfo_from = _nodeInfo_from nia
393+ , _nodeInfo_to = _nodeInfo_to nib
394+ }
395+ applyFixup _ ni = \case
396+ Fixup_Delete -> Nothing
397+ Fixup_Update u -> Just $ NodeInfo
398+ { _nodeInfo_from = case _nodeInfo_from ni of
399+ f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
400+ Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
401+ Just (From_Insert v) -> From_Insert $ applyAlways p' v
402+ Just From_Delete -> From_Delete
403+ Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
404+ _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
405+ , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
406+ }
407+ m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
408+ getHere :: These a b -> Maybe a
409+ getHere = \case
410+ This a -> Just a
411+ These a _ -> Just a
412+ That _ -> Nothing
413+ getThere :: These a b -> Maybe b
414+ getThere = \case
415+ This _ -> Nothing
416+ These _ b -> Just b
417+ That b -> Just b
418+
419+--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
420+-- | Compose patches having the same effect as applying the patches in turn:
421+-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
422+instance ( Ord k
423+#if !MIN_VERSION_base(4,11,0)
424+ , Semigroup p
425+#endif
426+ , DecidablyEmpty p
427+ , Patch p
428+ ) => Monoid (PatchMapWithPatchingMove k p) where
429+ mempty = PatchMapWithPatchingMove mempty
430+ mappend = (<>)
431+
432+makeWrapped ''PatchMapWithPatchingMove
src/Data/Semigroup/Additive.hsnew file+54
@@ -0,0 +1,54 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE TypeOperators #-}
3+{-# LANGUAGE TypeFamilies #-}
4+-- |
5+-- Module:
6+-- Data.Semigroup.Additive
7+-- Description:
8+-- This module defines a class for commutative semigroups, until it is moved
9+-- to another library.
10+module Data.Semigroup.Additive
11+ ( Additive
12+ ) where
13+
14+import Data.Functor.Const (Const (..))
15+import Data.Functor.Identity
16+import Data.Proxy
17+#if !MIN_VERSION_base(4,12,0)
18+-- for :*: and :.: semigroup instances
19+import Data.Orphans ()
20+#endif
21+#if !MIN_VERSION_base(4,11,0)
22+import Data.Semigroup (Semigroup (..))
23+#endif
24+import GHC.Generics
25+
26+-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
27+class Semigroup q => Additive q where
28+
29+-- | Trivial additive semigroup.
30+instance Additive ()
31+
32+-- | Product additive semigroup.
33+-- A Pair of additive semigroups gives rise to a additive semigroup
34+instance (Additive a, Additive b) => Additive (a, b)
35+
36+-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
37+-- Base does not define Monoid (Compose f g a) so this is the best we can
38+-- really do for functor composition.
39+instance Additive (f (g a)) => Additive ((f :.: g) a)
40+
41+-- | Product of additive semigroups, Functor style.
42+instance (Additive (f a), Additive (g a)) => Additive ((f :*: g) a)
43+
44+-- | Trivial additive semigroup, Functor style
45+instance Additive (Proxy x)
46+
47+-- | Const lifts additive semigroups into a functor.
48+instance Additive a => Additive (Const a x)
49+
50+-- | Identity lifts additive semigroups pointwise (at only one point)
51+instance Additive a => Additive (Identity a)
52+
53+-- | Functions lift additive semigroups pointwise.
54+instance Additive b => Additive (a -> b)
src/Data/WeakBag.hsdeleted−126
@@ -1,126 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ExistentialQuantification #-}
4−#ifdef USE_REFLEX_OPTIMIZER
5−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
6−#endif
7−-- | This module defines the 'WeakBag' type, which represents a mutable
8−-- collection of items that does not cause the items to be retained in memory.
9−-- This is useful for situations where a value needs to be inspected or modified
10−-- if it is still alive, but can be ignored if it is dead.
11−module Data.WeakBag
12− ( WeakBag
13− , WeakBagTicket
14− , empty
15− , singleton
16− , insert
17− , traverse
18− , traverse_
19− , remove
20− -- * Internal functions
21− -- These will not always be available.
22− , _weakBag_children --TODO: Don't export this
23− ) where
24−
25−import Prelude hiding (traverse)
26−
27−import Control.Exception
28−import Control.Monad
29−import Control.Monad.IO.Class
30−import Data.IntMap.Strict (IntMap)
31−import qualified Data.IntMap.Strict as IntMap
32−import Data.IORef
33−import System.Mem.Weak
34−
35−-- | A 'WeakBag' holds a set of values of type @/a/@, but does not retain them -
36−-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
37−-- alive, the 'WeakBag' will continue to refer to them.
38−data WeakBag a = WeakBag
39− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
40− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ The items referenced by the WeakBag
41− }
42−
43−-- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned. If
44−-- the caller retains the ticket, the item is guranteed to stay in memory (and
45−-- thus in the 'WeakBag'). The ticket can also be used to remove the item from
46−-- the 'WeakBag' prematurely (i.e. while it is still alive), using 'remove'.
47−data WeakBagTicket = forall a. WeakBagTicket
48− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
49− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
50− }
51−
52−-- | Insert an item into a 'WeakBag'.
53−{-# INLINE insert #-}
54−insert :: a -- ^ The item
55− -> WeakBag a -- ^ The 'WeakBag' to insert into
56− -> IORef (Weak b) -- ^ An arbitrary value to be used in the following
57− -- callback
58− -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed
59− -- (whether automatically by the item being garbage
60− -- collected or manually via 'remove')
61− -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item
62− -- is retained and allows the item to be removed.
63−insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do
64− a' <- evaluate a
65− wbRef' <- evaluate wbRef
66− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
67− let cleanup = do
68− wb <- readIORef wbRef'
69− mb <- deRefWeak wb
70− forM_ mb $ \b -> do
71− csWithoutMe <- atomicModifyIORef children $ \cs ->
72− let !csWithoutMe = IntMap.delete myId cs
73− in (csWithoutMe, csWithoutMe)
74− when (IntMap.null csWithoutMe) $ finalizer b
75− wa <- mkWeakPtr a' $ Just cleanup
76− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
77− return $ WeakBagTicket
78− { _weakBagTicket_weakItem = wa
79− , _weakBagTicket_item = a'
80− }
81−
82−-- | Create an empty 'WeakBag'.
83−{-# INLINE empty #-}
84−empty :: IO (WeakBag a)
85−empty = {-# SCC "empty" #-} do
86− nextId <- newIORef 1
87− children <- newIORef IntMap.empty
88− let bag = WeakBag
89− { _weakBag_nextId = nextId
90− , _weakBag_children = children
91− }
92− return bag
93−
94−-- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with
95−-- 'empty', then using 'insert'.
96−{-# INLINE singleton #-}
97−singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
98−singleton a wbRef finalizer = {-# SCC "singleton" #-} do
99− bag <- empty
100− ticket <- insert a bag wbRef finalizer
101− return (bag, ticket)
102−
103−{-# INLINE traverse_ #-}
104−-- | Visit every node in the given list. If new nodes are appended during the
105−-- traversal, they will not be visited. Every live node that was in the list
106−-- when the traversal began will be visited exactly once; however, no guarantee
107−-- is made about the order of the traversal.
108−traverse_ :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
109−traverse_ (WeakBag _ children) f = {-# SCC "traverse" #-} do
110− cs <- liftIO $ readIORef children
111− forM_ cs $ \c -> do
112− ma <- liftIO $ deRefWeak c
113− mapM_ f ma
114−
115−{-# DEPRECATED traverse "Use 'traverse_' instead" #-}
116−traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
117−traverse = traverse_
118−
119−-- | Remove an item from the 'WeakBag'; does nothing if invoked multiple times
120−-- on the same 'WeakBagTicket'.
121−{-# INLINE remove #-}
122−remove :: WeakBagTicket -> IO ()
123−remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w
124−--TODO: Should 'remove' also drop the reference to the item?
125−
126−--TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hsdeleted−35
@@ -1,35 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−-- | This module exports all of the commonly-used functionality of Reflex; if
3−-- you are just getting started with Reflex, this is probably what you want.
4−module Reflex
5− ( module X
6− ) where
7−
8−import Reflex.Class as X
9−import Reflex.Adjustable.Class as X
10−import Reflex.BehaviorWriter.Base as X
11−import Reflex.BehaviorWriter.Class as X
12−import Reflex.Collection as X
13−import Reflex.Dynamic as X
14−import Reflex.EventWriter.Base as X
15−import Reflex.EventWriter.Class as X
16−#ifdef USE_TEMPLATE_HASKELL
17−import Reflex.Dynamic.TH as X
18−#endif
19−import Reflex.Dynamic.Uniq as X
20−import Reflex.DynamicWriter.Base as X
21−import Reflex.DynamicWriter.Class as X
22−import Reflex.NotReady.Class as X
23−import Reflex.PerformEvent.Base as X
24−import Reflex.PerformEvent.Class as X
25−import Reflex.PostBuild.Base as X
26−import Reflex.PostBuild.Class as X
27−import Reflex.Profiled as X
28−import Reflex.Query.Base as X
29−import Reflex.Query.Class as X
30−import Reflex.Requester.Base as X
31−import Reflex.Requester.Class as X
32−import Reflex.Spider as X
33−import Reflex.Time as X
34−import Reflex.TriggerEvent.Base as X
35−import Reflex.TriggerEvent.Class as X
src/Reflex/Adjustable/Class.hsdeleted−139
@@ -1,139 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−#ifdef USE_REFLEX_OPTIMIZER
11−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12−#endif
13−-- |
14−-- Module:
15−-- Reflex.Adjustable.Class
16−-- Description:
17−-- A class for actions that can be "adjusted" over time based on some 'Event'
18−-- such that, when observed after the firing of any such 'Event', the result
19−-- is as though the action was originally run with the 'Event's value.
20−module Reflex.Adjustable.Class
21− (
22− -- * The Adjustable typeclass
23− Adjustable(..)
24− , sequenceDMapWithAdjust
25− , sequenceDMapWithAdjustWithMove
26− , mapMapWithAdjustWithMove
27− -- * Deprecated aliases
28− , MonadAdjust
29− ) where
30−
31−import Control.Monad.Identity
32−import Control.Monad.Reader
33−import Data.Dependent.Map (DMap, GCompare (..))
34−import qualified Data.Dependent.Map as DMap
35−import Data.Functor.Constant
36−import Data.Functor.Misc
37−import Data.IntMap.Strict (IntMap)
38−import qualified Data.IntMap.Strict as IntMap
39−import Data.Map (Map)
40−
41−import Reflex.Class
42−import Reflex.Patch.DMapWithMove
43−
44−-- | A 'Monad' that supports adjustment over time. After an action has been
45−-- run, if the given events fire, it will adjust itself so that its net effect
46−-- is as though it had originally been run with the new value. Note that there
47−-- is some issue here with persistent side-effects: obviously, IO (and some
48−-- other side-effects) cannot be undone, so it is up to the instance implementer
49−-- to determine what the best meaning for this class is in such cases.
50−class (Reflex t, Monad m) => Adjustable t m | m -> t where
51− runWithReplace
52− :: m a
53− -> Event t (m b)
54− -> m (a, Event t b)
55−
56− traverseIntMapWithKeyWithAdjust
57− :: (IntMap.Key -> v -> m v')
58− -> IntMap v
59− -> Event t (PatchIntMap v)
60− -> m (IntMap v', Event t (PatchIntMap v'))
61−
62− traverseDMapWithKeyWithAdjust
63− :: GCompare k
64− => (forall a. k a -> v a -> m (v' a))
65− -> DMap k v
66− -> Event t (PatchDMap k v)
67− -> m (DMap k v', Event t (PatchDMap k v'))
68− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
69− traverseDMapWithKeyWithAdjust f dm0 dm' = fmap (fmap (fmap fromPatchWithMove)) $
70− traverseDMapWithKeyWithAdjustWithMove f dm0 $ fmap toPatchWithMove dm'
71− where
72− toPatchWithMove (PatchDMap m) = PatchDMapWithMove $ DMap.map toNodeInfoWithMove m
73− toNodeInfoWithMove = \case
74− ComposeMaybe (Just v) -> NodeInfo (From_Insert v) $ ComposeMaybe Nothing
75− ComposeMaybe Nothing -> NodeInfo From_Delete $ ComposeMaybe Nothing
76− fromPatchWithMove (PatchDMapWithMove m) = PatchDMap $ DMap.map fromNodeInfoWithMove m
77− fromNodeInfoWithMove (NodeInfo from _) = ComposeMaybe $ case from of
78− From_Insert v -> Just v
79− From_Delete -> Nothing
80− From_Move _ -> error "traverseDMapWithKeyWithAdjust: implementation of traverseDMapWithKeyWithAdjustWithMove inserted spurious move"
81−
82− traverseDMapWithKeyWithAdjustWithMove
83− :: GCompare k
84− => (forall a. k a -> v a -> m (v' a))
85− -> DMap k v
86− -> Event t (PatchDMapWithMove k v)
87− -> m (DMap k v', Event t (PatchDMapWithMove k v'))
88−
89−instance Adjustable t m => Adjustable t (ReaderT r m) where
90− runWithReplace a0 a' = do
91− r <- ask
92− lift $ runWithReplace (runReaderT a0 r) $ fmap (`runReaderT` r) a'
93− traverseIntMapWithKeyWithAdjust f dm0 dm' = do
94− r <- ask
95− lift $ traverseIntMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm'
96− traverseDMapWithKeyWithAdjust f dm0 dm' = do
97− r <- ask
98− lift $ traverseDMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm'
99− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
100− r <- ask
101− lift $ traverseDMapWithKeyWithAdjustWithMove (\k v -> runReaderT (f k v) r) dm0 dm'
102−
103−-- | Traverse a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches
104−-- to the 'DMap' can add, remove, or update values.
105−sequenceDMapWithAdjust
106− :: (GCompare k, Adjustable t m)
107− => DMap k m
108− -> Event t (PatchDMap k m)
109− -> m (DMap k Identity, Event t (PatchDMap k Identity))
110−sequenceDMapWithAdjust = traverseDMapWithKeyWithAdjust $ \_ -> fmap Identity
111−
112−-- | Traverses a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches
113−-- to the 'DMap' can add, remove, update, move, or swap values.
114−sequenceDMapWithAdjustWithMove
115− :: (GCompare k, Adjustable t m)
116− => DMap k m
117− -> Event t (PatchDMapWithMove k m)
118− -> m (DMap k Identity, Event t (PatchDMapWithMove k Identity))
119−sequenceDMapWithAdjustWithMove = traverseDMapWithKeyWithAdjustWithMove $ \_ -> fmap Identity
120−
121−-- | Traverses a 'Map', running the provided 'Adjustable' action. The provided 'Event' of patches to the 'Map'
122−-- can add, remove, update, move, or swap values.
123−mapMapWithAdjustWithMove
124− :: forall t m k v v'. (Adjustable t m, Ord k)
125− => (k -> v -> m v')
126− -> Map k v
127− -> Event t (PatchMapWithMove k v)
128− -> m (Map k v', Event t (PatchMapWithMove k v'))
129−mapMapWithAdjustWithMove f m0 m' = do
130− (out0 :: DMap (Const2 k v) (Constant v'), out') <- traverseDMapWithKeyWithAdjustWithMove (\(Const2 k) (Identity v) -> Constant <$> f k v) (mapToDMap m0) (const2PatchDMapWithMoveWith Identity <$> m')
131− return (dmapToMapWith (\(Constant v') -> v') out0, patchDMapWithMoveToPatchMapWithMoveWith (\(Constant v') -> v') <$> out')
132−
133−--------------------------------------------------------------------------------
134−-- Deprecated functions
135−--------------------------------------------------------------------------------
136−
137−{-# DEPRECATED MonadAdjust "Use Adjustable instead" #-}
138−-- | Synonym for 'Adjustable'
139−type MonadAdjust = Adjustable
src/Reflex/BehaviorWriter/Base.hsdeleted−202
@@ -1,202 +0,0 @@
1−{-|
2−Module: Reflex.BehaviorWriter.Base
3−Description: Implementation of MonadBehaviorWriter
4−-}
5−{-# LANGUAGE CPP #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE GADTs #-}
8−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−{-# LANGUAGE StandaloneDeriving #-}
15−#ifdef USE_REFLEX_OPTIMIZER
16−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
17−#endif
18−module Reflex.BehaviorWriter.Base
19− ( BehaviorWriterT (..)
20− , runBehaviorWriterT
21− , withBehaviorWriterT
22− ) where
23−
24−import Control.Monad.Exception
25−import Control.Monad.Identity
26−import Control.Monad.IO.Class
27−import Control.Monad.Reader
28−import Control.Monad.Ref
29−import Control.Monad.State.Strict
30−import Data.Dependent.Map (DMap)
31−import qualified Data.Dependent.Map as DMap
32−import Data.Functor.Misc
33−import Data.IntMap (IntMap)
34−import qualified Data.IntMap as IntMap
35−import Data.Map (Map)
36−import qualified Data.Map as Map
37−import Data.Some (Some)
38−
39−import Reflex.Class
40−import Reflex.Adjustable.Class
41−import Reflex.BehaviorWriter.Class
42−import Reflex.Host.Class
43−import Reflex.PerformEvent.Class
44−import Reflex.PostBuild.Class
45−import Reflex.Query.Class
46−import Reflex.Requester.Class
47−import Reflex.TriggerEvent.Class
48−
49−-- | A basic implementation of 'MonadBehaviorWriter'.
50−newtype BehaviorWriterT t w m a = BehaviorWriterT { unBehaviorWriterT :: StateT [Behavior t w] m a }
51− deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadAsyncException, MonadException) -- The list is kept in reverse order
52−
53−-- | Run a 'BehaviorWriterT' action. The behavior writer output will be provided
54−-- along with the result of the action.
55−runBehaviorWriterT :: (Monad m, Reflex t, Monoid w) => BehaviorWriterT t w m a -> m (a, Behavior t w)
56−runBehaviorWriterT (BehaviorWriterT a) = do
57− (result, ws) <- runStateT a []
58− return (result, mconcat $ reverse ws)
59−
60−-- | Map a function over the output of a 'BehaviorWriterT'.
61−withBehaviorWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m)
62− => (w -> w')
63− -> BehaviorWriterT t w m a
64− -> BehaviorWriterT t w' m a
65−withBehaviorWriterT f dw = do
66− (r, d) <- lift $ do
67− (r, d) <- runBehaviorWriterT dw
68− let d' = fmap f d
69− return (r, d')
70− tellBehavior d
71− return r
72−
73−deriving instance MonadHold t m => MonadHold t (BehaviorWriterT t w m)
74−deriving instance MonadSample t m => MonadSample t (BehaviorWriterT t w m)
75−
76−instance MonadTrans (BehaviorWriterT t w) where
77− lift = BehaviorWriterT . lift
78−
79−instance MonadRef m => MonadRef (BehaviorWriterT t w m) where
80− type Ref (BehaviorWriterT t w m) = Ref m
81− newRef = lift . newRef
82− readRef = lift . readRef
83− writeRef r = lift . writeRef r
84−
85−instance MonadAtomicRef m => MonadAtomicRef (BehaviorWriterT t w m) where
86− atomicModifyRef r = lift . atomicModifyRef r
87−
88−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (BehaviorWriterT t w m) where
89− newEventWithTrigger = lift . newEventWithTrigger
90− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
91−
92−instance (Monad m, Monoid w, Reflex t) => MonadBehaviorWriter t w (BehaviorWriterT t w m) where
93− tellBehavior w = BehaviorWriterT $ modify (w :)
94−
95−instance MonadReader r m => MonadReader r (BehaviorWriterT t w m) where
96− ask = lift ask
97− local f (BehaviorWriterT a) = BehaviorWriterT $ mapStateT (local f) a
98− reader = lift . reader
99−
100−instance PerformEvent t m => PerformEvent t (BehaviorWriterT t w m) where
101− type Performable (BehaviorWriterT t w m) = Performable m
102− performEvent_ = lift . performEvent_
103− performEvent = lift . performEvent
104−
105−instance TriggerEvent t m => TriggerEvent t (BehaviorWriterT t w m) where
106− newTriggerEvent = lift newTriggerEvent
107− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
108− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
109−
110−instance PostBuild t m => PostBuild t (BehaviorWriterT t w m) where
111− getPostBuild = lift getPostBuild
112−
113−instance MonadState s m => MonadState s (BehaviorWriterT t w m) where
114− get = lift get
115− put = lift . put
116−
117−instance Requester t m => Requester t (BehaviorWriterT t w m) where
118− type Request (BehaviorWriterT t w m) = Request m
119− type Response (BehaviorWriterT t w m) = Response m
120− requesting = lift . requesting
121− requesting_ = lift . requesting_
122−
123−instance (MonadQuery t q m, Monad m) => MonadQuery t q (BehaviorWriterT t w m) where
124− tellQueryIncremental = lift . tellQueryIncremental
125− askQueryResult = lift askQueryResult
126− queryIncremental = lift . queryIncremental
127−
128−instance (Adjustable t m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (BehaviorWriterT t w m) where
129− runWithReplace a0 a' = do
130− (result0, result') <- lift $ runWithReplace (runBehaviorWriterT a0) $ runBehaviorWriterT <$> a'
131− tellBehavior . join =<< hold (snd result0) (snd <$> result')
132− return (fst result0, fst <$> result')
133− traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust
134− traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith
135−
136−traverseIntMapWithKeyWithAdjustImpl
137− :: forall t w v' p p' v m.
138− ( PatchTarget (p' (Behavior t w)) ~ IntMap (Behavior t w)
139− , Patch (p' (Behavior t w))
140− , Monoid w
141− , Reflex t
142− , MonadHold t m
143− , Functor p
144− , p ~ p'
145− )
146− => ( (IntMap.Key -> v -> m (v', Behavior t w))
147− -> IntMap v
148− -> Event t (p v)
149− -> m (IntMap (v', Behavior t w), Event t (p (v', Behavior t w)))
150− )
151− -> (IntMap.Key -> v -> BehaviorWriterT t w m v')
152− -> IntMap v
153− -> Event t (p v)
154− -> BehaviorWriterT t w m (IntMap v', Event t (p v'))
155−traverseIntMapWithKeyWithAdjustImpl base f (dm0 :: IntMap v) dm' = do
156− (result0, result') <- lift $ base (\k v -> runBehaviorWriterT $ f k v) dm0 dm'
157− let liftedResult0 = fmap fst result0
158− liftedResult' = fmap (fmap fst) result'
159− liftedWritten0 :: IntMap (Behavior t w)
160− liftedWritten0 = fmap snd result0
161− liftedWritten' = fmap (fmap snd) result'
162− i <- holdIncremental liftedWritten0 liftedWritten'
163− tellBehavior $ pull $ do
164− m <- sample $ currentIncremental i
165− mconcat . IntMap.elems <$> traverse sample m
166− return (liftedResult0, liftedResult')
167−
168−newtype BehaviorWriterTLoweredResult t w v a = BehaviorWriterTLoweredResult (v a, Behavior t w)
169−
170−traverseDMapWithKeyWithAdjustImpl
171− :: forall t w k v' p p' v m.
172− ( PatchTarget (p' (Some k) (Behavior t w)) ~ Map (Some k) (Behavior t w)
173− , Patch (p' (Some k) (Behavior t w))
174− , Monoid w
175− , Reflex t
176− , MonadHold t m
177− )
178− => ( (forall a. k a -> v a -> m (BehaviorWriterTLoweredResult t w v' a))
179− -> DMap k v
180− -> Event t (p k v)
181− -> m (DMap k (BehaviorWriterTLoweredResult t w v'), Event t (p k (BehaviorWriterTLoweredResult t w v')))
182− )
183− -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> v' a) -> p k (BehaviorWriterTLoweredResult t w v') -> p k v')
184− -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> Behavior t w) -> p k (BehaviorWriterTLoweredResult t w v') -> p' (Some k) (Behavior t w))
185− -> (forall a. k a -> v a -> BehaviorWriterT t w m (v' a))
186− -> DMap k v
187− -> Event t (p k v)
188− -> BehaviorWriterT t w m (DMap k v', Event t (p k v'))
189−traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith f (dm0 :: DMap k v) dm' = do
190− (result0, result') <- lift $ base (\k v -> fmap BehaviorWriterTLoweredResult $ runBehaviorWriterT $ f k v) dm0 dm'
191− let getValue (BehaviorWriterTLoweredResult (v, _)) = v
192− getWritten (BehaviorWriterTLoweredResult (_, w)) = w
193− liftedResult0 = DMap.map getValue result0
194− liftedResult' = ffor result' $ mapPatch getValue
195− liftedWritten0 :: Map (Some k) (Behavior t w)
196− liftedWritten0 = weakenDMapWith getWritten result0
197− liftedWritten' = ffor result' $ weakenPatchWith getWritten
198− i <- holdIncremental liftedWritten0 liftedWritten'
199− tellBehavior $ pull $ do
200− m <- sample $ currentIncremental i
201− mconcat . Map.elems <$> traverse sample m
202− return (liftedResult0, liftedResult')
src/Reflex/BehaviorWriter/Class.hsdeleted−25
@@ -1,25 +0,0 @@
1−{-|
2−Module: Reflex.BehaviorWriter.Class
3−Description: This module defines the 'MonadBehaviorWriter' class
4−-}
5−{-# LANGUAGE CPP #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE UndecidableInstances #-}
9−#ifdef USE_REFLEX_OPTIMIZER
10−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
11−#endif
12−module Reflex.BehaviorWriter.Class
13− ( MonadBehaviorWriter (..)
14− ) where
15−
16−import Control.Monad.Reader (ReaderT, lift)
17−import Reflex.Class (Behavior)
18−
19−-- | 'MonadBehaviorWriter' efficiently collects 'Behavior' values using 'tellBehavior'
20−-- and combines them monoidally to provide a 'Behavior' result.
21−class (Monad m, Monoid w) => MonadBehaviorWriter t w m | m -> t w where
22− tellBehavior :: Behavior t w -> m ()
23−
24−instance MonadBehaviorWriter t w m => MonadBehaviorWriter t w (ReaderT r m) where
25− tellBehavior = lift . tellBehavior
src/Reflex/Class.hsdeleted−1676
@@ -1,1676 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE DefaultSignatures #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE LambdaCase #-}
10−{-# LANGUAGE NoMonomorphismRestriction #-}
11−{-# LANGUAGE PolyKinds #-}
12−{-# LANGUAGE RankNTypes #-}
13−{-# LANGUAGE RecursiveDo #-}
14−{-# LANGUAGE RoleAnnotations #-}
15−{-# LANGUAGE ScopedTypeVariables #-}
16−{-# LANGUAGE TypeFamilies #-}
17−{-# LANGUAGE TypeOperators #-}
18−{-# LANGUAGE UndecidableInstances #-}
19−{-# LANGUAGE Trustworthy #-}
20−#ifdef USE_REFLEX_OPTIMIZER
21−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
22−#endif
23−
24−-- |
25−-- Module:
26−-- Reflex.Class
27−-- Description:
28−-- This module contains the Reflex interface, as well as a variety of
29−-- convenience functions for working with 'Event's, 'Behavior's, and other
30−-- signals.
31−module Reflex.Class
32− ( module Reflex.Patch
33− -- * Primitives
34− , Reflex (..)
35− , mergeInt
36− , coerceBehavior
37− , coerceEvent
38− , coerceDynamic
39− , coerceIncremental
40− , MonadSample (..)
41− , MonadHold (..)
42− -- ** 'fan' related types
43− , EventSelector (..)
44− , EventSelectorG (..)
45− , EventSelectorInt (..)
46− -- * Convenience functions
47− , constDyn
48− , pushAlways
49− -- ** Combining 'Event's
50− , leftmost
51− , merge
52− , mergeIncremental
53− , mergeIncrementalWithMove
54− , mergeMap
55− , mergeIntMap
56− , mergeMapIncremental
57− , mergeMapIncrementalWithMove
58− , mergeIntMapIncremental
59− , coincidencePatchMap
60− , coincidencePatchMapWithMove
61− , coincidencePatchIntMap
62− , mergeList
63− , mergeWith
64− , difference
65− , alignEventWithMaybe
66− -- ** Breaking up 'Event's
67− , splitE
68− , fan
69− , fanEither
70− , fanThese
71− , fanMap
72− , dmapToThese
73− , EitherTag (..)
74− , eitherToDSum
75− , dsumToEither
76− , factorEvent
77− , filterEventKey
78− -- ** Collapsing 'Event . Event'
79− , switchHold
80− , switchHoldPromptly
81− , switchHoldPromptOnly
82− , switchHoldPromptOnlyIncremental
83− -- ** Using 'Event's to sample 'Behavior's
84− , tag
85− , tagMaybe
86− , attach
87− , attachWith
88− , attachWithMaybe
89− -- ** Blocking an 'Event' based on a 'Behavior'
90− , gate
91− -- ** Combining 'Dynamic's
92− , distributeDMapOverDynPure
93− , distributeDMapOverDynPureG
94− , distributeListOverDyn
95− , distributeListOverDynWith
96− , zipDyn
97− , zipDynWith
98− -- ** Accumulating state
99− , Accumulator (..)
100− , accumDyn
101− , accumMDyn
102− , accumMaybeDyn
103− , accumMaybeMDyn
104− , mapAccumDyn
105− , mapAccumMDyn
106− , mapAccumMaybeDyn
107− , mapAccumMaybeMDyn
108− , accumB
109− , accumMB
110− , accumMaybeB
111− , accumMaybeMB
112− , mapAccumB
113− , mapAccumMB
114− , mapAccumMaybeB
115− , mapAccumMaybeMB
116− , mapAccum_
117− , mapAccumM_
118− , mapAccumMaybe_
119− , mapAccumMaybeM_
120− , accumIncremental
121− , accumMIncremental
122− , accumMaybeIncremental
123− , accumMaybeMIncremental
124− , mapAccumIncremental
125− , mapAccumMIncremental
126− , mapAccumMaybeIncremental
127− , mapAccumMaybeMIncremental
128− , zipListWithEvent
129− , numberOccurrences
130− , numberOccurrencesFrom
131− , numberOccurrencesFrom_
132− , (<@>)
133− , (<@)
134− , tailE
135− , headTailE
136− , takeWhileE
137− , takeWhileJustE
138− , dropWhileE
139− , takeDropWhileJustE
140− , switcher
141− -- * Debugging functions
142− , traceEvent
143− , traceEventWith
144− -- * Unsafe functions
145− , unsafeDynamic
146− , unsafeMapIncremental
147− -- * 'Filterable' convenience functions
148− , FunctorMaybe -- fmapMaybe is purposely not exported from deprecated 'FunctorMaybe' and the new alias is exported instead
149− , mapMaybe -- Re-exported for convenience
150− , fmapMaybe
151− , fforMaybe
152− , ffilter
153− , filterLeft
154− , filterRight
155− -- * Miscellaneous convenience functions
156− , ffor
157− , ffor2
158− , ffor3
159− -- * Deprecated functions
160− , switchPromptly
161− , switchPromptOnly
162− -- * "Cheap" functions
163− , fmapMaybeCheap
164− , mapMaybeCheap
165− , fmapCheap
166− , fforCheap
167− , fforMaybeCheap
168− , pushAlwaysCheap
169− , tagCheap
170− , mergeWithCheap
171− , mergeWithCheap'
172− -- * Slow, but general, implementations
173− , slowHeadE
174− ) where
175−
176−#ifdef MIN_VERSION_semialign
177−import Prelude hiding (zip, zipWith)
178−
179−#if MIN_VERSION_these(0,8,0)
180−import Data.These.Combinators (justThese)
181−#endif
182−#if MIN_VERSION_semialign(1,1,0)
183−import Data.Zip (Zip (..))
184−#endif
185−#endif
186−
187−import Control.Applicative
188−import Control.Monad.Identity
189−import Control.Monad.Reader
190−import Control.Monad.State.Strict
191−import Control.Monad.Trans.Cont (ContT)
192−import Control.Monad.Trans.Except (ExceptT)
193−import Control.Monad.Trans.RWS (RWST)
194−import Control.Monad.Trans.Writer (WriterT)
195−import Data.Align
196−import Data.Bifunctor
197−import Data.Coerce
198−import Data.Default
199−import Data.Dependent.Map (DMap, DSum (..))
200−import qualified Data.Dependent.Map as DMap
201−import Data.Functor.Compose
202−import Data.Functor.Product
203−import Data.GADT.Compare (GEq (..), GCompare (..), (:~:) (..))
204−import Data.FastMutableIntMap (PatchIntMap)
205−import Data.Foldable
206−import Data.Functor.Bind
207−import Data.Functor.Misc
208−import Data.Functor.Plus
209−import Data.IntMap.Strict (IntMap)
210−import qualified Data.IntMap.Strict as IntMap
211−import Data.List.NonEmpty (NonEmpty (..))
212−import Data.Map (Map)
213−import Data.Semigroup (Semigroup, sconcat, stimes, (<>))
214−import Data.Some (Some(Some))
215−import Data.String
216−import Data.These
217−import Data.Type.Coercion
218−import Data.Witherable (Filterable(..))
219−import qualified Data.Witherable as W
220−import Reflex.FunctorMaybe (FunctorMaybe)
221−import qualified Reflex.FunctorMaybe
222−import Reflex.Patch
223−import qualified Reflex.Patch.MapWithMove as PatchMapWithMove
224−
225−import Debug.Trace (trace)
226−
227−-- | The 'Reflex' class contains all the primitive functionality needed for
228−-- Functional Reactive Programming (FRP). The @/t/@ type parameter indicates
229−-- which "timeline" is in use. Timelines are fully-independent FRP contexts,
230−-- and the type of the timeline determines the FRP engine to be used. For most
231−-- purposes, the 'Reflex.Spider' implementation is recommended.
232−class ( MonadHold t (PushM t)
233− , MonadSample t (PullM t)
234− , MonadFix (PushM t)
235− , Functor (Dynamic t)
236− , Applicative (Dynamic t) -- Necessary for GHC <= 7.8
237− , Monad (Dynamic t)
238− ) => Reflex t where
239− -- | A container for a value that can change over time. 'Behavior's can be
240− -- sampled at will, but it is not possible to be notified when they change
241− data Behavior t :: * -> *
242− -- | A stream of occurrences. During any given frame, an 'Event' is either
243− -- occurring or not occurring; if it is occurring, it will contain a value of
244− -- the given type (its "occurrence type")
245− data Event t :: * -> *
246− -- | A container for a value that can change over time and allows
247− -- notifications on changes. Basically a combination of a 'Behavior' and an
248− -- 'Event', with a rule that the 'Behavior' will change if and only if the
249− -- 'Event' fires.
250− data Dynamic t :: * -> *
251− -- | An 'Incremental' is a more general form of a 'Dynamic'.
252− -- Instead of always fully replacing the value, only parts of it can be patched.
253− -- This is only needed for performance critical code via `mergeIncremental` to make small
254− -- changes to large values.
255− data Incremental t :: * -> *
256− -- | A monad for doing complex push-based calculations efficiently
257− type PushM t :: * -> *
258− -- | A monad for doing complex pull-based calculations efficiently
259− type PullM t :: * -> *
260− -- | An 'Event' with no occurrences
261− never :: Event t a
262− -- | Create a 'Behavior' that always has the given value
263− constant :: a -> Behavior t a --TODO: Refactor to use 'pure' from Applicative instead; however, we need to make sure that encouraging Applicative-style use of 'Behavior's doesn't have a negative performance impact
264− -- | Create an 'Event' from another 'Event'; the provided function can sample
265− -- 'Behavior's and hold 'Event's, and use the results to produce a occurring
266− -- (Just) or non-occurring (Nothing) result
267− push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
268− -- | Like 'push' but intended for functions that the implementation can consider cheap to compute for performance considerations. WARNING: The function passed to 'pushCheap' may be run multiple times without any caching.
269− pushCheap :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
270− -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be
271− -- recomputed whenever any of the read 'Behavior's changes
272− pull :: PullM t a -> Behavior t a
273− -- | Merge a collection of events; the resulting 'Event' will only occur if at
274− -- least one input event is occurring, and will contain all of the input keys
275− -- that are occurring simultaneously
276−
277− --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
278− mergeG :: GCompare k => (forall a. q a -> Event t (v a))
279− -> DMap k q -> Event t (DMap k v)
280−
281− -- | Efficiently fan-out an event to many destinations. You should save the
282− -- result in a @let@-binding, and then repeatedly 'selectG' on the result to
283− -- create child events
284− fanG :: GCompare k => Event t (DMap k v) -> EventSelectorG t k v
285−
286− -- | Create an 'Event' that will occur whenever the currently-selected input
287− -- 'Event' occurs
288− switch :: Behavior t (Event t a) -> Event t a
289− -- | Create an 'Event' that will occur whenever the input event is occurring -- and its occurrence value, another 'Event', is also occurring.
290− -- You maybe looking for '@switchHold@ @never@' instead.
291− coincidence :: Event t (Event t a) -> Event t a
292− -- | Extract the 'Behavior' of a 'Dynamic'.
293− current :: Dynamic t a -> Behavior t a
294− -- | Extract the 'Event' of the 'Dynamic'.
295− updated :: Dynamic t a -> Event t a
296− -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
297− -- recent firing of the given 'Event', if any.
298− unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
299− -- | Create a new 'Incremental'. The given "PullM"'s value must always change
300− -- in the same way that the accumulated application of patches would change
301− -- that value.
302− unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
303− -- | Create a merge whose parents can change over time
304− mergeIncrementalG :: GCompare k
305− => (forall a. q a -> Event t (v a))
306− -> Incremental t (PatchDMap k q)
307− -> Event t (DMap k v)
308− -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
309− mergeIncrementalWithMoveG :: GCompare k
310− => (forall a. q a -> Event t (v a))
311− -> Incremental t (PatchDMapWithMove k q) -> Event t (DMap k v)
312− -- | Extract the 'Behavior' component of an 'Incremental'
313− currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
314− -- | Extract the 'Event' component of an 'Incremental'
315− updatedIncremental :: Patch p => Incremental t p -> Event t p
316− -- | Convert an 'Incremental' to a 'Dynamic'
317− incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
318− -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
319− -- occurrence type
320− behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
321− -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
322− -- occurrence type
323− eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
324− -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
325− -- occurrence type
326− dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
327− -- | Construct a 'Coercion' for an 'Incremental' given 'Coercion's for its
328− -- patch target and patch types.
329− incrementalCoercion
330− :: Coercion (PatchTarget a) (PatchTarget b) -> Coercion a b -> Coercion (Incremental t a) (Incremental t b)
331− mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
332− fanInt :: Event t (IntMap a) -> EventSelectorInt t a
333−
334−-- | Efficiently fan-out an event to many destinations. You should save the
335−-- result in a @let@-binding, and then repeatedly 'select' on the result to
336−-- create child events
337−fan :: forall t k. (Reflex t, GCompare k)
338− => Event t (DMap k Identity) -> EventSelector t k
339− --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
340−fan e = EventSelector (fixup (selectG (fanG e) :: k a -> Event t (Identity a)) :: forall a. k a -> Event t a)
341− where
342− fixup :: forall a. (k a -> Event t (Identity a)) -> k a -> Event t a
343− fixup = case eventCoercion Coercion :: Coercion (Event t (Identity a)) (Event t a) of
344− Coercion -> coerce
345−
346−--TODO: Specialize this so that we can take advantage of knowing that there's no changing going on
347−-- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple
348−-- keys simultaneously.
349−mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
350−mergeInt m = mergeIntIncremental $ unsafeBuildIncremental (return m) never
351−
352−-- | Coerce a 'Behavior' between representationally-equivalent value types
353−coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
354−coerceBehavior = coerceWith $ behaviorCoercion Coercion
355−
356−-- | Coerce an 'Event' between representationally-equivalent occurrence types
357−coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
358−coerceEvent = coerceWith $ eventCoercion Coercion
359−
360−-- | Coerce a 'Dynamic' between representationally-equivalent value types
361−coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
362−coerceDynamic = coerceWith $ dynamicCoercion Coercion
363−
364−-- | Coerce an 'Incremental' between representationally-equivalent value types
365−coerceIncremental
366− :: (Reflex t, Coercible a b, Coercible (PatchTarget a) (PatchTarget b))
367− => Incremental t a -> Incremental t b
368−coerceIncremental = coerceWith $ incrementalCoercion Coercion Coercion
369−
370−-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
371−-- __must__ change when and only when the 'Event' fires, such that the
372−-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
373−-- if this is not the case, the resulting 'Dynamic' will behave
374−-- nondeterministically.
375−unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
376−unsafeDynamic = unsafeBuildDynamic . sample
377−
378−-- | Construct a 'Dynamic' value that never changes
379−constDyn :: Reflex t => a -> Dynamic t a
380−constDyn = pure
381−
382−instance (Reflex t, Default a) => Default (Dynamic t a) where
383− def = pure def
384−
385−-- | 'MonadSample' designates monads that can read the current value of a
386−-- 'Behavior'. This includes both 'PullM' and 'PushM'.
387−class (Applicative m, Monad m) => MonadSample t m | m -> t where
388− -- | Get the current value in the 'Behavior'
389− sample :: Behavior t a -> m a
390−
391−-- | 'MonadHold' designates monads that can create new 'Behavior's based on
392−-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
393−-- is required to create any stateful computations with Reflex.
394−class MonadSample t m => MonadHold t m where
395− -- | Create a new 'Behavior' whose value will initially be equal to the given
396− -- value and will be updated whenever the given 'Event' occurs. The update
397− -- takes effect immediately after the 'Event' occurs; if the occurrence that
398− -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
399− -- the 'Behavior', it will see the __old__ value of the 'Behavior', not the new
400− -- one.
401− hold :: a -> Event t a -> m (Behavior t a)
402− default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)
403− hold v0 = lift . hold v0
404− -- | Create a 'Dynamic' value using the given initial value that changes every
405− -- time the 'Event' occurs.
406− holdDyn :: a -> Event t a -> m (Dynamic t a)
407− default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)
408− holdDyn v0 = lift . holdDyn v0
409− -- | Create an 'Incremental' value using the given initial value that changes
410− -- every time the 'Event' occurs.
411− holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
412− default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)
413− holdIncremental v0 = lift . holdIncremental v0
414− buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)
415− {-
416− default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)
417− buildDynamic getV0 = lift . buildDynamic getV0
418− -}
419− -- | Create a new 'Event' that only occurs only once, on the first occurrence of
420− -- the supplied 'Event'.
421− headE :: Event t a -> m (Event t a)
422−
423−-- | Accumulate an 'Incremental' with the supplied initial value and the firings of the provided 'Event',
424−-- using the combining function to produce a patch.
425−accumIncremental
426− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
427− => (PatchTarget p -> b -> p)
428− -> PatchTarget p
429− -> Event t b
430− -> m (Incremental t p)
431−accumIncremental f = accumMaybeIncremental $ \v o -> Just $ f v o
432−
433−-- | Similar to 'accumIncremental' but the combining function runs in 'PushM'
434−accumMIncremental
435− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
436− => (PatchTarget p -> b -> PushM t p)
437− -> PatchTarget p
438− -> Event t b
439− -> m (Incremental t p)
440−accumMIncremental f = accumMaybeMIncremental $ \v o -> Just <$> f v o
441−
442−-- | Similar to 'accumIncremental' but allows filtering of updates (by dropping updates when the
443−-- combining function produces @Nothing@)
444−accumMaybeIncremental
445− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
446− => (PatchTarget p -> b -> Maybe p)
447− -> PatchTarget p
448− -> Event t b
449− -> m (Incremental t p)
450−accumMaybeIncremental f = accumMaybeMIncremental $ \v o -> return $ f v o
451−
452−-- | Similar to 'accumMaybeMIncremental' but the combining function runs in 'PushM'
453−accumMaybeMIncremental
454− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
455− => (PatchTarget p -> b -> PushM t (Maybe p))
456− -> PatchTarget p
457− -> Event t b
458− -> m (Incremental t p)
459−accumMaybeMIncremental f z e = do
460− rec let e' = flip push e $ \o -> do
461− v <- sample $ currentIncremental d'
462− f v o
463− d' <- holdIncremental z e'
464− return d'
465−
466−-- | Accumulate an 'Incremental' by folding occurrences of an 'Event'
467−-- with a function that both accumulates and produces a value to fire
468−-- as an 'Event'. Returns both the accumulated value and the constructed
469−-- 'Event'.
470−mapAccumIncremental
471− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
472− => (PatchTarget p -> b -> (p, c))
473− -> PatchTarget p
474− -> Event t b
475− -> m (Incremental t p, Event t c)
476−mapAccumIncremental f = mapAccumMaybeIncremental $ \v o -> bimap Just Just $ f v o
477−
478−-- | Like 'mapAccumIncremental' but the combining function runs in 'PushM'
479−mapAccumMIncremental
480− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
481− => (PatchTarget p -> b -> PushM t (p, c))
482− -> PatchTarget p
483− -> Event t b
484− -> m (Incremental t p, Event t c)
485−mapAccumMIncremental f = mapAccumMaybeMIncremental $ \v o -> bimap Just Just <$> f v o
486−
487−-- | Accumulate an 'Incremental' by folding occurrences of an 'Event' with
488−-- a function that both optionally accumulates and optionally produces
489−-- a value to fire as a separate output 'Event'.
490−-- Note that because 'Nothing's are discarded in both cases, the output
491−-- 'Event' may fire even though the output 'Incremental' has not changed, and
492−-- the output 'Incremental' may update even when the output 'Event' is not firing.
493−mapAccumMaybeIncremental
494− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
495− => (PatchTarget p -> b -> (Maybe p, Maybe c))
496− -> PatchTarget p
497− -> Event t b
498− -> m (Incremental t p, Event t c)
499−mapAccumMaybeIncremental f = mapAccumMaybeMIncremental $ \v o -> return $ f v o
500−
501−-- | Like 'mapAccumMaybeIncremental' but the combining function is a 'PushM' action
502−mapAccumMaybeMIncremental
503− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
504− => (PatchTarget p -> b -> PushM t (Maybe p, Maybe c))
505− -> PatchTarget p
506− -> Event t b
507− -> m (Incremental t p, Event t c)
508−mapAccumMaybeMIncremental f z e = do
509− rec let e' = flip push e $ \o -> do
510− v <- sample $ currentIncremental d'
511− result <- f v o
512− return $ case result of
513− (Nothing, Nothing) -> Nothing
514− _ -> Just result
515− d' <- holdIncremental z $ mapMaybe fst e'
516− return (d', mapMaybe snd e')
517−
518−-- | A somewhat slow implementation of 'headE'
519−slowHeadE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
520−slowHeadE e = do
521− rec be <- hold e $ fmapCheap (const never) e'
522− let e' = switch be
523− return e'
524−
525−-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
526−-- key. This is much more efficient than filtering for each key with
527−-- 'mapMaybe'.
528−newtype EventSelector t k = EventSelector
529− { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
530− -- determined by the type of the key, so this can be used to fan-out
531− -- 'Event's whose sub-'Event's have different types.
532− --
533− -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
534− -- (but equivalent to) using 'mapMaybe' to select only the relevant
535− -- occurrences of an 'Event'.
536− select :: forall a. k a -> Event t a
537− }
538−
539−newtype EventSelectorG t k v = EventSelectorG
540− { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
541− -- determined by the type of the key, so this can be used to fan-out
542− -- 'Event's whose sub-'Event's have different types.
543− --
544− -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
545− -- (but equivalent to) using 'mapMaybe' to select only the relevant
546− -- occurrences of an 'Event'.
547− selectG :: forall a. k a -> Event t (v a)
548− }
549−
550−-- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually
551−-- filtering by key.
552−newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }
553−
554−--------------------------------------------------------------------------------
555−-- Instances
556−--------------------------------------------------------------------------------
557−
558−instance MonadSample t m => MonadSample t (ReaderT r m) where
559− sample = lift . sample
560−
561−instance MonadHold t m => MonadHold t (ReaderT r m) where
562− hold a0 = lift . hold a0
563− holdDyn a0 = lift . holdDyn a0
564− holdIncremental a0 = lift . holdIncremental a0
565− buildDynamic a0 = lift . buildDynamic a0
566− headE = lift . headE
567−
568−instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
569− sample = lift . sample
570−
571−instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
572− hold a0 = lift . hold a0
573− holdDyn a0 = lift . holdDyn a0
574− holdIncremental a0 = lift . holdIncremental a0
575− buildDynamic a0 = lift . buildDynamic a0
576− headE = lift . headE
577−
578−instance MonadSample t m => MonadSample t (StateT s m) where
579− sample = lift . sample
580−
581−instance MonadHold t m => MonadHold t (StateT s m) where
582− hold a0 = lift . hold a0
583− holdDyn a0 = lift . holdDyn a0
584− holdIncremental a0 = lift . holdIncremental a0
585− buildDynamic a0 = lift . buildDynamic a0
586− headE = lift . headE
587−
588−instance MonadSample t m => MonadSample t (ExceptT e m) where
589− sample = lift . sample
590−
591−instance MonadHold t m => MonadHold t (ExceptT e m) where
592− hold a0 = lift . hold a0
593− holdDyn a0 = lift . holdDyn a0
594− holdIncremental a0 = lift . holdIncremental a0
595− buildDynamic a0 = lift . buildDynamic a0
596− headE = lift . headE
597−
598−instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
599− sample = lift . sample
600−
601−instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
602− hold a0 = lift . hold a0
603− holdDyn a0 = lift . holdDyn a0
604− holdIncremental a0 = lift . holdIncremental a0
605− buildDynamic a0 = lift . buildDynamic a0
606− headE = lift . headE
607−
608−instance MonadSample t m => MonadSample t (ContT r m) where
609− sample = lift . sample
610−
611−instance MonadHold t m => MonadHold t (ContT r m) where
612− hold a0 = lift . hold a0
613− holdDyn a0 = lift . holdDyn a0
614− holdIncremental a0 = lift . holdIncremental a0
615− buildDynamic a0 = lift . buildDynamic a0
616− headE = lift . headE
617−
618−--------------------------------------------------------------------------------
619−-- Convenience functions
620−--------------------------------------------------------------------------------
621−
622−-- | Create an 'Event' from another 'Event'. The provided function can sample
623−-- 'Behavior's and hold 'Event's.
624−pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
625−pushAlways f = push (fmap Just . f)
626−
627−-- | Flipped version of 'fmap'.
628−ffor :: Functor f => f a -> (a -> b) -> f b
629−ffor = flip fmap
630−
631−-- | Rotated version of 'liftA2'.
632−ffor2 :: Applicative f => f a -> f b -> (a -> b -> c) -> f c
633−ffor2 a b f = liftA2 f a b
634−
635−-- | Rotated version of 'liftA3'.
636−ffor3 :: Applicative f => f a -> f b -> f c -> (a -> b -> c -> d) -> f d
637−ffor3 a b c f = liftA3 f a b c
638−
639−instance Reflex t => Applicative (Behavior t) where
640− pure = constant
641− f <*> x = pull $ sample f `ap` sample x
642− _ *> b = b
643− a <* _ = a
644−
645−instance Reflex t => Apply (Behavior t) where
646− (<.>) = (<*>)
647−
648−instance Reflex t => Bind (Behavior t) where
649− (>>-) = (>>=)
650−
651−instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
652− (/) = liftA2 (/)
653− fromRational = pure . fromRational
654− recip = fmap recip
655−
656−instance Reflex t => Functor (Behavior t) where
657− fmap f = pull . fmap f . sample
658−
659−instance (Reflex t, IsString a) => IsString (Behavior t a) where
660− fromString = pure . fromString
661−
662−instance Reflex t => Monad (Behavior t) where
663− a >>= f = pull $ sample a >>= sample . f
664− -- Note: it is tempting to write (_ >> b = b); however, this would result in (fail x >> return y) succeeding (returning y), which violates the law that (a >> b = a >>= \_ -> b), since the implementation of (>>=) above actually will fail. Since we can't examine 'Behavior's other than by using sample, I don't think it's possible to write (>>) to be more efficient than the (>>=) above.
665− return = constant
666− fail = error "Monad (Behavior t) does not support fail"
667−
668−instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
669− mempty = constant mempty
670− mappend a b = pull $ liftM2 mappend (sample a) (sample b)
671− mconcat = pull . fmap mconcat . mapM sample
672−
673−instance (Reflex t, Num a) => Num (Behavior t a) where
674− (+) = liftA2 (+)
675− (-) = liftA2 (-)
676− (*) = liftA2 (*)
677− abs = fmap abs
678− fromInteger = pure . fromInteger
679− negate = fmap negate
680− signum = fmap signum
681−
682−instance (Num a, Reflex t) => Num (Dynamic t a) where
683− (+) = liftA2 (+)
684− (*) = liftA2 (*)
685− abs = fmap abs
686− signum = fmap signum
687− fromInteger = pure . fromInteger
688− negate = fmap negate
689− (-) = liftA2 (-)
690−
691−instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
692− a <> b = pull $ liftM2 (<>) (sample a) (sample b)
693− sconcat = pull . fmap sconcat . mapM sample
694− stimes n = fmap $ stimes n
695−
696−-- | Alias for 'mapMaybe'
697−fmapMaybe :: Filterable f => (a -> Maybe b) -> f a -> f b
698−fmapMaybe = mapMaybe
699−
700−-- | Flipped version of 'mapMaybe'.
701−fforMaybe :: Filterable f => f a -> (a -> Maybe b) -> f b
702−fforMaybe = flip mapMaybe
703−
704−-- | Filter 'f a' using the provided predicate.
705−ffilter :: Filterable f => (a -> Bool) -> f a -> f a
706−ffilter = W.filter
707−
708−-- | Filter 'Left's from 'f (Either a b)' into 'a'.
709−filterLeft :: Filterable f => f (Either a b) -> f a
710−filterLeft = mapMaybe (either Just (const Nothing))
711−
712−-- | Filter 'Right's from 'f (Either a b)' into 'b'.
713−filterRight :: Filterable f => f (Either a b) -> f b
714−filterRight = mapMaybe (either (const Nothing) Just)
715−
716−-- | Left-biased event union (prefers left event on simultaneous
717−-- occurrence).
718−instance Reflex t => Alt (Event t) where
719− ev1 <!> ev2 = leftmost [ev1, ev2]
720−
721−-- | 'Event' intersection. Only occurs when both events are co-incident.
722−instance Reflex t => Apply (Event t) where
723− evf <.> evx = mapMaybe f (align evf evx) where
724− f (These g a) = Just (g a)
725− f _ = Nothing
726−
727−
728−-- | 'Event' intersection (convenient interface to 'coincidence').
729−instance Reflex t => Bind (Event t) where
730− evx >>- f = coincidence (f <$> evx)
731− join = coincidence
732−
733−instance Reflex t => Functor (Event t) where
734− {-# INLINE fmap #-}
735− fmap f = mapMaybe $ Just . f
736− {-# INLINE (<$) #-}
737− x <$ e = fmapCheap (const x) e
738−
739−-- TODO Remove this instance
740−instance Reflex t => FunctorMaybe (Event t) where
741− {-# INLINE fmapMaybe #-}
742− fmapMaybe = mapMaybe
743−
744−instance Reflex t => Filterable (Event t) where
745− {-# INLINE mapMaybe #-}
746− mapMaybe f = push $ return . f
747−
748−-- | Never: @'zero' = 'never'@.
749−instance Reflex t => Plus (Event t) where
750− zero = never
751−
752−-- | Replace each occurrence value of the 'Event' with the value of the
753−-- 'Behavior' at the time of that occurrence.
754−tag :: Reflex t => Behavior t b -> Event t a -> Event t b
755−tag b = pushAlways $ \_ -> sample b
756−
757−-- | Replace each occurrence value of the 'Event' with the value of the
758−-- 'Behavior' at that time; if it is 'Just', fire with the contained value; if
759−-- it is 'Nothing', drop the occurrence.
760−tagMaybe :: Reflex t => Behavior t (Maybe b) -> Event t a -> Event t b
761−tagMaybe b = push $ \_ -> sample b
762−
763−-- | Create a new 'Event' that combines occurrences of supplied 'Event' with the
764−-- current value of the 'Behavior'.
765−attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
766−attach = attachWith (,)
767−
768−-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
769−-- combining it with the current value of the 'Behavior'.
770−attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
771−attachWith f = attachWithMaybe $ \a b -> Just $ f a b
772−
773−-- | Create a new 'Event' by combining each occurrence with the current value of
774−-- the 'Behavior'. The occurrence is discarded if the combining function returns
775−-- Nothing
776−attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
777−attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
778−
779−-- | Create a new 'Event' that occurs on all but the first occurrence of the
780−-- supplied 'Event'.
781−tailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a)
782−tailE e = snd <$> headTailE e
783−
784−-- | Create a tuple of two 'Event's with the first one occurring only the first
785−-- time the supplied 'Event' occurs and the second occurring on all but the first
786−-- occurrence.
787−headTailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a, Event t a)
788−headTailE e = do
789− eHead <- headE e
790− be <- hold never $ fmap (const e) eHead
791− return (eHead, switch be)
792−
793−-- | Take the streak of occurrences starting at the current time for which the
794−-- event returns 'True'.
795−--
796−-- Starting at the current time, fire all the occurrences of the 'Event' for
797−-- which the given predicate returns 'True'. When first 'False' is returned,
798−-- do not fire, and permanently stop firing, even if 'True' values would have
799−-- been encountered later.
800−takeWhileE
801− :: forall t m a
802− . (Reflex t, MonadFix m, MonadHold t m)
803− => (a -> Bool)
804− -> Event t a
805− -> m (Event t a)
806−takeWhileE f = takeWhileJustE $ \v -> guard (f v) $> v
807−
808−-- | Take the streak of occurrences starting at the current time for which the
809−-- event returns 'Just b'.
810−--
811−-- Starting at the current time, fire all the occurrences of the 'Event' for
812−-- which the given predicate returns 'Just b'. When first 'Nothing' is returned,
813−-- do not fire, and permanently stop firing, even if 'Just b' values would have
814−-- been encountered later.
815−takeWhileJustE
816− :: forall t m a b
817− . (Reflex t, MonadFix m, MonadHold t m)
818− => (a -> Maybe b)
819− -> Event t a
820− -> m (Event t b)
821−takeWhileJustE f e = do
822− rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of
823− Nothing -> Left never
824− Just b -> Right b
825− eFirstBad <- headE eBad
826− e' <- switchHold e eFirstBad
827− return eTrue
828−
829−-- | Drop the streak of occurrences starting at the current time for which the
830−-- event returns 'True'.
831−--
832−-- Starting at the current time, do not fire all the occurrences of the 'Event'
833−-- for which the given predicate returns 'True'. When 'False' is first
834−-- returned, do fire, and permanently continue firing, even if 'True' values
835−-- would have been encountered later.
836−dropWhileE
837− :: forall t m a
838− . (Reflex t, MonadFix m, MonadHold t m)
839− => (a -> Bool)
840− -> Event t a
841− -> m (Event t a)
842−dropWhileE f e = snd <$> takeDropWhileJustE (\v -> guard (f v) $> v) e
843−
844−-- | Both take and drop the streak of occurrences starting at the current time
845−-- for which the event returns 'Just b'.
846−--
847−-- For the left event, starting at the current time, fire all the occurrences
848−-- of the 'Event' for which the given function returns 'Just b'. When
849−-- 'Nothing' is returned, do not fire, and permanently stop firing, even if
850−-- 'Just b' values would have been encountered later.
851−--
852−-- For the right event, do not fire until the first occurrence where the given
853−-- function returns 'Nothing', and fire that one and all subsequent
854−-- occurrences. Even if the function would have again returned 'Just b', keep
855−-- on firing.
856−takeDropWhileJustE
857− :: forall t m a b
858− . (Reflex t, MonadFix m, MonadHold t m)
859− => (a -> Maybe b)
860− -> Event t a
861− -> m (Event t b, Event t a)
862−takeDropWhileJustE f e = do
863− rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of
864− Nothing -> Left ()
865− Just b -> Right b
866− eFirstBad <- headE eBad
867− e' <- switchHold e (never <$ eFirstBad)
868− eRest <- switchHoldPromptOnly never (e <$ eFirstBad)
869− return (eGood, eRest)
870−
871−-- | Split the supplied 'Event' into two individual 'Event's occurring at the
872−-- same time with the respective values from the tuple.
873−splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
874−splitE e = (fmap fst e, fmap snd e)
875−
876−-- | Print the supplied 'String' and the value of the 'Event' on each
877−-- occurrence. This should /only/ be used for debugging.
878−--
879−-- Note: As with Debug.Trace.trace, the message will only be printed if the
880−-- 'Event' is actually used.
881−traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
882−traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
883−
884−-- | Print the output of the supplied function on each occurrence of the
885−-- 'Event'. This should /only/ be used for debugging.
886−--
887−-- Note: As with Debug.Trace.trace, the message will only be printed if the
888−-- 'Event' is actually used.
889−traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
890−traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
891−
892−instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
893− (<>) = alignWith (mergeThese (<>))
894− sconcat = fmap sconcat . mergeList . toList
895− stimes n = fmap $ stimes n
896−
897−instance (Semigroup a, Reflex t) => Monoid (Event t a) where
898− mempty = never
899− mappend = (<>)
900− mconcat = fmap sconcat . mergeList
901−
902−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
903−-- list occurs. If multiple occur at the same time they are folded from the left
904−-- with the given function.
905−{-# INLINE mergeWith #-}
906−mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
907−mergeWith = mergeWith' id
908−
909−{-# INLINE mergeWith' #-}
910−mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
911−mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)
912− . mergeInt
913− . IntMap.fromDistinctAscList
914− $ zip [0 :: Int ..] es
915−
916−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
917−-- list occurs. If multiple occur at the same time the value is the value of the
918−-- leftmost event.
919−{-# INLINE leftmost #-}
920−leftmost :: Reflex t => [Event t a] -> Event t a
921−leftmost = mergeWith const
922−
923−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
924−-- list occurs and has a list of the values of all 'Event's occurring at that
925−-- time.
926−mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
927−mergeList [] = never
928−mergeList es = mergeWithFoldCheap' id es
929−
930−unsafeMapIncremental
931− :: (Reflex t, Patch p, Patch p')
932− => (PatchTarget p -> PatchTarget p')
933− -> (p -> p')
934− -> Incremental t p
935− -> Incremental t p'
936−unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
937−
938−-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
939−-- occurs if at least one of them occurs and has a map of values of all 'Event's
940−-- occurring at that time.
941−mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
942−mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
943−
944−-- | Like 'mergeMap' but for 'IntMap'.
945−mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
946−mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap
947−
948−-- | Create a merge whose parents can change over time
949−mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a)
950−mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id)
951−
952−-- | Create a merge whose parents can change over time
953−mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
954−mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)
955−
956−-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
957−mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a)
958−mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id)
959−
960−-- | Split the event into separate events for 'Left' and 'Right' values.
961−fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
962−fanEither e =
963− let justLeft = either Just (const Nothing)
964− justRight = either (const Nothing) Just
965− in (mapMaybe justLeft e, mapMaybe justRight e)
966−
967−-- | Split the event into separate events for 'This' and 'That' values,
968−-- allowing them to fire simultaneously when the input value is 'These'.
969−fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
970−fanThese e =
971− let this (This x) = Just x
972− this (These x _) = Just x
973− this _ = Nothing
974− that (That y) = Just y
975− that (These _ y) = Just y
976− that _ = Nothing
977− in (mapMaybe this e, mapMaybe that e)
978−
979−-- | Split the event into an 'EventSelector' that allows efficient selection of
980−-- the individual 'Event's.
981−fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
982−fanMap = fan . fmap mapToDMap
983−
984−-- | Switches to the new event whenever it receives one. Only the old event is
985−-- considered the moment a new one is switched in; the output event will fire at
986−-- that moment only if the old event does.
987−--
988−-- Because the simultaneous firing case is irrelevant, this function imposes
989−-- laxer "timing requirements" on the overall circuit, avoiding many potential
990−-- cyclic dependency / metastability failures. It's also more performant. Use
991−-- this rather than 'switchHoldPromptly' and 'switchHoldPromptOnly' unless you
992−-- are absolutely sure you need to act on the new event in the coincidental
993−-- case.
994−switchHold :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
995−switchHold ea0 eea = switch <$> hold ea0 eea
996−
997−-- | Switches to the new event whenever it receives one. Whenever a new event is
998−-- provided, if it is firing, its value will be the resulting event's value; if
999−-- it is not firing, but the old one is, the old one's value will be used.
1000−--
1001−-- 'switchHold', by always forwarding the old event the moment it is switched
1002−-- out, avoids many potential cyclic dependency problems / metastability
1003−-- problems. It's also more performant. Use it instead unless you are sure you
1004−-- cannot.
1005−switchHoldPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1006−switchHoldPromptly ea0 eea = do
1007− bea <- hold ea0 eea
1008− let eLag = switch bea
1009− eCoincidences = coincidence eea
1010− return $ leftmost [eCoincidences, eLag]
1011−
1012−-- | switches to a new event whenever it receives one. At the moment of
1013−-- switching, the old event will be ignored if it fires, and the new one will be
1014−-- used if it fires; this is the opposite of 'switch', which will use only the
1015−-- old value.
1016−--
1017−-- 'switchHold', by always forwarding the old event the moment it is switched
1018−-- out, avoids many potential cyclic dependency problems / metastability
1019−-- problems. It's also more performant. Use it instead unless you are sure you
1020−-- cannot.
1021−switchHoldPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1022−switchHoldPromptOnly e0 e' = do
1023− eLag <- switch <$> hold e0 e'
1024− return $ coincidence $ leftmost [e', eLag <$ eLag]
1025−
1026−-- | When the given outer event fires, condense the inner events into the contained patch. Non-firing inner events will be replaced with deletions.
1027−coincidencePatchMap :: (Reflex t, Ord k) => Event t (PatchMap k (Event t v)) -> Event t (PatchMap k v)
1028−coincidencePatchMap e = fmapCheap PatchMap $ coincidence $ ffor e $ \(PatchMap m) -> mergeMap $ ffor m $ \case
1029− Nothing -> fmapCheap (const Nothing) e
1030− Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1031−
1032−-- | See 'coincidencePatchMap'
1033−coincidencePatchIntMap :: Reflex t => Event t (PatchIntMap (Event t v)) -> Event t (PatchIntMap v)
1034−coincidencePatchIntMap e = fmapCheap PatchIntMap $ coincidence $ ffor e $ \(PatchIntMap m) -> mergeIntMap $ ffor m $ \case
1035− Nothing -> fmapCheap (const Nothing) e
1036− Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1037−
1038−-- | See 'coincidencePatchMap'
1039−coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v)
1040−coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of
1041− PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->
1042− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1043− PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->
1044− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }
1045− PatchMapWithMove.From_Insert ev -> leftmost
1046− [ fforCheap ev $ \v ->
1047− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }
1048− , fforCheap e $ \_ ->
1049− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1050− ]
1051−
1052−-- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es
1053−-- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that
1054−-- fires with the patched value.
1055−switchHoldPromptOnlyIncremental
1056− :: forall t m p pt w
1057− . ( Reflex t
1058− , MonadHold t m
1059− , Patch (p (Event t w))
1060− , PatchTarget (p (Event t w)) ~ pt (Event t w)
1061− , Patch (p w)
1062− , PatchTarget (p w) ~ pt w
1063− , Monoid (pt w)
1064− )
1065− => (Incremental t (p (Event t w)) -> Event t (pt w))
1066− -> (Event t (p (Event t w)) -> Event t (p w))
1067− -> pt (Event t w)
1068− -> Event t (p (Event t w))
1069− -> m (Event t (pt w))
1070−switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch e0 e' = do
1071− lag <- mergePatchIncremental <$> holdIncremental e0 e'
1072− pure $ ffor (align lag (coincidencePatch e')) $ \case
1073− This old -> old
1074− That new -> new `applyAlways` mempty
1075− These old new -> new `applyAlways` old
1076−
1077−instance Reflex t => Align (Event t) where
1078− nil = never
1079−#if MIN_VERSION_these(0, 8, 0)
1080−instance Reflex t => Semialign (Event t) where
1081−#endif
1082− align = alignEventWithMaybe Just
1083−
1084−#ifdef MIN_VERSION_semialign
1085−#if MIN_VERSION_semialign(1,1,0)
1086−instance Reflex t => Zip (Event t) where
1087−#endif
1088− zip x y = mapMaybe justThese $ align x y
1089−#endif
1090−
1091−
1092−-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
1093−-- the 'Behavior' is true at the time of occurrence.
1094−gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
1095−gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
1096−
1097−-- | Create a new behavior given a starting behavior and switch to the behavior
1098−-- carried by the event when it fires.
1099−switcher :: (Reflex t, MonadHold t m)
1100− => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
1101−switcher b eb = pull . (sample <=< sample) <$> hold b eb
1102−
1103−instance (Reflex t, IsString a) => IsString (Dynamic t a) where
1104− fromString = pure . fromString
1105−
1106−-- | Combine two 'Dynamic's. The result will change whenever either (or both)
1107−-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
1108−zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
1109−zipDyn = zipDynWith (,)
1110−
1111−-- | Combine two 'Dynamic's with a combining function. The result will change
1112−-- whenever either (or both) input 'Dynamic' changes.
1113−-- More efficient than 'liftA2'.
1114−zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
1115−zipDynWith f da db =
1116− let eab = align (updated da) (updated db)
1117− ec = flip push eab $ \o -> do
1118− (a, b) <- case o of
1119− This a -> do
1120− b <- sample $ current db
1121− return (a, b)
1122− That b -> do
1123− a <- sample $ current da
1124− return (a, b)
1125− These a b -> return (a, b)
1126− return $ Just $ f a b
1127− in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
1128−
1129−instance (Reflex t, Semigroup a) => Semigroup (Dynamic t a) where
1130− (<>) = zipDynWith (<>)
1131− stimes n = fmap $ stimes n
1132−
1133−instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
1134− mconcat = distributeListOverDynWith mconcat
1135− mempty = constDyn mempty
1136− mappend = zipDynWith mappend
1137−
1138−-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1139−-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1140−-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1141−distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
1142−distributeDMapOverDynPure = distributeDMapOverDynPureG coerceDynamic
1143−
1144−-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1145−-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1146−-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1147−distributeDMapOverDynPureG
1148− :: forall t k q v. (Reflex t, GCompare k)
1149− => (forall a. q a -> Dynamic t (v a))
1150− -> DMap k q -> Dynamic t (DMap k v)
1151−distributeDMapOverDynPureG nt dm = case DMap.toList dm of
1152− [] -> constDyn DMap.empty
1153− [k :=> v] -> DMap.singleton k <$> nt v
1154− _ ->
1155− let getInitial = DMap.traverseWithKey (\_ -> sample . current . nt) dm
1156− edmPre = mergeG getCompose $ DMap.map (Compose . updated . nt) dm
1157− result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
1158− olds <- sample $ current result
1159− return $ DMap.unionWithKey (\_ _ new -> new) olds news
1160− in result
1161−
1162−-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
1163−distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
1164−distributeListOverDyn = distributeListOverDynWith id
1165−
1166−-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
1167−distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
1168−distributeListOverDynWith f =
1169− fmap (f . map fromDSum . DMap.toAscList) .
1170− distributeDMapOverDynPure .
1171− DMap.fromDistinctAscList .
1172− zipWith toDSum [0..]
1173− where
1174− toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
1175− toDSum k v = Const2 k :=> v
1176− fromDSum :: DSum (Const2 Int a) Identity -> a
1177− fromDSum (Const2 _ :=> Identity v) = v
1178−
1179−-- | Create a new 'Event' that occurs when the first supplied 'Event' occurs
1180−-- unless the second supplied 'Event' occurs simultaneously.
1181−difference :: Reflex t => Event t a -> Event t b -> Event t a
1182−difference = alignEventWithMaybe $ \case
1183− This a -> Just a
1184− _ -> Nothing
1185−
1186−-- | Zips two values by taking the union of their shapes and combining with the provided function.
1187−-- 'Nothing' values are dropped.
1188−alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c
1189−alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $
1190− merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1191−
1192−-- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that
1193−-- matches the provided key.
1194−filterEventKey
1195− :: forall t m k v a.
1196− ( Reflex t
1197− , MonadFix m
1198− , MonadHold t m
1199− , GEq k
1200− )
1201− => k a
1202− -> Event t (DSum k v)
1203− -> m (Event t (v a))
1204−filterEventKey k kv' = do
1205− let f :: DSum k v -> Maybe (v a)
1206− f (newK :=> newV) = case newK `geq` k of
1207− Just Refl -> Just newV
1208− Nothing -> Nothing
1209− takeWhileJustE f kv'
1210−
1211−-- | "Factor" the input 'DSum' 'Event' to produce an 'Event' which
1212−-- fires when the 'DSum' key changes and contains both the value of the
1213−-- 'DSum' at switchover and an 'Event' of values produced by subsequent
1214−-- firings of the input 'Event' that do not change the 'DSum' key.
1215−factorEvent
1216− :: forall t m k v a.
1217− ( Reflex t
1218− , MonadFix m
1219− , MonadHold t m
1220− , GEq k
1221− )
1222− => k a
1223− -> Event t (DSum k v)
1224− -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v))))
1225−factorEvent k0 kv' = do
1226− key :: Behavior t (Some k) <- hold (Some k0) $ fmapCheap (\(k :=> _) -> Some k) kv'
1227− let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case
1228− Some oldKey -> case newKey `geq` oldKey of
1229− Just Refl -> return Nothing
1230− Nothing -> do
1231− newInner <- filterEventKey newKey kv'
1232− return $ Just $ newKey :=> Pair newVal (Compose newInner)
1233− eInitial <- filterEventKey k0 kv'
1234− return (eInitial, update)
1235−
1236−--------------------------------------------------------------------------------
1237−-- Accumulator
1238−--------------------------------------------------------------------------------
1239−
1240−-- | An 'Accumulator' type can be built by accumulating occurrences of an
1241−-- 'Event'.
1242−#if __GLASGOW_HASKELL__ < 802
1243−{-# WARNING accum "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1244−{-# WARNING accumM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1245−{-# WARNING accumMaybe "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1246−{-# WARNING accumMaybeM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1247−#endif
1248−class Reflex t => Accumulator t f | f -> t where
1249− accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
1250− accum f = accumMaybe $ \v o -> Just $ f v o
1251− accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
1252− accumM f = accumMaybeM $ \v o -> Just <$> f v o
1253− accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
1254− accumMaybe f = accumMaybeM $ \v o -> return $ f v o
1255− accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
1256− mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
1257− mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
1258− mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
1259− mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
1260− mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1261− mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
1262− mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1263−
1264−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1265−-- with the provided function. See 'foldDyn'.
1266−accumDyn
1267− :: (Reflex t, MonadHold t m, MonadFix m)
1268− => (a -> b -> a)
1269− -> a
1270− -> Event t b
1271− -> m (Dynamic t a)
1272−accumDyn f = accumMaybeDyn $ \v o -> Just $ f v o
1273−
1274−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1275−-- with the provided 'PushM' action.
1276−accumMDyn
1277− :: (Reflex t, MonadHold t m, MonadFix m)
1278− => (a -> b -> PushM t a)
1279− -> a
1280− -> Event t b
1281− -> m (Dynamic t a)
1282−accumMDyn f = accumMaybeMDyn $ \v o -> Just <$> f v o
1283−
1284−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1285−-- with the provided function, discarding 'Nothing' results.
1286−accumMaybeDyn
1287− :: (Reflex t, MonadHold t m, MonadFix m)
1288− => (a -> b -> Maybe a)
1289− -> a
1290− -> Event t b
1291− -> m (Dynamic t a)
1292−accumMaybeDyn f = accumMaybeMDyn $ \v o -> return $ f v o
1293−
1294−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1295−-- with the provided 'PushM' action, discarding 'Nothing' results.
1296−accumMaybeMDyn
1297− :: (Reflex t, MonadHold t m, MonadFix m)
1298− => (a -> b -> PushM t (Maybe a))
1299− -> a
1300− -> Event t b
1301− -> m (Dynamic t a)
1302−accumMaybeMDyn f z e = do
1303− rec let e' = flip push e $ \o -> do
1304− v <- sample $ current d'
1305− f v o
1306− d' <- holdDyn z e'
1307− return d'
1308−
1309−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1310−-- with a function that both accumulates and produces a value to fire
1311−-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1312−mapAccumDyn
1313− :: (Reflex t, MonadHold t m, MonadFix m)
1314− => (a -> b -> (a, c))
1315− -> a
1316− -> Event t b
1317− -> m (Dynamic t a, Event t c)
1318−mapAccumDyn f = mapAccumMaybeDyn $ \v o -> bimap Just Just $ f v o
1319−
1320−-- | Similar to 'mapAccumDyn' except that the combining function is a
1321−-- 'PushM' action.
1322−mapAccumMDyn
1323− :: (Reflex t, MonadHold t m, MonadFix m)
1324− => (a -> b -> PushM t (a, c))
1325− -> a
1326− -> Event t b
1327− -> m (Dynamic t a, Event t c)
1328−mapAccumMDyn f = mapAccumMaybeMDyn $ \v o -> bimap Just Just <$> f v o
1329−
1330−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event' with
1331−-- a function that both optionally accumulates and optionally produces
1332−-- a value to fire as a separate output 'Event'.
1333−-- Note that because 'Nothing's are discarded in both cases, the output
1334−-- 'Event' may fire even though the output 'Dynamic' has not changed, and
1335−-- the output 'Dynamic' may update even when the output 'Event' is not firing.
1336−mapAccumMaybeDyn
1337− :: (Reflex t, MonadHold t m, MonadFix m)
1338− => (a -> b -> (Maybe a, Maybe c))
1339− -> a
1340− -> Event t b
1341− -> m (Dynamic t a, Event t c)
1342−mapAccumMaybeDyn f = mapAccumMaybeMDyn $ \v o -> return $ f v o
1343−
1344−-- | Like 'mapAccumMaybeDyn' except that the combining function is a
1345−-- 'PushM' action.
1346−mapAccumMaybeMDyn
1347− :: (Reflex t, MonadHold t m, MonadFix m)
1348− => (a -> b -> PushM t (Maybe a, Maybe c))
1349− -> a
1350− -> Event t b
1351− -> m (Dynamic t a, Event t c)
1352−mapAccumMaybeMDyn f z e = do
1353− rec let e' = flip push e $ \o -> do
1354− v <- sample $ current d'
1355− result <- f v o
1356− return $ case result of
1357− (Nothing, Nothing) -> Nothing
1358− _ -> Just result
1359− d' <- holdDyn z $ mapMaybe fst e'
1360− return (d', mapMaybe snd e')
1361−
1362−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1363−-- with the provided function.
1364−{-# INLINE accumB #-}
1365−accumB
1366− :: (Reflex t, MonadHold t m, MonadFix m)
1367− => (a -> b -> a)
1368− -> a
1369− -> Event t b
1370− -> m (Behavior t a)
1371−accumB f = accumMaybeB $ \v o -> Just $ f v o
1372−
1373−-- | Like 'accumB' except that the combining function is a 'PushM' action.
1374−{-# INLINE accumMB #-}
1375−accumMB
1376− :: (Reflex t, MonadHold t m, MonadFix m)
1377− => (a -> b -> PushM t a)
1378− -> a
1379− -> Event t b
1380− -> m (Behavior t a)
1381−accumMB f = accumMaybeMB $ \v o -> Just <$> f v o
1382−
1383−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1384−-- with the provided function, discarding 'Nothing' results.
1385−{-# INLINE accumMaybeB #-}
1386−accumMaybeB
1387− :: (Reflex t, MonadHold t m, MonadFix m)
1388− => (a -> b -> Maybe a)
1389− -> a
1390− -> Event t b
1391− -> m (Behavior t a)
1392−accumMaybeB f = accumMaybeMB $ \v o -> return $ f v o
1393−
1394−-- | Like 'accumMaybeB' except that the combining function is a 'PushM' action.
1395−{-# INLINE accumMaybeMB #-}
1396−accumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (Behavior t a)
1397−accumMaybeMB f z e = do
1398− rec let e' = flip push e $ \o -> do
1399− v <- sample d'
1400− f v o
1401− d' <- hold z e'
1402− return d'
1403−
1404−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1405−-- with a function that both accumulates and produces a value to fire
1406−-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1407−{-# INLINE mapAccumB #-}
1408−mapAccumB
1409− :: (Reflex t, MonadHold t m, MonadFix m)
1410− => (a -> b -> (a, c))
1411− -> a
1412− -> Event t b
1413− -> m (Behavior t a, Event t c)
1414−mapAccumB f = mapAccumMaybeB $ \v o -> bimap Just Just $ f v o
1415−
1416−-- | Like 'mapAccumB' except that the combining function is a 'PushM' action.
1417−{-# INLINE mapAccumMB #-}
1418−mapAccumMB
1419− :: (Reflex t, MonadHold t m, MonadFix m)
1420− => (a -> b -> PushM t (a, c))
1421− -> a
1422− -> Event t b
1423− -> m (Behavior t a, Event t c)
1424−mapAccumMB f = mapAccumMaybeMB $ \v o -> bimap Just Just <$> f v o
1425−
1426−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event' with
1427−-- a function that both optionally accumulates and optionally produces
1428−-- a value to fire as a separate output 'Event'. 'Nothing's are discarded.
1429−{-# INLINE mapAccumMaybeB #-}
1430−mapAccumMaybeB
1431− :: (Reflex t, MonadHold t m, MonadFix m)
1432− => (a -> b -> (Maybe a, Maybe c))
1433− -> a
1434− -> Event t b
1435− -> m (Behavior t a, Event t c)
1436−mapAccumMaybeB f = mapAccumMaybeMB $ \v o -> return $ f v o
1437−
1438−-- | Like 'mapAccumMaybeB' except that the combining function is a 'PushM' action.
1439−{-# INLINE mapAccumMaybeMB #-}
1440−mapAccumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (Behavior t a, Event t c)
1441−mapAccumMaybeMB f z e = do
1442− rec let e' = flip push e $ \o -> do
1443− v <- sample d'
1444− result <- f v o
1445− return $ case result of
1446− (Nothing, Nothing) -> Nothing
1447− _ -> Just result
1448− d' <- hold z $ mapMaybe fst e'
1449− return (d', mapMaybe snd e')
1450−
1451−-- | Accumulate occurrences of an 'Event', producing an output occurrence each
1452−-- time. Discard the underlying 'Accumulator'.
1453−{-# INLINE mapAccum_ #-}
1454−mapAccum_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (Event t c)
1455−mapAccum_ f z e = do
1456− (_, result) <- mapAccumB f z e
1457− return result
1458−
1459−-- | Accumulate occurrences of an 'Event', possibly producing an output
1460−-- occurrence each time. Discard the underlying 'Accumulator'.
1461−{-# INLINE mapAccumMaybe_ #-}
1462−mapAccumMaybe_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (Event t c)
1463−mapAccumMaybe_ f z e = do
1464− (_, result) <- mapAccumMaybeB f z e
1465− return result
1466−
1467−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
1468−-- an output occurrence each time. Discard the underlying 'Accumulator'.
1469−{-# INLINE mapAccumM_ #-}
1470−mapAccumM_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (Event t c)
1471−mapAccumM_ f z e = do
1472− (_, result) <- mapAccumMB f z e
1473− return result
1474−
1475−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
1476−-- producing an output occurrence each time. Discard the underlying
1477−-- 'Accumulator'.
1478−{-# INLINE mapAccumMaybeM_ #-}
1479−mapAccumMaybeM_ :: forall t m a b c. (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (Event t c)
1480−mapAccumMaybeM_ f z e = do
1481− (_, result) <- mapAccumMaybeMB f z e
1482− return result
1483−
1484−instance Reflex t => Accumulator t (Dynamic t) where
1485− accumMaybeM = accumMaybeMDyn
1486− mapAccumMaybeM = mapAccumMaybeMDyn
1487−
1488−instance Reflex t => Accumulator t (Behavior t) where
1489− accumMaybeM = accumMaybeMB
1490− mapAccumMaybeM = mapAccumMaybeMB
1491−
1492−instance Reflex t => Accumulator t (Event t) where
1493− accumMaybeM f z e = updated <$> accumMaybeM f z e
1494− mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
1495−
1496−-- | Create a new 'Event' by combining each occurrence with the next value of the
1497−-- list using the supplied function. If the list runs out of items, all
1498−-- subsequent 'Event' occurrences will be ignored.
1499−zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
1500−zipListWithEvent f l e = do
1501− let f' a b = case a of
1502− h:t -> (Just t, Just $ f h b)
1503− _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
1504− mapAccumMaybe_ f' l e
1505−
1506−-- | Assign a number to each occurrence of the given 'Event', starting from 0
1507−{-# INLINE numberOccurrences #-}
1508−numberOccurrences :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Event t (b, a))
1509−numberOccurrences = numberOccurrencesFrom 0
1510−
1511−-- | Assign a number to each occurrence of the given 'Event'
1512−{-# INLINE numberOccurrencesFrom #-}
1513−numberOccurrencesFrom :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t (b, a))
1514−numberOccurrencesFrom = mapAccum_ (\n a -> let !next = n + 1 in (next, (n, a)))
1515−
1516−-- | Assign a number to each occurrence of the given 'Event'; discard the occurrences' values
1517−{-# INLINE numberOccurrencesFrom_ #-}
1518−numberOccurrencesFrom_ :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t b)
1519−numberOccurrencesFrom_ = mapAccum_ (\n _ -> let !next = n + 1 in (next, n))
1520−
1521−-- | This is used to sample the value of a 'Behavior' using an 'Event'.
1522−--
1523−-- The '<@>' operator is intended to be used in conjunction with
1524−-- the 'Applicative' instance for 'Behavior'.
1525−--
1526−-- This is useful when we want to combine the values of one 'Event' and
1527−-- the value of several 'Behavior's at the time the 'Event' is firing.
1528−--
1529−-- If we have:
1530−--
1531−-- > f :: a -> b -> c -> d
1532−-- > b1 :: Behavior t a
1533−-- > b2 :: Behavior t b
1534−-- > e :: Event t c
1535−--
1536−-- then we can do:
1537−--
1538−-- > f <$> b1 <*> b2 <@> e :: Event t d
1539−--
1540−-- in order to apply the function 'f' to the relevant values.
1541−--
1542−-- The alternative would be something like:
1543−--
1544−-- > attachWith (\(x1, x2) y -> f x1 x2 y) ((,) <$> b1 <*> b2) e :: Event t d
1545−--
1546−-- or a variation involing a custom data type to hold the combination of
1547−-- 'Behavior's even when that combination might only ever be used by 'f'.
1548−--
1549−-- A more suggestive example might be:
1550−--
1551−-- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)
1552−--
1553−(<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b
1554−(<@>) b = push $ \x -> do
1555− f <- sample b
1556− return . Just . f $ x
1557−infixl 4 <@>
1558−
1559−-- | An version of '<@>' that does not use the value of the 'Event'.
1560−--
1561−-- Alternatively, it is 'tag' in operator form.
1562−--
1563−-- This is useful when we want to combine the values of several
1564−-- 'Behavior's at particular points in time using an 'Applicative'
1565−-- style syntax.
1566−--
1567−-- If we have:
1568−--
1569−-- > g :: a -> b -> d
1570−-- > b1 :: Behavior t a
1571−-- > b2 :: Behavior t b
1572−-- > e :: Event t c
1573−--
1574−-- where 'e' is firing at the points in time of interest.
1575−--
1576−-- Then we can use '<@':
1577−--
1578−-- > g <$> b1 <*> b2 <@ e :: Event t d
1579−--
1580−-- to combine the values of 'b1' and 'b2' at each of those points of time,
1581−-- with the function 'g' being used to combine the values.
1582−--
1583−-- This is the same as '<@>' except that the 'Event' is being used only
1584−-- to act as a trigger.
1585−(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b
1586−(<@) = tag
1587−infixl 4 <@
1588−
1589−------------------
1590−-- Cheap Functions
1591−------------------
1592−
1593−-- | A "cheap" version of 'pushAlways'. See the performance note on 'pushCheap'.
1594−{-# INLINE pushAlwaysCheap #-}
1595−pushAlwaysCheap :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
1596−pushAlwaysCheap f = pushCheap (fmap Just . f)
1597−
1598−-- | A "cheap" version of 'mapMaybe'. See the performance note on 'pushCheap'.
1599−{-# INLINE mapMaybeCheap #-}
1600−mapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1601−mapMaybeCheap f = pushCheap $ return . f
1602−
1603−-- | An alias for 'mapMaybeCheap'
1604−{-# INLINE fmapMaybeCheap #-}
1605−fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1606−fmapMaybeCheap = mapMaybeCheap
1607−
1608−
1609−-- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'.
1610−{-# INLINE fforMaybeCheap #-}
1611−fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b
1612−fforMaybeCheap = flip mapMaybeCheap
1613−
1614−-- | A "cheap" version of 'ffor'. See the performance note on 'pushCheap'.
1615−{-# INLINE fforCheap #-}
1616−fforCheap :: Reflex t => Event t a -> (a -> b) -> Event t b
1617−fforCheap = flip fmapCheap
1618−
1619−-- | A "cheap" version of 'fmap'. See the performance note on 'pushCheap'.
1620−{-# INLINE fmapCheap #-}
1621−fmapCheap :: Reflex t => (a -> b) -> Event t a -> Event t b
1622−fmapCheap f = pushCheap $ return . Just . f
1623−
1624−-- | A "cheap" version of 'tag'. See the performance note on 'pushCheap'.
1625−{-# INLINE tagCheap #-}
1626−tagCheap :: Reflex t => Behavior t b -> Event t a -> Event t b
1627−tagCheap b = pushAlwaysCheap $ \_ -> sample b
1628−
1629−-- | Merge a collection of events; the resulting 'Event' will only occur if at
1630−-- least one input event is occurring, and will contain all of the input keys
1631−-- that are occurring simultaneously
1632−merge :: (Reflex t, GCompare k) => DMap k (Event t) -> Event t (DMap k Identity)
1633−merge = mergeG coerceEvent
1634−{-# INLINE merge #-}
1635−
1636−-- | Create a merge whose parents can change over time
1637−mergeIncremental :: (Reflex t, GCompare k)
1638− => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
1639−mergeIncremental = mergeIncrementalG coerceEvent
1640−
1641−-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
1642−mergeIncrementalWithMove :: (Reflex t, GCompare k)
1643− => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity)
1644−mergeIncrementalWithMove = mergeIncrementalWithMoveG coerceEvent
1645−
1646−-- | A "cheap" version of 'mergeWithCheap'. See the performance note on 'pushCheap'.
1647−{-# INLINE mergeWithCheap #-}
1648−mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
1649−mergeWithCheap = mergeWithCheap' id
1650−
1651−-- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'.
1652−{-# INLINE mergeWithCheap' #-}
1653−mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
1654−mergeWithCheap' f g = mergeWithFoldCheap' $ foldl1 g . fmap f
1655−
1656−-- | A "cheap" version of 'mergeWithFoldCheap''. See the performance note on 'pushCheap'.
1657−{-# INLINE mergeWithFoldCheap' #-}
1658−mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b
1659−mergeWithFoldCheap' f es =
1660− fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)
1661− . mergeInt
1662− . IntMap.fromDistinctAscList
1663− $ zip [0 :: Int ..] es
1664−
1665−--------------------------------------------------------------------------------
1666−-- Deprecated functions
1667−--------------------------------------------------------------------------------
1668−
1669−{-# DEPRECATED switchPromptly "Use 'switchHoldPromptly' instead. The 'switchHold*' naming convention was chosen because those functions are more closely related to each other than they are to 'switch'. " #-}
1670−-- | See 'switchHoldPromptly'
1671−switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1672−switchPromptly = switchHoldPromptly
1673−{-# DEPRECATED switchPromptOnly "Use 'switchHoldPromptOnly' instead. The 'switchHold*' naming convention was chosen because those functions are more closely related to each other than they are to 'switch'. " #-}
1674−-- | See 'switchHoldPromptOnly'
1675−switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1676−switchPromptOnly = switchHoldPromptOnly
src/Reflex/Collection.hsdeleted−225
@@ -1,225 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE LambdaCase #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE RankNTypes #-}
6−{-# LANGUAGE RecursiveDo #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−#ifdef USE_REFLEX_OPTIMIZER
11−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12−#endif
13−-- |
14−-- Module:
15−-- Reflex.Collection
16−module Reflex.Collection
17− (
18− -- * Widgets on Collections
19− listHoldWithKey
20− , listWithKey
21− , listWithKeyShallowDiff
22− , listViewWithKey
23− , selectViewListWithKey
24− , selectViewListWithKey_
25− -- * List Utils
26− , list
27− , simpleList
28− ) where
29−
30−#ifdef MIN_VERSION_semialign
31−import Prelude hiding (zip, zipWith)
32−#if MIN_VERSION_semialign(1,1,0)
33−import Data.Zip (Zip (..))
34−#endif
35−#endif
36−
37−import Control.Monad.Identity
38−import Data.Align
39−import Data.Functor.Misc
40−import Data.Map (Map)
41−import qualified Data.Map as Map
42−import Data.Map.Misc
43−import Data.These
44−
45−import Reflex.Class
46−import Reflex.Adjustable.Class
47−import Reflex.Dynamic
48−import Reflex.PostBuild.Class
49−
50−-- | Create a set of widgets based on the provided 'Map'. When the
51−-- input 'Event' fires, remove widgets for keys with the value 'Nothing'
52−-- and add/replace widgets for keys with 'Just' values.
53−listHoldWithKey
54− :: forall t m k v a
55− . (Ord k, Adjustable t m, MonadHold t m)
56− => Map k v
57− -> Event t (Map k (Maybe v))
58− -> (k -> v -> m a)
59− -> m (Dynamic t (Map k a))
60−listHoldWithKey m0 m' f = do
61− let dm0 = mapWithFunctorToDMap $ Map.mapWithKey f m0
62− dm' = fmap
63− (PatchDMap . mapWithFunctorToDMap . Map.mapWithKey
64− (\k v -> ComposeMaybe $ fmap (f k) v)
65− )
66− m'
67− (a0, a') <- sequenceDMapWithAdjust dm0 dm'
68−
69− --TODO: Move the dmapToMap to the righthand side so it doesn't get
70− --fully redone every time
71− fmap dmapToMap . incrementalToDynamic <$> holdIncremental a0 a'
72−
73−--TODO: Something better than Dynamic t (Map k v) - we want something
74−--where the Events carry diffs, not the whole value
75−listWithKey
76− :: forall t k v m a
77− . (Ord k, Adjustable t m, PostBuild t m, MonadFix m, MonadHold t m)
78− => Dynamic t (Map k v)
79− -> (k -> Dynamic t v -> m a)
80− -> m (Dynamic t (Map k a))
81−listWithKey vals mkChild = do
82− postBuild <- getPostBuild
83− let childValChangedSelector = fanMap $ updated vals
84−
85− -- We keep track of changes to children values in the mkChild
86− -- function we pass to listHoldWithKey The other changes we need
87− -- to keep track of are child insertions and
88− -- deletions. diffOnlyKeyChanges keeps track of insertions and
89− -- deletions but ignores value changes, since they're already
90− -- accounted for.
91− diffOnlyKeyChanges olds news =
92− flip Map.mapMaybe (align olds news) $ \case
93− This _ -> Just Nothing
94− These _ _ -> Nothing
95− That new -> Just $ Just new
96− rec sentVals :: Dynamic t (Map k v) <- foldDyn applyMap Map.empty changeVals
97− let changeVals :: Event t (Map k (Maybe v))
98− changeVals =
99− attachWith diffOnlyKeyChanges (current sentVals) $ leftmost
100− [ updated vals
101−
102− -- TODO: This should probably be added to the
103− -- attachWith, not to the updated; if we were using
104− -- diffMap instead of diffMapNoEq, I think it might not
105− -- work
106− , tag (current vals) postBuild
107− ]
108− listHoldWithKey Map.empty changeVals $ \k v ->
109− mkChild k =<< holdDyn v (select childValChangedSelector $ Const2 k)
110−
111−-- | Display the given map of items (in key order) using the builder
112−-- function provided, and update it with the given event. 'Nothing'
113−-- update entries will delete the corresponding children, and 'Just'
114−-- entries will create them if they do not exist or send an update
115−-- event to them if they do.
116−listWithKeyShallowDiff
117− :: (Ord k, Adjustable t m, MonadFix m, MonadHold t m)
118− => Map k v
119− -> Event t (Map k (Maybe v))
120− -> (k -> v -> Event t v -> m a)
121− -> m (Dynamic t (Map k a))
122−listWithKeyShallowDiff initialVals valsChanged mkChild = do
123− let childValChangedSelector = fanMap $ fmap (Map.mapMaybe id) valsChanged
124− sentVals <- foldDyn applyMap (void initialVals) $ fmap (fmap void) valsChanged
125− let relevantPatch patch _ = case patch of
126−
127− -- Even if we let a Nothing through when the element doesn't
128− -- already exist, this doesn't cause a problem because it is
129− -- ignored
130− Nothing -> Just Nothing
131−
132− -- We don't want to let spurious re-creations of items through
133− Just _ -> Nothing
134− listHoldWithKey
135− initialVals
136− (attachWith (flip (Map.differenceWith relevantPatch))
137− (current sentVals)
138− valsChanged
139− )
140− $ \k v -> mkChild k v $ select childValChangedSelector $ Const2 k
141−
142−--TODO: Something better than Dynamic t (Map k v) - we want something
143−--where the Events carry diffs, not the whole value
144−-- | Create a dynamically-changing set of Event-valued widgets. This
145−-- is like 'listWithKey', specialized for widgets returning @/Event t a/@.
146−-- 'listWithKey' would return @/Dynamic t (Map k (Event t a))/@ in
147−-- this scenario, but 'listViewWithKey' flattens this to
148−-- @/Event t (Map k a)/@ via 'switch'.
149−listViewWithKey
150− :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
151− => Dynamic t (Map k v)
152− -> (k -> Dynamic t v -> m (Event t a))
153− -> m (Event t (Map k a))
154−listViewWithKey vals mkChild =
155− switch . fmap mergeMap <$> listViewWithKey' vals mkChild
156−
157−listViewWithKey'
158− :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
159− => Dynamic t (Map k v)
160− -> (k -> Dynamic t v -> m a)
161− -> m (Behavior t (Map k a))
162−listViewWithKey' vals mkChild = current <$> listWithKey vals mkChild
163−
164−-- | Create a dynamically-changing set of widgets, one of which is
165−-- selected at any time.
166−selectViewListWithKey
167− :: forall t m k v a
168− . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
169− => Dynamic t k
170− -- ^ Current selection key
171− -> Dynamic t (Map k v)
172− -- ^ Dynamic key/value map
173− -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
174− -- ^ Function to create a widget for a given key from Dynamic value
175− -- and Dynamic Bool indicating if this widget is currently selected
176− -> m (Event t (k, a))
177− -- ^ Event that fires when any child's return Event fires. Contains
178− -- key of an arbitrary firing widget.
179−selectViewListWithKey selection vals mkChild = do
180− -- For good performance, this value must be shared across all children
181− let selectionDemux = demux selection
182− selectChild <- listWithKey vals $ \k v -> do
183− let selected = demuxed selectionDemux k
184− selectSelf <- mkChild k v selected
185− return $ fmap ((,) k) selectSelf
186− return $ switchPromptlyDyn $ leftmost . Map.elems <$> selectChild
187−
188−-- | Like 'selectViewListWithKey' but discards the value of the list
189−-- item widget's output 'Event'.
190−selectViewListWithKey_
191− :: forall t m k v a
192− . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
193− => Dynamic t k
194− -- ^ Current selection key
195− -> Dynamic t (Map k v)
196− -- ^ Dynamic key/value map
197− -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
198− -- ^ Function to create a widget for a given key from Dynamic value
199− -- and Dynamic Bool indicating if this widget is currently selected
200− -> m (Event t k)
201− -- ^ Event that fires when any child's return Event fires. Contains
202− -- key of an arbitrary firing widget.
203−selectViewListWithKey_ selection vals mkChild =
204− fmap fst <$> selectViewListWithKey selection vals mkChild
205−
206−-- | Create a dynamically-changing set of widgets from a Dynamic
207−-- key/value map. Unlike the 'withKey' variants, the child widgets
208−-- are insensitive to which key they're associated with.
209−list
210− :: (Ord k, Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
211− => Dynamic t (Map k v)
212− -> (Dynamic t v -> m a)
213− -> m (Dynamic t (Map k a))
214−list dm mkChild = listWithKey dm (\_ dv -> mkChild dv)
215−
216−-- | Create a dynamically-changing set of widgets from a Dynamic list.
217−simpleList
218− :: (Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
219− => Dynamic t [v]
220− -> (Dynamic t v -> m a)
221− -> m (Dynamic t [a])
222−simpleList xs mkChild =
223− fmap (fmap (map snd . Map.toList)) $ flip list mkChild $ fmap
224− (Map.fromList . zip [(1 :: Int) ..])
225− xs
src/Reflex/Dynamic.hsdeleted−530
@@ -1,530 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoMonomorphismRestriction #-}
9−{-# LANGUAGE PolyKinds #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE RecursiveDo #-}
12−{-# LANGUAGE ScopedTypeVariables #-}
13−{-# LANGUAGE StandaloneDeriving #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE TypeOperators #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−#ifdef USE_REFLEX_OPTIMIZER
18−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
19−#endif
20−-- |
21−-- Module:
22−-- Reflex.Dynamic
23−-- Description:
24−-- This module contains various functions for working with 'Dynamic' values.
25−-- 'Dynamic' and its primitives have been moved to the 'Reflex' class.
26−module Reflex.Dynamic
27− ( -- * Basics
28− Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update
29− , current
30− , updated
31− , holdDyn
32− , mapDynM
33− , forDynM
34− , constDyn
35− , count
36− , toggle
37− , switchDyn
38− , switchPromptlyDyn
39− , tagPromptlyDyn
40− , attachPromptlyDyn
41− , attachPromptlyDynWith
42− , attachPromptlyDynWithMaybe
43− , maybeDyn
44− , eitherDyn
45− , factorDyn
46− , scanDyn
47− , scanDynMaybe
48− , holdUniqDyn
49− , holdUniqDynBy
50− , improvingMaybe
51− , foldDyn
52− , foldDynM
53− , foldDynMaybe
54− , foldDynMaybeM
55− , joinDynThroughMap
56− , traceDyn
57− , traceDynWith
58− , splitDynPure
59− , distributeMapOverDynPure
60− , distributeDMapOverDynPure
61− , distributeListOverDynPure
62− , Demux
63− , demux
64− , demuxed
65− -- * Miscellaneous
66− -- Things that probably aren't very useful:
67− , HList (..)
68− , FHList (..)
69− , collectDynPure
70− , RebuildSortedHList (..)
71− , IsHList (..)
72− , AllAreFunctors (..)
73− , HListPtr (..)
74− , distributeFHListOverDynPure
75− -- * Unsafe
76− , unsafeDynamic
77− ) where
78−
79−import Data.Functor.Compose
80−import Data.Functor.Misc
81−import Reflex.Class
82−
83−import Control.Monad
84−import Control.Monad.Fix
85−import Control.Monad.Identity
86−import Data.Align
87−import Data.Dependent.Map (DMap)
88−import qualified Data.Dependent.Map as DMap
89−import Data.Dependent.Sum (DSum (..))
90−import Data.GADT.Compare ((:~:) (..), GCompare (..), GEq (..), GOrdering (..))
91−import Data.Map (Map)
92−import Data.Maybe
93−import Data.Monoid ((<>))
94−import Data.These
95−
96−import Debug.Trace
97−
98−-- | Map a sampling function over a 'Dynamic'.
99−mapDynM :: forall t m a b. (Reflex t, MonadHold t m) => (forall m'. MonadSample t m' => a -> m' b) -> Dynamic t a -> m (Dynamic t b)
100−mapDynM f d = buildDynamic (f =<< sample (current d)) $ pushAlways f (updated d)
101−
102−-- | Flipped version of 'mapDynM'
103−forDynM :: forall t m a b. (Reflex t, MonadHold t m) => Dynamic t a -> (forall m'. MonadSample t m' => a -> m' b) -> m (Dynamic t b)
104−forDynM d f = mapDynM f d
105−
106−-- | Create a new 'Dynamic' that only signals changes if the values actually
107−-- changed.
108−holdUniqDyn :: (Reflex t, MonadHold t m, MonadFix m, Eq a) => Dynamic t a -> m (Dynamic t a)
109−holdUniqDyn = holdUniqDynBy (==)
110−
111−-- | Create a new 'Dynamic' that changes only when the underlying 'Dynamic'
112−-- changes and the given function returns 'False' when given both the old and
113−-- the new values.
114−holdUniqDynBy :: (Reflex t, MonadHold t m, MonadFix m) => (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
115−holdUniqDynBy eq = scanDynMaybe id (\new old -> if new `eq` old then Nothing else Just new)
116−
117−-- | @/Dynamic Maybe/@ that can only update from @/Nothing/@ to @/Just/@ or @/Just/@ to @/Just/@ (i.e., cannot revert to @/Nothing/@)
118−improvingMaybe :: (Reflex t, MonadHold t m, MonadFix m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe a))
119−improvingMaybe = scanDynMaybe id (\new _ -> if isJust new then Just new else Nothing)
120−
121−-- | Create a 'Dynamic' that accumulates values from another 'Dynamic'. This
122−-- function does not force its input 'Dynamic' until the output 'Dynamic' is
123−-- forced.
124−scanDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> b) -> Dynamic t a -> m (Dynamic t b)
125−scanDyn z f = scanDynMaybe z (\a b -> Just $ f a b)
126−
127−-- | Like 'scanDyn', but the the accumulator function may decline to update the
128−-- result 'Dynamic''s value.
129−scanDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> Maybe b) -> Dynamic t a -> m (Dynamic t b)
130−scanDynMaybe z f d = do
131− rec d' <- buildDynamic (z <$> sample (current d)) $ flip push (updated d) $ \a -> do
132− b <- sample $ current d'
133− return $ f a b
134− return d'
135−
136−-- | Create a 'Dynamic' using the initial value and change it each time the
137−-- 'Event' occurs using a folding function on the previous value and the value
138−-- of the 'Event'.
139−foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b)
140−foldDyn = accumDyn . flip
141−
142−-- | Like 'foldDyn', but the combining function is a 'PushM' action, so it
143−-- can 'sample' existing 'Behaviors' and 'hold' new ones.
144−foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b)
145−foldDynM = accumMDyn . flip
146−
147−-- | Create a 'Dynamic' using the provided initial value and change it each time
148−-- the provided 'Event' occurs, using a function to combine the old value with
149−-- the 'Event''s value. If the function returns 'Nothing', the value is not
150−-- changed; this is distinct from returning 'Just' the old value, since the
151−-- 'Dynamic''s 'updated' 'Event' will fire in the 'Just' case, and will not fire
152−-- in the 'Nothing' case.
153−foldDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> Maybe b) -> b -> Event t a -> m (Dynamic t b)
154−foldDynMaybe = accumMaybeDyn . flip
155−
156−-- | Like 'foldDynMaybe', but the combining function is a 'PushM' action, so it
157−-- can 'sample' existing 'Behaviors' and 'hold' new ones.
158−foldDynMaybeM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe b)) -> b -> Event t a -> m (Dynamic t b)
159−foldDynMaybeM = accumMaybeMDyn . flip
160−
161−-- | Create a new 'Dynamic' that counts the occurrences of the 'Event'.
162−count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)
163−count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e
164−
165−-- | Create a new 'Dynamic' using the initial value that flips its
166−-- value every time the 'Event' occurs.
167−toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool)
168−toggle = foldDyn (const not)
169−
170−-- | Switches to the new 'Event' whenever it receives one. Only the old event is
171−-- considered the moment a new one is switched in; the output event will fire at
172−-- that moment if only if the old event does.
173−--
174−-- Prefer this to 'switchPromptlyDyn' where possible. The lack of doing double
175−-- work when the outer and (new) inner fires means this imposes fewer "timing
176−-- requirements" and thus is far more easy to use without introducing fresh
177−-- failure cases. 'switchDyn' is also more performant.
178−switchDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
179−switchDyn d = switch (current d)
180−
181−-- | Switches to the new 'Event' whenever it receives one. Switching occurs
182−-- __before__ the inner 'Event' fires - so if the 'Dynamic' changes and both the
183−-- old and new inner Events fire simultaneously, the output will fire with the
184−-- value of the __new__ 'Event'.
185−--
186−-- Prefer 'switchDyn' to this where possible. The timing requirements that
187−-- switching before imposes are likely to bring down your app unless you are
188−-- very careful. 'switchDyn' is also more performant.
189−switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
190−switchPromptlyDyn de =
191− let eLag = switch $ current de
192− eCoincidences = coincidence $ updated de
193− in leftmost [eCoincidences, eLag]
194−
195−-- | Split a 'Dynamic' pair into a pair of 'Dynamic's
196−splitDynPure :: Reflex t => Dynamic t (a, b) -> (Dynamic t a, Dynamic t b)
197−splitDynPure d = (fmap fst d, fmap snd d)
198−
199−-- | Convert a 'Map' with 'Dynamic' elements into a 'Dynamic' of a 'Map' with
200−-- non-'Dynamic' elements.
201−distributeMapOverDynPure :: (Reflex t, Ord k) => Map k (Dynamic t v) -> Dynamic t (Map k v)
202−distributeMapOverDynPure = fmap dmapToMap . distributeDMapOverDynPure . mapWithFunctorToDMap
203−
204−-- | Convert a list with 'Dynamic' elements into a 'Dynamic' of a list with
205−-- non-'Dynamic' elements, preserving the order of the elements.
206−{-# DEPRECATED distributeListOverDynPure "Use 'distributeListOverDyn' instead" #-}
207−distributeListOverDynPure :: Reflex t => [Dynamic t v] -> Dynamic t [v]
208−distributeListOverDynPure = distributeListOverDyn
209−
210−--TODO: Generalize this to functors other than Maps
211−-- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic'
212−-- with the current values of the 'Dynamic's in a map.
213−joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)
214−joinDynThroughMap = (distributeMapOverDynPure =<<)
215−
216−-- | Print the value of the 'Dynamic' when it is first read and on each
217−-- subsequent change that is observed (as 'traceEvent'), prefixed with the
218−-- provided string. This should /only/ be used for debugging.
219−--
220−-- Note: Just like Debug.Trace.trace, the value will only be shown if something
221−-- else in the system is depending on it.
222−traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a
223−traceDyn s = traceDynWith $ \x -> s <> ": " <> show x
224−
225−-- | Print the result of applying the provided function to the value
226−-- of the 'Dynamic' when it is first read and on each subsequent change
227−-- that is observed (as 'traceEvent'). This should /only/ be used for
228−-- debugging.
229−--
230−-- Note: Just like Debug.Trace.trace, the value will only be shown if something
231−-- else in the system is depending on it.
232−traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a
233−traceDynWith f d =
234− let e' = traceEventWith f $ updated d
235− getV0 = do
236− x <- sample $ current d
237− trace (f x) $ return x
238− in unsafeBuildDynamic getV0 e'
239−
240−-- | Replace the value of the 'Event' with the current value of the 'Dynamic'
241−-- each time the 'Event' occurs.
242−--
243−-- Note: @/tagPromptlyDyn d e/@ differs from @/tag (current d) e/@ in the case that @/e/@ is firing
244−-- at the same time that @/d/@ is changing. With @/tagPromptlyDyn d e/@, the __new__ value of @/d/@
245−-- will replace the value of @/e/@, whereas with @/tag (current d) e/@, the __old__ value
246−-- will be used, since the 'Behavior' won't be updated until the end of the frame.
247−-- Additionally, this means that the output 'Event' may not be used to directly change
248−-- the input 'Dynamic', because that would mean its value depends on itself. __When creating__
249−-- __cyclic data flows, generally @/tag (current d) e/@ is preferred.__
250−tagPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
251−tagPromptlyDyn = attachPromptlyDynWith const
252−
253−-- | Attach the current value of the 'Dynamic' to the value of the
254−-- 'Event' each time it occurs.
255−--
256−-- Note: @/attachPromptlyDyn d/@ is not the same as @/attach (current d)/@. See 'tagPromptlyDyn' for details.
257−attachPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
258−attachPromptlyDyn = attachPromptlyDynWith (,)
259−
260−-- | Combine the current value of the 'Dynamic' with the value of the
261−-- 'Event' each time it occurs.
262−--
263−-- Note: @/attachPromptlyDynWith f d/@ is not the same as @/attachWith f (current d)/@. See 'tagPromptlyDyn' for details.
264−attachPromptlyDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
265−attachPromptlyDynWith f = attachPromptlyDynWithMaybe $ \a b -> Just $ f a b
266−
267−-- | Create a new 'Event' by combining the value at each occurrence with the
268−-- current value of the 'Dynamic' value and possibly filtering if the combining
269−-- function returns 'Nothing'.
270−--
271−-- Note: @/attachPromptlyDynWithMaybe f d/@ is not the same as @/attachWithMaybe f (current d)/@. See 'tagPromptlyDyn' for details.
272−attachPromptlyDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
273−attachPromptlyDynWithMaybe f d e =
274− let e' = attach (current d) e
275− in fforMaybe (align e' $ updated d) $ \case
276− This (a, b) -> f a b -- Only the tagging event is firing, so use that
277− These (_, b) a -> f a b -- Both events are firing, so use the newer value
278− That _ -> Nothing -- The tagging event isn't firing, so don't fire
279−
280−-- | Factor a @/Dynamic t (Maybe a)/@ into a @/Dynamic t (Maybe (Dynamic t a))/@,
281−-- such that the outer 'Dynamic' is updated only when the "Maybe"'s constructor
282−-- chages from 'Nothing' to 'Just' or vice-versa. Whenever the constructor
283−-- becomes 'Just', an inner 'Dynamic' will be provided, whose value will track
284−-- the 'a' inside the 'Just'; when the constructor becomes 'Nothing', the
285−-- existing inner 'Dynamic' will become constant, and will not change when the
286−-- outer constructor changes back to 'Nothing'.
287−maybeDyn :: forall t a m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe (Dynamic t a)))
288−maybeDyn = fmap (fmap unpack) . eitherDyn . fmap pack
289− where pack = \case
290− Nothing -> Left ()
291− Just a -> Right a
292− unpack = \case
293− Left _ -> Nothing
294− Right a -> Just a
295−
296−-- | Turns a 'Dynamic t (Either a b)' into a 'Dynamic t (Either (Dynamic t a) (Dynamic t b))' such that
297−-- the outer 'Dynamic' is updated only when the 'Either' constructor changes (e.g., from 'Left' to 'Right').
298−eitherDyn :: forall t a b m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Either a b) -> m (Dynamic t (Either (Dynamic t a) (Dynamic t b)))
299−eitherDyn = fmap (fmap unpack) . factorDyn . fmap eitherToDSum
300− where unpack :: DSum (EitherTag a b) (Compose (Dynamic t) Identity) -> Either (Dynamic t a) (Dynamic t b)
301− unpack = \case
302− LeftTag :=> Compose a -> Left $ coerceDynamic a
303− RightTag :=> Compose b -> Right $ coerceDynamic b
304−
305−-- | Factor a 'Dynamic t DSum' into a 'Dynamic' 'DSum' containing nested 'Dynamic' values.
306−-- The outer 'Dynamic' updates only when the key of the 'DSum' changes, while the update of the inner
307−-- 'Dynamic' represents updates within the current key.
308−factorDyn :: forall t m k v. (Reflex t, MonadHold t m, GEq k)
309− => Dynamic t (DSum k v) -> m (Dynamic t (DSum k (Compose (Dynamic t) v)))
310−factorDyn d = buildDynamic (sample (current d) >>= holdKey) update where
311− update :: Event t (DSum k (Compose (Dynamic t) v))
312− update = flip push (updated d) $ \(newKey :=> newVal) -> do
313− (oldKey :=> _) <- sample (current d)
314− case newKey `geq` oldKey of
315− Just Refl -> return Nothing
316− Nothing -> Just <$> holdKey (newKey :=> newVal)
317−
318− holdKey (k :=> v) = do
319− inner' <- filterEventKey k (updated d)
320− inner <- holdDyn v inner'
321− return $ k :=> Compose inner
322−
323−--------------------------------------------------------------------------------
324−-- Demux
325−--------------------------------------------------------------------------------
326−
327−-- | Represents a time changing value together with an 'EventSelector' that can
328−-- efficiently detect when the underlying 'Dynamic' has a particular value.
329−-- This is useful for representing data like the current selection of a long
330−-- list.
331−--
332−-- Semantically,
333−--
334−-- > demuxed (demux d) k === fmap (== k) d
335−--
336−-- However, when getDemuxed is used multiple times, the complexity is only
337−-- /O(log(n))/, rather than /O(n)/ for fmap.
338−data Demux t k = Demux { demuxValue :: Behavior t k
339− , demuxSelector :: EventSelector t (Const2 k Bool)
340− }
341−
342−-- | Demultiplex an input value to a 'Demux' with many outputs. At any given
343−-- time, whichever output is indicated by the given 'Dynamic' will be 'True'.
344−demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k
345−demux k = Demux (current k)
346− (fan $ attachWith (\k0 k1 -> if k0 == k1
347− then DMap.empty
348− else DMap.fromList [Const2 k0 :=> Identity False,
349− Const2 k1 :=> Identity True])
350− (current k) (updated k))
351−
352−-- | Select a particular output of the 'Demux'; this is equivalent to (but much
353−-- faster than) mapping over the original 'Dynamic' and checking whether it is
354−-- equal to the given key.
355−demuxed :: (Reflex t, Eq k) => Demux t k -> k -> Dynamic t Bool
356−demuxed d k =
357− let e = select (demuxSelector d) (Const2 k)
358− in unsafeBuildDynamic (fmap (==k) $ sample $ demuxValue d) e
359−
360−--------------------------------------------------------------------------------
361−-- collectDyn
362−--------------------------------------------------------------------------------
363−
364−--TODO: This whole section is badly in need of cleanup
365−
366−-- | A heterogeneous list whose type and length are fixed statically. This is
367−-- reproduced from the 'HList' package due to integration issues, and because
368−-- very little other functionality from that library is needed.
369−data HList (l::[*]) where
370− HNil :: HList '[]
371− HCons :: e -> HList l -> HList (e ': l)
372−
373−infixr 2 `HCons`
374−
375−type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
376−type instance HRevApp '[] l = l
377−type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
378−
379−hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
380−hRevApp HNil l = l
381−hRevApp (HCons x l) l' = hRevApp l (HCons x l')
382−
383−hReverse :: HList l -> HList (HRevApp l '[])
384−hReverse l = hRevApp l HNil
385−
386−hBuild :: (HBuild' '[] r) => r
387−hBuild = hBuild' HNil
388−
389−class HBuild' l r where
390− hBuild' :: HList l -> r
391−
392−instance (l' ~ HRevApp l '[])
393− => HBuild' l (HList l') where
394− hBuild' = hReverse
395−
396−instance HBuild' (a ': l) r
397− => HBuild' l (a->r) where
398− hBuild' l x = hBuild' (HCons x l)
399−
400−-- | Like 'HList', but with a functor wrapping each element.
401−data FHList f l where
402− FHNil :: FHList f '[]
403− FHCons :: f e -> FHList f l -> FHList f (e ': l)
404−
405−instance GEq (HListPtr l) where
406− HHeadPtr `geq` HHeadPtr = Just Refl
407− HHeadPtr `geq` HTailPtr _ = Nothing
408− HTailPtr _ `geq` HHeadPtr = Nothing
409− HTailPtr a `geq` HTailPtr b = a `geq` b
410−
411−instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dmapTo*HList will break
412− HHeadPtr `gcompare` HHeadPtr = GEQ
413− HHeadPtr `gcompare` HTailPtr _ = GLT
414− HTailPtr _ `gcompare` HHeadPtr = GGT
415− HTailPtr a `gcompare` HTailPtr b = a `gcompare` b
416−
417−-- | A typed index into a typed heterogeneous list.
418−data HListPtr l a where
419− HHeadPtr :: HListPtr (h ': t) h
420− HTailPtr :: HListPtr t a -> HListPtr (h ': t) a
421−
422−deriving instance Eq (HListPtr l a)
423−deriving instance Ord (HListPtr l a)
424−
425−fhlistToDMap :: forall (f :: * -> *) l. FHList f l -> DMap (HListPtr l) f
426−fhlistToDMap = DMap.fromList . go
427− where go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]
428− go = \case
429− FHNil -> []
430− FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)
431−
432−-- | This class allows 'HList's and 'FHlist's to be built from regular lists;
433−-- they must be contiguous and sorted.
434−class RebuildSortedHList l where
435− rebuildSortedFHList :: [DSum (HListPtr l) f] -> FHList f l
436− rebuildSortedHList :: [DSum (HListPtr l) Identity] -> HList l
437−
438−instance RebuildSortedHList '[] where
439− rebuildSortedFHList l = case l of
440− [] -> FHNil
441− _ : _ -> error "rebuildSortedFHList{'[]}: empty list expected"
442− rebuildSortedHList l = case l of
443− [] -> HNil
444− _ : _ -> error "rebuildSortedHList{'[]}: empty list expected"
445−
446−instance RebuildSortedHList t => RebuildSortedHList (h ': t) where
447− rebuildSortedFHList l = case l of
448− ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
449− _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected"
450− rebuildSortedHList l = case l of
451− ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
452− _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected"
453−
454−dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) Identity -> HList l
455−dmapToHList = rebuildSortedHList . DMap.toList
456−
457−-- | Collect a hetereogeneous list whose elements are all 'Dynamic's into a
458−-- single 'Dynamic' whose value represents the current values of all of the
459−-- input 'Dynamic's.
460−distributeFHListOverDynPure :: (Reflex t, RebuildSortedHList l) => FHList (Dynamic t) l -> Dynamic t (HList l)
461−distributeFHListOverDynPure l = fmap dmapToHList $ distributeDMapOverDynPure $ fhlistToDMap l
462−
463−-- | Indicates that all elements in a type-level list are applications of the
464−-- same functor.
465−class AllAreFunctors (f :: a -> *) (l :: [a]) where
466− type FunctorList f l :: [*]
467− toFHList :: HList (FunctorList f l) -> FHList f l
468− fromFHList :: FHList f l -> HList (FunctorList f l)
469−
470−instance AllAreFunctors f '[] where
471− type FunctorList f '[] = '[]
472− toFHList l = case l of
473− HNil -> FHNil
474−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
475− _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
476−#endif
477− fromFHList FHNil = HNil
478−
479−instance AllAreFunctors f t => AllAreFunctors f (h ': t) where
480− type FunctorList f (h ': t) = f h ': FunctorList f t
481− toFHList l = case l of
482− a `HCons` b -> a `FHCons` toFHList b
483−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
484− _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
485−#endif
486− fromFHList (a `FHCons` b) = a `HCons` fromFHList b
487−
488−-- | Convert a datastructure whose constituent parts are all 'Dynamic's into a
489−-- single 'Dynamic' whose value represents all the current values of the input's
490−-- constituent 'Dynamic's.
491−collectDynPure :: ( RebuildSortedHList (HListElems b)
492− , IsHList a, IsHList b
493− , AllAreFunctors (Dynamic t) (HListElems b)
494− , Reflex t
495− , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
496− ) => a -> Dynamic t b
497−collectDynPure ds = fmap fromHList $ distributeFHListOverDynPure $ toFHList $ toHList ds
498−
499−-- | Poor man's 'Generic's for product types only.
500−class IsHList a where
501− type HListElems a :: [*]
502− toHList :: a -> HList (HListElems a)
503− fromHList :: HList (HListElems a) -> a
504−
505−instance IsHList (a, b) where
506− type HListElems (a, b) = [a, b]
507− toHList (a, b) = hBuild a b
508− fromHList l = case l of
509− a `HCons` b `HCons` HNil -> (a, b)
510−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
511− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
512−#endif
513−
514−instance IsHList (a, b, c, d) where
515− type HListElems (a, b, c, d) = [a, b, c, d]
516− toHList (a, b, c, d) = hBuild a b c d
517− fromHList l = case l of
518− a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d)
519−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
520− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
521−#endif
522−
523−instance IsHList (a, b, c, d, e, f) where
524− type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]
525− toHList (a, b, c, d, e, f) = hBuild a b c d e f
526− fromHList l = case l of
527− a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f)
528−#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
529− _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
530−#endif
src/Reflex/Dynamic/TH.hsdeleted−106
@@ -1,106 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE EmptyDataDecls #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE PatternGuards #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE TemplateHaskell #-}
7−{-# LANGUAGE TypeOperators #-}
8−#ifdef USE_REFLEX_OPTIMIZER
9−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10−#endif
11−-- | Template Haskell helper functions for building complex 'Dynamic' values.
12−module Reflex.Dynamic.TH
13− ( qDynPure
14− , unqDyn
15− , mkDynPure
16− ) where
17−
18−import Reflex.Dynamic
19−
20−import Control.Monad.State
21−import Data.Data
22−import Data.Generics
23−import Data.Monoid ((<>))
24−import qualified Language.Haskell.Exts as Hs
25−import qualified Language.Haskell.Meta.Syntax.Translate as Hs
26−import Language.Haskell.TH
27−import Language.Haskell.TH.Quote
28−import qualified Language.Haskell.TH.Syntax as TH
29−
30−-- | Quote a 'Dynamic' expression. Within the quoted expression, you can use
31−-- @$(unqDyn [| x |])@ to refer to any expression @x@ of type @Dynamic t a@; the
32−-- unquoted result will be of type @a@
33−qDynPure :: Q Exp -> Q Exp
34−qDynPure qe = do
35− e <- qe
36− let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d
37− f d = case eqT of
38− Just (Refl :: d :~: Exp)
39− | AppE (VarE m) eInner <- d
40− , m == 'unqMarker
41− -> do n <- lift $ newName "dynamicQuotedExpressionVariable"
42− modify ((n, eInner):)
43− return $ VarE n
44− _ -> gmapM f d
45− (e', exprsReversed) <- runStateT (gmapM f e) []
46− let exprs = reverse exprsReversed
47− arg = foldr (\a b -> ConE 'FHCons `AppE` snd a `AppE` b) (ConE 'FHNil) exprs
48− param = foldr (\a b -> ConP 'HCons [VarP (fst a), b]) (ConP 'HNil []) exprs
49− [| $(return $ LamE [param] e') <$> distributeFHListOverDynPure $(return arg) |]
50−
51−-- | Antiquote a 'Dynamic' expression. This can /only/ be used inside of a
52−-- 'qDyn' quotation.
53−unqDyn :: Q Exp -> Q Exp
54−unqDyn e = [| unqMarker $e |]
55−
56−-- | This type represents an occurrence of unqDyn before it has been processed
57−-- by qDyn. If you see it in a type error, it probably means that unqDyn has
58−-- been used outside of a qDyn context.
59−data UnqDyn
60−
61−-- unqMarker must not be exported; it is used only as a way of smuggling data
62−-- from unqDyn to qDyn
63−
64−--TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery
65−unqMarker :: a -> UnqDyn
66−unqMarker = error "An unqDyn expression was used outside of a qDyn expression"
67−
68−-- | Create a 'Dynamic' value using other 'Dynamic's as inputs. The result is
69−-- sometimes more concise and readable than the equivalent 'Applicative'-based
70−-- expression. For example:
71−--
72−-- > [mkDyn| $x + $v * $t + 1/2 * $a * $t ^ 2 |]
73−--
74−-- would have a very cumbersome 'Applicative' encoding.
75−mkDynPure :: QuasiQuoter
76−mkDynPure = QuasiQuoter
77− { quoteExp = mkDynExp
78− , quotePat = error "mkDyn: pattern splices are not supported"
79− , quoteType = error "mkDyn: type splices are not supported"
80− , quoteDec = error "mkDyn: declaration splices are not supported"
81− }
82−
83−mkDynExp :: String -> Q Exp
84−mkDynExp s = case Hs.parseExpWithMode Hs.defaultParseMode { Hs.extensions = [ Hs.EnableExtension Hs.TemplateHaskell ] } s of
85− Hs.ParseFailed (Hs.SrcLoc _ l c) err -> fail $ "mkDyn:" <> show l <> ":" <> show c <> ": " <> err
86− Hs.ParseOk e -> qDynPure $ return $ everywhere (id `extT` reinstateUnqDyn) $ Hs.toExp $ everywhere (id `extT` antiE) e
87− where TH.Name (TH.OccName occName) (TH.NameG _ _ (TH.ModName modName)) = 'unqMarker
88−#if MIN_VERSION_haskell_src_exts(1,18,0)
89− antiE :: Hs.Exp Hs.SrcSpanInfo -> Hs.Exp Hs.SrcSpanInfo
90− antiE x = case x of
91− Hs.SpliceExp l se ->
92− Hs.App l (Hs.Var l $ Hs.Qual l (Hs.ModuleName l modName) (Hs.Ident l occName)) $ case se of
93− Hs.IdSplice l2 v -> Hs.Var l2 $ Hs.UnQual l2 $ Hs.Ident l2 v
94− Hs.ParenSplice _ ps -> ps
95− _ -> x
96−#else
97− antiE x = case x of
98− Hs.SpliceExp se ->
99− Hs.App (Hs.Var $ Hs.Qual (Hs.ModuleName modName) (Hs.Ident occName)) $ case se of
100− Hs.IdSplice v -> Hs.Var $ Hs.UnQual $ Hs.Ident v
101− Hs.ParenSplice ps -> ps
102− _ -> x
103−#endif
104− reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName')))
105− | modName == modName' && occName == occName' = 'unqMarker
106− reinstateUnqDyn x = x
src/Reflex/Dynamic/Uniq.hsdeleted−105
@@ -1,105 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE MagicHash #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−#ifdef USE_REFLEX_OPTIMIZER
6−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
7−#endif
8−-- | This module provides a variation of 'Dynamic' values that uses cheap
9−-- pointer equality checks to reduce the amount of signal propagation needed.
10−module Reflex.Dynamic.Uniq
11− ( UniqDynamic
12− , uniqDynamic
13− , fromUniqDynamic
14− , alreadyUniqDynamic
15− ) where
16−
17−import Control.Applicative (Applicative (..))
18−import GHC.Exts
19−import Reflex.Class
20−
21−-- | A 'Dynamic' whose 'updated' 'Event' will never fire with the same value as
22−-- the 'current' 'Behavior''s contents. In order to maintain this constraint,
23−-- the value inside a 'UniqDynamic' is always evaluated to
24−-- <https://wiki.haskell.org/Weak_head_normal_form weak head normal form>.
25−--
26−-- Internally, 'UniqDynamic' uses pointer equality as a heuristic to avoid
27−-- unnecessary update propagation; this is much more efficient than performing
28−-- full comparisons. However, when the 'UniqDynamic' is converted back into a
29−-- regular 'Dynamic', a full comparison is performed.
30−newtype UniqDynamic t a = UniqDynamic { unUniqDynamic :: Dynamic t a }
31−
32−-- | Construct a 'UniqDynamic' by eliminating redundant updates from a 'Dynamic'.
33−uniqDynamic :: Reflex t => Dynamic t a -> UniqDynamic t a
34−uniqDynamic d = UniqDynamic $ unsafeBuildDynamic (sample $ current d) $ flip pushCheap (updated d) $ \new -> do
35− old <- sample $ current d --TODO: Is it better to sample ourselves here?
36− return $ unsafeJustChanged old new
37−
38−-- | Retrieve a normal 'Dynamic' from a 'UniqDynamic'. This will perform a
39−-- final check using the output type's 'Eq' instance to ensure deterministic
40−-- behavior.
41−--
42−-- WARNING: If used with a type whose 'Eq' instance is not law-abiding -
43−-- specifically, if there are cases where @x /= x@, 'fromUniqDynamic' may
44−-- eliminate more 'updated' occurrences than it should. For example, NaN values
45−-- of 'Double' and 'Float' are considered unequal to themselves by the 'Eq'
46−-- instance, but can be equal by pointer equality. This may cause 'UniqDynamic'
47−-- to lose changes from NaN to NaN.
48−fromUniqDynamic :: (Reflex t, Eq a) => UniqDynamic t a -> Dynamic t a
49−fromUniqDynamic (UniqDynamic d) = unsafeDynamic (current d) e'
50− where
51− -- Only consider values different if they fail both pointer equality /and/
52− -- 'Eq' equality. This is to make things a bit more deterministic in the
53− -- case of unlawful 'Eq' instances. However, it is still possible to
54− -- achieve nondeterminism by constructing elements that are identical in
55− -- value, unequal according to 'Eq', and nondeterministically equal or
56− -- nonequal by pointer quality. I suspect that it is impossible to make the
57− -- behavior deterministic in this case.
58− superEq a b = a `unsafePtrEq` b || a == b
59− e' = attachWithMaybe (\x x' -> if x' `superEq` x then Nothing else Just x') (current d) (updated d)
60−
61−-- | Create a UniqDynamic without uniqing it on creation. This will be slightly
62−-- faster than uniqDynamic when used with a Dynamic whose values are always (or
63−-- nearly always) different from its previous values; if used with a Dynamic
64−-- whose values do not change frequently, it may be much slower than uniqDynamic
65−alreadyUniqDynamic :: Dynamic t a -> UniqDynamic t a
66−alreadyUniqDynamic = UniqDynamic
67−
68−unsafePtrEq :: a -> a -> Bool
69−unsafePtrEq a b = case a `seq` b `seq` reallyUnsafePtrEquality# a b of
70− 0# -> False
71− _ -> True
72−
73−unsafeJustChanged :: a -> a -> Maybe a
74−unsafeJustChanged old new =
75− if old `unsafePtrEq` new
76− then Nothing
77− else Just new
78−
79−instance Reflex t => Accumulator t (UniqDynamic t) where
80− accumMaybeM f z e = do
81− let f' old change = do
82− mNew <- f old change
83− return $ unsafeJustChanged old =<< mNew
84− d <- accumMaybeMDyn f' z e
85− return $ UniqDynamic d
86− mapAccumMaybeM f z e = do
87− let f' old change = do
88− (mNew, output) <- f old change
89− return (unsafeJustChanged old =<< mNew, output)
90− (d, out) <- mapAccumMaybeMDyn f' z e
91− return (UniqDynamic d, out)
92−
93−instance Reflex t => Functor (UniqDynamic t) where
94− fmap f (UniqDynamic d) = uniqDynamic $ fmap f d
95−
96−instance Reflex t => Applicative (UniqDynamic t) where
97− pure = UniqDynamic . constDyn
98− UniqDynamic a <*> UniqDynamic b = uniqDynamic $ a <*> b
99− _ *> b = b
100− a <* _ = a
101−
102−instance Reflex t => Monad (UniqDynamic t) where
103− UniqDynamic x >>= f = uniqDynamic $ x >>= unUniqDynamic . f
104− _ >> b = b
105− return = pure
src/Reflex/DynamicWriter.hsdeleted−7
@@ -1,7 +0,0 @@
1−module Reflex.DynamicWriter
2− {-# DEPRECATED "Use 'Reflex.DynamicWriter.Class' and 'Reflex.DynamicWrite.Base' instead, or just import 'Reflex'" #-}
3− ( module X
4− ) where
5−
6−import Reflex.DynamicWriter.Base as X
7−import Reflex.DynamicWriter.Class as X
src/Reflex/DynamicWriter/Base.hsdeleted−237
@@ -1,237 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−{-# LANGUAGE StandaloneDeriving #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−module Reflex.DynamicWriter.Base
17− ( DynamicWriterT (..)
18− , runDynamicWriterT
19− , withDynamicWriterT
20− ) where
21−
22−import Control.Monad.Exception
23−import Control.Monad.Identity
24−import Control.Monad.IO.Class
25−import Control.Monad.Primitive
26−import Control.Monad.Reader
27−import Control.Monad.Ref
28−import Control.Monad.State.Strict
29−import Data.Align
30−import Data.Dependent.Map (DMap)
31−import qualified Data.Dependent.Map as DMap
32−import Data.FastMutableIntMap
33−import Data.Functor.Misc
34−import Data.IntMap (IntMap)
35−import qualified Data.IntMap as IntMap
36−import Data.Map (Map)
37−import qualified Data.Map as Map
38−import Data.Semigroup (Semigroup(..))
39−import Data.Some (Some)
40−import Data.These
41−
42−import Reflex.Adjustable.Class
43−import Reflex.Class
44−import Reflex.DynamicWriter.Class
45−import Reflex.EventWriter.Class (EventWriter, tellEvent)
46−import Reflex.Host.Class
47−import qualified Reflex.Patch.MapWithMove as MapWithMove
48−import Reflex.PerformEvent.Class
49−import Reflex.PostBuild.Class
50−import Reflex.Query.Class
51−import Reflex.Requester.Class
52−import Reflex.TriggerEvent.Class
53−
54−instance MonadTrans (DynamicWriterT t w) where
55− lift = DynamicWriterT . lift
56−
57−mapIncrementalMapValues :: (Reflex t, Patch (p v), Patch (p v'), PatchTarget (p v) ~ f v, PatchTarget (p v') ~ f v', Functor p, Functor f) => (v -> v') -> Incremental t (p v) -> Incremental t (p v')
58−mapIncrementalMapValues f = unsafeMapIncremental (fmap f) (fmap f)
59−
60−mergeDynIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Dynamic t v)) -> Incremental t (PatchMap k v)
61−mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
62− where changedValues = fmap (PatchMap . fmap Just) $ mergeMapIncremental $ mapIncrementalMapValues updated a
63− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m
64−
65−mergeIntMapDynIncremental :: Reflex t => Incremental t (PatchIntMap (Dynamic t v)) -> Incremental t (PatchIntMap v)
66−mergeIntMapDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
67− where changedValues = fmap (PatchIntMap . fmap Just) $ mergeIntMapIncremental $ mapIncrementalMapValues updated a
68− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchIntMap m) -> PatchIntMap <$> mapM (mapM (sample . current)) m
69−
70−mergeDynIncrementalWithMove :: forall t k v. (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Dynamic t v)) -> Incremental t (PatchMapWithMove k v)
71−mergeDynIncrementalWithMove a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ alignWith f addedAndRemovedValues changedValues
72− where changedValues = mergeMapIncrementalWithMove $ mapIncrementalMapValues updated a
73− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ fmap unsafePatchMapWithMove . mapM (mapM (sample . current)) . unPatchMapWithMove
74− f :: These (PatchMapWithMove k v) (Map k v) -> PatchMapWithMove k v
75− f x = unsafePatchMapWithMove $
76− let (p, changed) = case x of
77− This p_ -> (unPatchMapWithMove p_, mempty)
78− That c -> (mempty, c)
79− These p_ c -> (unPatchMapWithMove p_, c)
80− (pWithNewVals, noLongerMoved) = flip runState [] $ forM p $ MapWithMove.nodeInfoMapMFrom $ \case
81− MapWithMove.From_Insert v -> return $ MapWithMove.From_Insert v
82− MapWithMove.From_Delete -> return MapWithMove.From_Delete
83− MapWithMove.From_Move k -> case Map.lookup k changed of
84− Nothing -> return $ MapWithMove.From_Move k
85− Just v -> do
86− modify (k:)
87− return $ MapWithMove.From_Insert v
88− noLongerMovedMap = Map.fromList $ fmap (, ()) noLongerMoved
89− in Map.differenceWith (\e _ -> Just $ MapWithMove.nodeInfoSetTo Nothing e) pWithNewVals noLongerMovedMap --TODO: Check if any in the second map are not covered?
90−
91−-- | A basic implementation of 'DynamicWriter'.
92−newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT [Dynamic t w] m a }
93− deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadAsyncException, MonadException) -- The list is kept in reverse order
94−
95−deriving instance MonadHold t m => MonadHold t (DynamicWriterT t w m)
96−deriving instance MonadSample t m => MonadSample t (DynamicWriterT t w m)
97−
98−
99−instance MonadRef m => MonadRef (DynamicWriterT t w m) where
100− type Ref (DynamicWriterT t w m) = Ref m
101− newRef = lift . newRef
102− readRef = lift . readRef
103− writeRef r = lift . writeRef r
104−
105−instance MonadAtomicRef m => MonadAtomicRef (DynamicWriterT t w m) where
106− atomicModifyRef r = lift . atomicModifyRef r
107−
108−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DynamicWriterT t w m) where
109− newEventWithTrigger = lift . newEventWithTrigger
110− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
111−
112−-- | Run a 'DynamicWriterT' action. The dynamic writer output will be provided
113−-- along with the result of the action.
114−runDynamicWriterT :: (MonadFix m, Reflex t, Monoid w) => DynamicWriterT t w m a -> m (a, Dynamic t w)
115−runDynamicWriterT (DynamicWriterT a) = do
116− (result, ws) <- runStateT a []
117− return (result, mconcat $ reverse ws)
118−
119−instance (Monad m, Monoid w, Reflex t) => DynamicWriter t w (DynamicWriterT t w m) where
120− tellDyn w = DynamicWriterT $ modify (w :)
121−
122−instance MonadReader r m => MonadReader r (DynamicWriterT t w m) where
123− ask = lift ask
124− local f (DynamicWriterT a) = DynamicWriterT $ mapStateT (local f) a
125− reader = lift . reader
126−
127−instance PerformEvent t m => PerformEvent t (DynamicWriterT t w m) where
128− type Performable (DynamicWriterT t w m) = Performable m
129− performEvent_ = lift . performEvent_
130− performEvent = lift . performEvent
131−
132−instance TriggerEvent t m => TriggerEvent t (DynamicWriterT t w m) where
133− newTriggerEvent = lift newTriggerEvent
134− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
135− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
136−
137−instance PostBuild t m => PostBuild t (DynamicWriterT t w m) where
138− getPostBuild = lift getPostBuild
139−
140−instance MonadState s m => MonadState s (DynamicWriterT t w m) where
141− get = lift get
142− put = lift . put
143−
144−instance PrimMonad m => PrimMonad (DynamicWriterT t w m) where
145− type PrimState (DynamicWriterT t w m) = PrimState m
146− primitive = lift . primitive
147−
148−newtype DynamicWriterTLoweredResult t w v a = DynamicWriterTLoweredResult (v a, Dynamic t w)
149−
150−-- | When the execution of a 'DynamicWriterT' action is adjusted using
151−-- 'Adjustable', the 'Dynamic' output of that action will also be updated to
152−-- match.
153−instance (Adjustable t m, MonadFix m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (DynamicWriterT t w m) where
154− runWithReplace a0 a' = do
155− (result0, result') <- lift $ runWithReplace (runDynamicWriterT a0) $ runDynamicWriterT <$> a'
156− tellDyn . join =<< holdDyn (snd result0) (snd <$> result')
157− return (fst result0, fst <$> result')
158− traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust mergeIntMapDynIncremental
159− traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap weakenPatchDMapWith mergeDynIncremental
160− traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeDynIncrementalWithMove
161−
162−traverseDMapWithKeyWithAdjustImpl :: forall t w k v' p p' v m. (PatchTarget (p' (Some k) (Dynamic t w)) ~ Map (Some k) (Dynamic t w), PatchTarget (p' (Some k) w) ~ Map (Some k) w, Patch (p' (Some k) w), Patch (p' (Some k) (Dynamic t w)), MonadFix m, Monoid w, Reflex t, MonadHold t m)
163− => ( (forall a. k a -> v a -> m (DynamicWriterTLoweredResult t w v' a))
164− -> DMap k v
165− -> Event t (p k v)
166− -> m (DMap k (DynamicWriterTLoweredResult t w v'), Event t (p k (DynamicWriterTLoweredResult t w v')))
167− )
168− -> ((forall a. DynamicWriterTLoweredResult t w v' a -> v' a) -> p k (DynamicWriterTLoweredResult t w v') -> p k v')
169− -> ((forall a. DynamicWriterTLoweredResult t w v' a -> Dynamic t w) -> p k (DynamicWriterTLoweredResult t w v') -> p' (Some k) (Dynamic t w))
170− -> (Incremental t (p' (Some k) (Dynamic t w)) -> Incremental t (p' (Some k) w))
171− -> (forall a. k a -> v a -> DynamicWriterT t w m (v' a))
172− -> DMap k v
173− -> Event t (p k v)
174− -> DynamicWriterT t w m (DMap k v', Event t (p k v'))
175−traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith mergeMyDynIncremental f (dm0 :: DMap k v) dm' = do
176− (result0, result') <- lift $ base (\k v -> fmap DynamicWriterTLoweredResult $ runDynamicWriterT $ f k v) dm0 dm'
177− let getValue (DynamicWriterTLoweredResult (v, _)) = v
178− getWritten (DynamicWriterTLoweredResult (_, w)) = w
179− liftedResult0 = DMap.map getValue result0
180− liftedResult' = ffor result' $ mapPatch getValue
181− liftedWritten0 :: Map (Some k) (Dynamic t w)
182− liftedWritten0 = weakenDMapWith getWritten result0
183− liftedWritten' = ffor result' $ weakenPatchWith getWritten
184− --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
185− i <- holdIncremental liftedWritten0 liftedWritten'
186− tellDyn $ fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
187− return (liftedResult0, liftedResult')
188−
189−traverseIntMapWithKeyWithAdjustImpl :: forall t w v' p p' v m. (PatchTarget (p' (Dynamic t w)) ~ IntMap (Dynamic t w), PatchTarget (p' w) ~ IntMap w, Patch (p' w), Patch (p' (Dynamic t w)), MonadFix m, Monoid w, Reflex t, MonadHold t m, Functor p, p ~ p')
190− => ( (IntMap.Key -> v -> m (v', Dynamic t w))
191− -> IntMap v
192− -> Event t (p v)
193− -> m (IntMap (v', Dynamic t w), Event t (p (v', Dynamic t w)))
194− )
195− -> (Incremental t (p' (Dynamic t w)) -> Incremental t (p' w))
196− -> (IntMap.Key -> v -> DynamicWriterT t w m v')
197− -> IntMap v
198− -> Event t (p v)
199− -> DynamicWriterT t w m (IntMap v', Event t (p v'))
200−traverseIntMapWithKeyWithAdjustImpl base mergeMyDynIncremental f (dm0 :: IntMap v) dm' = do
201− (result0, result') <- lift $ base (\k v -> runDynamicWriterT $ f k v) dm0 dm'
202− let liftedResult0 = fmap fst result0
203− liftedResult' = fmap (fmap fst) result'
204− liftedWritten0 :: IntMap (Dynamic t w)
205− liftedWritten0 = fmap snd result0
206− liftedWritten' = fmap (fmap snd) result'
207− --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
208− i <- holdIncremental liftedWritten0 liftedWritten'
209− tellDyn $ fmap (mconcat . IntMap.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
210− return (liftedResult0, liftedResult')
211−
212−-- | Map a function over the output of a 'DynamicWriterT'.
213−withDynamicWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m, MonadFix m)
214− => (w -> w')
215− -> DynamicWriterT t w m a
216− -> DynamicWriterT t w' m a
217−withDynamicWriterT f dw = do
218− (r, d) <- lift $ do
219− (r, d) <- runDynamicWriterT dw
220− let d' = fmap f d
221− return (r, d')
222− tellDyn d
223− return r
224−
225−instance Requester t m => Requester t (DynamicWriterT t w m) where
226− type Request (DynamicWriterT t w m) = Request m
227− type Response (DynamicWriterT t w m) = Response m
228− requesting = lift . requesting
229− requesting_ = lift . requesting_
230−
231−instance (MonadQuery t q m, Monad m) => MonadQuery t q (DynamicWriterT t w m) where
232− tellQueryIncremental = lift . tellQueryIncremental
233− askQueryResult = lift askQueryResult
234− queryIncremental = lift . queryIncremental
235−
236−instance EventWriter t w m => EventWriter t w (DynamicWriterT t v m) where
237− tellEvent = lift . tellEvent
src/Reflex/DynamicWriter/Class.hsdeleted−28
@@ -1,28 +0,0 @@
1−-- | This module defines the 'DynamicWriter' class.
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE UndecidableInstances #-}
7−#ifdef USE_REFLEX_OPTIMIZER
8−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
9−#endif
10−module Reflex.DynamicWriter.Class
11− ( MonadDynamicWriter
12− , DynamicWriter(..)
13− ) where
14−
15−import Control.Monad.Reader (ReaderT, lift)
16−import Reflex.Class (Dynamic)
17−
18−{-# DEPRECATED MonadDynamicWriter "Use 'DynamicWriter' instead" #-}
19−-- | Type synonym for 'DynamicWriter'
20−type MonadDynamicWriter = DynamicWriter
21−
22−-- | 'MonadDynamicWriter' efficiently collects 'Dynamic' values using 'tellDyn'
23−-- and combines them monoidally to provide a 'Dynamic' result.
24−class (Monad m, Monoid w) => DynamicWriter t w m | m -> t w where
25− tellDyn :: Dynamic t w -> m ()
26−
27−instance DynamicWriter t w m => DynamicWriter t w (ReaderT r m) where
28− tellDyn = lift . tellDyn
src/Reflex/EventWriter.hsdeleted−7
@@ -1,7 +0,0 @@
1−module Reflex.EventWriter
2− {-# DEPRECATED "Use 'Reflex.EventWriter.Class' and 'Reflex.EventWriter.Base' instead, or just import 'Reflex'" #-}
3− ( module X
4− ) where
5−
6−import Reflex.EventWriter.Base as X
7−import Reflex.EventWriter.Class as X
src/Reflex/EventWriter/Base.hsdeleted−306
@@ -1,306 +0,0 @@
1−-- | This module provides 'EventWriterT', the standard implementation of
2−-- 'EventWriter'.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE ExistentialQuantification #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE Rank2Types #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE TypeOperators #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−module Reflex.EventWriter.Base
17− ( EventWriterT (..)
18− , runEventWriterT
19− , runWithReplaceEventWriterTWith
20− , sequenceDMapWithAdjustEventWriterTWith
21− , mapEventWriterT
22− , withEventWriterT
23− ) where
24−
25−import Reflex.Adjustable.Class
26−import Reflex.Class
27−import Reflex.EventWriter.Class (EventWriter, tellEvent)
28−import Reflex.DynamicWriter.Class (DynamicWriter, tellDyn)
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.PostBuild.Class
32−import Reflex.Query.Class
33−import Reflex.Requester.Class
34−import Reflex.TriggerEvent.Class
35−
36−import Control.Monad.Exception
37−import Control.Monad.Identity
38−import Control.Monad.Primitive
39−import Control.Monad.Reader
40−import Control.Monad.Ref
41−import Control.Monad.State.Strict
42−import Data.Dependent.Map (DMap, DSum (..))
43−import qualified Data.Dependent.Map as DMap
44−import Data.Functor.Compose
45−import Data.Functor.Misc
46−import Data.GADT.Compare (GCompare (..), GEq (..), GOrdering (..))
47−import Data.IntMap.Strict (IntMap)
48−import qualified Data.IntMap.Strict as IntMap
49−import Data.List.NonEmpty (NonEmpty (..))
50−import Data.Map (Map)
51−import qualified Data.Map as Map
52−import Data.Semigroup
53−import Data.Some (Some)
54−import Data.Tuple
55−import Data.Type.Equality
56−
57−import Unsafe.Coerce
58−
59−{-# DEPRECATED TellId "Do not construct this directly; use tellId instead" #-}
60−newtype TellId w x
61− = TellId Int -- ^ WARNING: Do not construct this directly; use 'tellId' instead
62− deriving (Show, Eq, Ord, Enum)
63−
64−tellId :: Int -> TellId w w
65−tellId = TellId
66−{-# INLINE tellId #-}
67−
68−tellIdRefl :: TellId w x -> w :~: x
69−tellIdRefl _ = unsafeCoerce Refl
70−
71−withTellIdRefl :: TellId w x -> (w ~ x => r) -> r
72−withTellIdRefl tid r = case tellIdRefl tid of
73− Refl -> r
74−
75−instance GEq (TellId w) where
76− a `geq` b =
77− withTellIdRefl a $
78− withTellIdRefl b $
79− if a == b
80− then Just Refl
81− else Nothing
82−
83−instance GCompare (TellId w) where
84− a `gcompare` b =
85− withTellIdRefl a $
86− withTellIdRefl b $
87− case a `compare` b of
88− LT -> GLT
89− EQ -> GEQ
90− GT -> GGT
91−
92−data EventWriterState t w = EventWriterState
93− { _eventWriterState_nextId :: {-# UNPACK #-} !Int -- Always negative (and decreasing over time)
94− , _eventWriterState_told :: ![DSum (TellId w) (Event t)] -- In increasing order
95− }
96−
97−-- | A basic implementation of 'EventWriter'.
98−newtype EventWriterT t w m a = EventWriterT { unEventWriterT :: StateT (EventWriterState t w) m a }
99− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
100−
101−-- | Run a 'EventWriterT' action.
102−runEventWriterT :: forall t m w a. (Reflex t, Monad m, Semigroup w) => EventWriterT t w m a -> m (a, Event t w)
103−runEventWriterT (EventWriterT a) = do
104− (result, requests) <- runStateT a $ EventWriterState (-1) []
105− let combineResults :: DMap (TellId w) Identity -> w
106− combineResults = sconcat
107− . (\(h : t) -> h :| t) -- Unconditional; 'merge' guarantees that it will only fire with non-empty DMaps
108− . DMap.foldlWithKey (\vs tid (Identity v) -> withTellIdRefl tid $ v : vs) [] -- This is where we finally reverse the DMap to get things in the correct order
109− return (result, fmap combineResults $ merge $ DMap.fromDistinctAscList $ _eventWriterState_told requests) --TODO: We can probably make this fromDistinctAscList more efficient by knowing the length in advance, but this will require exposing internals of DMap; also converting it to use a strict list might help
110−
111−instance (Reflex t, Monad m, Semigroup w) => EventWriter t w (EventWriterT t w m) where
112− tellEvent w = EventWriterT $ modify $ \old ->
113− let myId = _eventWriterState_nextId old
114− in EventWriterState
115− { _eventWriterState_nextId = pred myId
116− , _eventWriterState_told = (tellId myId :=> w) : _eventWriterState_told old
117− }
118−
119−instance MonadTrans (EventWriterT t w) where
120− lift = EventWriterT . lift
121−
122−instance MonadSample t m => MonadSample t (EventWriterT t w m) where
123− sample = lift . sample
124−
125−instance MonadHold t m => MonadHold t (EventWriterT t w m) where
126− {-# INLINABLE hold #-}
127− hold v0 = lift . hold v0
128− {-# INLINABLE holdDyn #-}
129− holdDyn v0 = lift . holdDyn v0
130− {-# INLINABLE holdIncremental #-}
131− holdIncremental v0 = lift . holdIncremental v0
132− {-# INLINABLE buildDynamic #-}
133− buildDynamic a0 = lift . buildDynamic a0
134− {-# INLINABLE headE #-}
135− headE = lift . headE
136−
137−instance (Reflex t, Adjustable t m, MonadHold t m, Semigroup w) => Adjustable t (EventWriterT t w m) where
138− runWithReplace = runWithReplaceEventWriterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
139− traverseIntMapWithKeyWithAdjust = sequenceIntMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') mergeIntIncremental coincidencePatchIntMap
140− traverseDMapWithKeyWithAdjust = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith mergeMapIncremental coincidencePatchMap
141− traverseDMapWithKeyWithAdjustWithMove = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeMapIncrementalWithMove coincidencePatchMapWithMove
142−
143−instance Requester t m => Requester t (EventWriterT t w m) where
144− type Request (EventWriterT t w m) = Request m
145− type Response (EventWriterT t w m) = Response m
146− requesting = lift . requesting
147− requesting_ = lift . requesting_
148−
149−-- | Given a function like 'runWithReplace' for the underlying monad, implement
150−-- 'runWithReplace' for 'EventWriterT'. This is necessary when the underlying
151−-- monad doesn't have a 'Adjustable' instance or to override the default
152−-- 'Adjustable' behavior.
153−runWithReplaceEventWriterTWith :: forall m t w a b. (Reflex t, MonadHold t m, Semigroup w)
154− => (forall a' b'. m a' -> Event t (m b') -> EventWriterT t w m (a', Event t b'))
155− -> EventWriterT t w m a
156− -> Event t (EventWriterT t w m b)
157− -> EventWriterT t w m (a, Event t b)
158−runWithReplaceEventWriterTWith f a0 a' = do
159− (result0, result') <- f (runEventWriterT a0) $ fmapCheap runEventWriterT a'
160− tellEvent =<< switchHoldPromptOnly (snd result0) (fmapCheap snd result')
161− return (fst result0, fmapCheap fst result')
162−
163−-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceIntMapWithAdjust'.
164−sequenceIntMapWithAdjustEventWriterTWith
165− :: forall t m p w v v'
166− . ( Reflex t
167− , MonadHold t m
168− , Semigroup w
169− , Functor p
170− , Patch (p (Event t w))
171− , PatchTarget (p (Event t w)) ~ IntMap (Event t w)
172− , Patch (p w)
173− , PatchTarget (p w) ~ IntMap w
174− )
175− => ( (IntMap.Key -> v -> m (Event t w, v'))
176− -> IntMap v
177− -> Event t (p v)
178− -> EventWriterT t w m (IntMap (Event t w, v'), Event t (p (Event t w, v')))
179− )
180− -> (Incremental t (p (Event t w)) -> Event t (PatchTarget (p w)))
181− -> (Event t (p (Event t w)) -> Event t (p w))
182− -> (IntMap.Key -> v -> EventWriterT t w m v')
183− -> IntMap v
184− -> Event t (p v)
185− -> EventWriterT t w m (IntMap v', Event t (p v'))
186−sequenceIntMapWithAdjustEventWriterTWith base mergePatchIncremental coincidencePatch f dm0 dm' = do
187− let f' :: IntMap.Key -> v -> m (Event t w, v')
188− f' k v = swap <$> runEventWriterT (f k v)
189− (children0, children') <- base f' dm0 dm'
190− let result0 = fmap snd children0
191− result' = fmapCheap (fmap snd) children'
192− requests0 :: IntMap (Event t w)
193− requests0 = fmap fst children0
194− requests' :: Event t (p (Event t w))
195− requests' = fmapCheap (fmap fst) children'
196− e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
197− tellEvent $ fforMaybeCheap e $ \m ->
198− case IntMap.elems m of
199− [] -> Nothing
200− h : t -> Just $ sconcat $ h :| t
201− return (result0, result')
202−
203−-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceDMapWithAdjust'.
204−sequenceDMapWithAdjustEventWriterTWith
205− :: forall t m p p' w k v v'
206− . ( Reflex t
207− , MonadHold t m
208− , Semigroup w
209− , Patch (p' (Some k) (Event t w))
210− , PatchTarget (p' (Some k) (Event t w)) ~ Map (Some k) (Event t w)
211− , GCompare k
212− , Patch (p' (Some k) w)
213− , PatchTarget (p' (Some k) w) ~ Map (Some k) w
214− )
215− => ( (forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a))
216− -> DMap k v
217− -> Event t (p k v)
218− -> EventWriterT t w m (DMap k (Compose ((,) (Event t w)) v'), Event t (p k (Compose ((,) (Event t w)) v')))
219− )
220− -> ((forall a. Compose ((,) (Event t w)) v' a -> v' a) -> p k (Compose ((,) (Event t w)) v') -> p k v')
221− -> ((forall a. Compose ((,) (Event t w)) v' a -> Event t w) -> p k (Compose ((,) (Event t w)) v') -> p' (Some k) (Event t w))
222− -> (Incremental t (p' (Some k) (Event t w)) -> Event t (PatchTarget (p' (Some k) w)))
223− -> (Event t (p' (Some k) (Event t w)) -> Event t (p' (Some k) w))
224− -> (forall a. k a -> v a -> EventWriterT t w m (v' a))
225− -> DMap k v
226− -> Event t (p k v)
227− -> EventWriterT t w m (DMap k v', Event t (p k v'))
228−sequenceDMapWithAdjustEventWriterTWith base mapPatch weakenPatchWith mergePatchIncremental coincidencePatch f dm0 dm' = do
229− let f' :: forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a)
230− f' k v = Compose . swap <$> runEventWriterT (f k v)
231− (children0, children') <- base f' dm0 dm'
232− let result0 = DMap.map (snd . getCompose) children0
233− result' = fforCheap children' $ mapPatch $ snd . getCompose
234− requests0 :: Map (Some k) (Event t w)
235− requests0 = weakenDMapWith (fst . getCompose) children0
236− requests' :: Event t (p' (Some k) (Event t w))
237− requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
238− e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
239− tellEvent $ fforMaybeCheap e $ \m ->
240− case Map.elems m of
241− [] -> Nothing
242− h : t -> Just $ sconcat $ h :| t
243− return (result0, result')
244−
245−instance PerformEvent t m => PerformEvent t (EventWriterT t w m) where
246− type Performable (EventWriterT t w m) = Performable m
247− performEvent_ = lift . performEvent_
248− performEvent = lift . performEvent
249−
250−instance PostBuild t m => PostBuild t (EventWriterT t w m) where
251− getPostBuild = lift getPostBuild
252−
253−instance TriggerEvent t m => TriggerEvent t (EventWriterT t w m) where
254− newTriggerEvent = lift newTriggerEvent
255− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
256− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
257−
258−instance MonadReader r m => MonadReader r (EventWriterT t w m) where
259− ask = lift ask
260− local f (EventWriterT a) = EventWriterT $ mapStateT (local f) a
261− reader = lift . reader
262−
263−instance MonadRef m => MonadRef (EventWriterT t w m) where
264− type Ref (EventWriterT t w m) = Ref m
265− newRef = lift . newRef
266− readRef = lift . readRef
267− writeRef r = lift . writeRef r
268−
269−instance MonadAtomicRef m => MonadAtomicRef (EventWriterT t w m) where
270− atomicModifyRef r = lift . atomicModifyRef r
271−
272−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (EventWriterT t w m) where
273− newEventWithTrigger = lift . newEventWithTrigger
274− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
275−
276−instance (MonadQuery t q m, Monad m) => MonadQuery t q (EventWriterT t w m) where
277− tellQueryIncremental = lift . tellQueryIncremental
278− askQueryResult = lift askQueryResult
279− queryIncremental = lift . queryIncremental
280−
281−instance DynamicWriter t w m => DynamicWriter t w (EventWriterT t v m) where
282− tellDyn = lift . tellDyn
283−
284−instance PrimMonad m => PrimMonad (EventWriterT t w m) where
285− type PrimState (EventWriterT t w m) = PrimState m
286− primitive = lift . primitive
287−
288−-- | Map a function over the output of a 'EventWriterT'.
289−withEventWriterT :: (Semigroup w, Semigroup w', Reflex t, MonadHold t m)
290− => (w -> w')
291− -> EventWriterT t w m a
292− -> EventWriterT t w' m a
293−withEventWriterT f ew = do
294− (r, e) <- lift $ do
295− (r, e) <- runEventWriterT ew
296− let e' = fmap f e
297− return (r, e')
298− tellEvent e
299− return r
300−
301−-- | Change the monad underlying an EventWriterT
302−mapEventWriterT
303− :: (forall x. m x -> n x)
304− -> EventWriterT t w m a
305− -> EventWriterT t w n a
306−mapEventWriterT f (EventWriterT a) = EventWriterT $ mapStateT f a
src/Reflex/EventWriter/Class.hsdeleted−26
@@ -1,26 +0,0 @@
1−-- | This module defines the 'EventWriter' class.
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE UndecidableInstances #-}
6−#ifdef USE_REFLEX_OPTIMIZER
7−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
8−#endif
9−module Reflex.EventWriter.Class
10− ( EventWriter (..)
11− ) where
12−
13−import Control.Monad.Reader (ReaderT, lift)
14−import Data.Semigroup (Semigroup)
15−
16−import Reflex.Class (Event)
17−
18−
19−-- | 'EventWriter' efficiently collects 'Event' values using 'tellEvent'
20−-- and combines them via 'Semigroup' to provide an 'Event' result.
21−class (Monad m, Semigroup w) => EventWriter t w m | m -> t w where
22− tellEvent :: Event t w -> m ()
23−
24−
25−instance EventWriter t w m => EventWriter t w (ReaderT r m) where
26− tellEvent = lift . tellEvent
src/Reflex/FastWeak.hsdeleted−200
@@ -1,200 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−#if GHCJS_FAST_WEAK
5−{-# LANGUAGE ForeignFunctionInterface #-}
6−{-# LANGUAGE JavaScriptFFI #-}
7−#endif
8−
9−-- |
10−-- Module:
11−-- Reflex.FastWeak
12−-- Description:
13−-- 'FastWeak' is a weak pointer to some value, and 'FastWeakTicket' ensures the value
14−-- referred to by a 'FastWeak' stays live while the ticket is held (live).
15−--
16−-- On GHC or GHCJS when not built with the @fast-weak@ cabal flag, 'FastWeak' is a wrapper
17−-- around the simple version of 'System.Mem.Weak.Weak' where the key and value are the same.
18−--
19−-- On GHCJS when built with the @fast-weak@ cabal flag, 'FastWeak' is implemented directly
20−-- in JS using @h$FastWeak@ and @h$FastWeakTicket@ which are a nonstandard part of the GHCJS RTS.
21−module Reflex.FastWeak
22− ( FastWeakTicket
23− , FastWeak
24− , mkFastWeakTicket
25− , getFastWeakTicketValue
26− , getFastWeakTicketWeak
27− , getFastWeakValue
28− , getFastWeakTicket
29− , emptyFastWeak
30−#ifdef GHCJS_FAST_WEAK
31− --TODO: Move these elsewhere
32− , unsafeFromRawJSVal
33− , unsafeToRawJSVal
34− , js_isNull
35−#endif
36− ) where
37−
38−import GHC.Exts (Any)
39−import Unsafe.Coerce
40−
41−#ifdef GHCJS_FAST_WEAK
42−import GHCJS.Types
43−#else
44−import Control.Exception (evaluate)
45−import System.IO.Unsafe
46−import System.Mem.Weak
47−#endif
48−
49−
50−#ifdef GHCJS_FAST_WEAK
51−-- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'
52−-- can be used to get the referred to value without fear of @Nothing,
53−-- and 'getFastWeakTicketWeak' can be used to get the weak version.
54−--
55−-- Implemented by way of special support in the GHCJS RTS, @h$FastWeakTicket@.
56−newtype FastWeakTicket a = FastWeakTicket JSVal
57−
58−-- | A reference to some value which can be garbage collected if there are only
59−-- weak references to the value left.
60−--
61−-- 'getFastWeakValue' can be used to try and obtain a strong reference to the value.
62−--
63−-- The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using
64−-- 'getFastWeakTicket' if the value hasn't been collected yet.
65−--
66−-- Implemented by way of special support in the GHCJS RTS, @h$FastWeak@.
67−newtype FastWeak a = FastWeak JSVal
68−
69−-- Just designed to mirror JSVal, so that we can unsafeCoerce between the two
70−data Val a = Val { unVal :: a }
71−
72−-- | Coerce a JSVal that represents the heap object of a value of type @a@ into a value of type @a@
73−unsafeFromRawJSVal :: JSVal -> a
74−unsafeFromRawJSVal v = unVal (unsafeCoerce v)
75−
76−-- | Coerce a heap object of type @a@ into a 'JSVal' which represents that object.
77−unsafeToRawJSVal :: a -> JSVal
78−unsafeToRawJSVal v = unsafeCoerce (Val v)
79−#else
80−-- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'
81−-- can be used to get the referred to value without fear of @Nothing@,
82−-- and 'getFastWeakTicketWeak' can be used to get the weak version.
83−data FastWeakTicket a = FastWeakTicket
84− { _fastWeakTicket_val :: !a
85− , _fastWeakTicket_weak :: {-# UNPACK #-} !(Weak a)
86− }
87−
88−-- | A reference to some value which can be garbage collected if there are only weak references to the value left.
89−--
90−-- 'getFastWeakValue' can be used to try and obtain a strong reference to the value.
91−--
92−-- The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using 'getFastWeakTicket'
93−-- if the value hasn't been collected yet.
94−--
95−-- Synonymous with 'Weak'.
96−type FastWeak a = Weak a
97−#endif
98−
99−-- | Return the @a@ kept alive by the given 'FastWeakTicket'.
100−--
101−-- This needs to be in IO so we know that we've relinquished the ticket.
102−getFastWeakTicketValue :: FastWeakTicket a -> IO a
103−#ifdef GHCJS_FAST_WEAK
104−getFastWeakTicketValue t = do
105− v <- js_ticketVal t
106− return $ unsafeFromRawJSVal v
107−
108−foreign import javascript unsafe "$r = $1.val;" js_ticketVal :: FastWeakTicket a -> IO JSVal
109−#else
110−getFastWeakTicketValue = return . _fastWeakTicket_val
111−#endif
112−
113−-- | Get the value referred to by a 'FastWeak' if it hasn't yet been collected,
114−-- or @Nothing@ if it has been collected.
115−getFastWeakValue :: FastWeak a -> IO (Maybe a)
116−#ifdef GHCJS_FAST_WEAK
117−getFastWeakValue w = do
118− r <- js_weakVal w
119− case js_isNull r of
120− True -> return Nothing
121− False -> return $ Just $ unsafeFromRawJSVal r
122−
123−foreign import javascript unsafe "$1 === null" js_isNull :: JSVal -> Bool
124−
125−foreign import javascript unsafe "$r = ($1.ticket === null) ? null : $1.ticket.val;" js_weakVal :: FastWeak a -> IO JSVal
126−#else
127−getFastWeakValue = deRefWeak
128−#endif
129−
130−-- | Try to create a 'FastWeakTicket' for the given 'FastWeak' which will ensure the value referred
131−-- remains alive. Returns @Just@ if the value hasn't been collected
132−-- and a ticket can therefore be obtained, @Nothing@ if it's been collected.
133−getFastWeakTicket :: forall a. FastWeak a -> IO (Maybe (FastWeakTicket a))
134−#ifdef GHCJS_FAST_WEAK
135−getFastWeakTicket w = do
136− r <- js_weakTicket w
137− case js_isNull r of
138− True -> return Nothing
139− False -> return $ Just $ FastWeakTicket r
140−
141−foreign import javascript unsafe "$r = $1.ticket;" js_weakTicket :: FastWeak a -> IO JSVal
142−#else
143−getFastWeakTicket w = do
144− deRefWeak w >>= \case
145− Nothing -> return Nothing
146− Just v -> return $ Just $ FastWeakTicket
147− { _fastWeakTicket_val = v
148− , _fastWeakTicket_weak = w
149− }
150−#endif
151−
152−-- | Create a 'FastWeakTicket' directly from a value, creating a 'FastWeak' in the process
153−-- which can be obtained with 'getFastWeakTicketValue'.
154−mkFastWeakTicket :: a -> IO (FastWeakTicket a)
155−-- I think it's fine if this is lazy - it'll retain the 'a', but so would the output; we just need to make sure it's forced before we start relying on the
156−-- associated FastWeak to actually be weak
157−#ifdef GHCJS_FAST_WEAK
158−mkFastWeakTicket v = js_fastWeakTicket (unsafeToRawJSVal v)
159−
160−foreign import javascript unsafe "$r = new h$FastWeakTicket($1);" js_fastWeakTicket :: JSVal -> IO (FastWeakTicket a)
161−#else
162−mkFastWeakTicket v = do
163− v' <- evaluate v
164− w <- mkWeakPtr v' Nothing
165− return $ FastWeakTicket
166− { _fastWeakTicket_val = v'
167− , _fastWeakTicket_weak = w
168− }
169−#endif
170−
171−-- | Demote a 'FastWeakTicket'; which ensures the value is alive, to a 'FastWeak' which doesn't.
172−-- Note that unless the ticket for the same 'FastWeak' is held in some other way
173−-- the value might be collected immediately.
174−getFastWeakTicketWeak :: FastWeakTicket a -> IO (FastWeak a)
175−-- Needs IO so that it can force the value - otherwise, could end up with a reference to the Ticket, which would retain the value
176−#ifdef GHCJS_FAST_WEAK
177−foreign import javascript unsafe "$r = $1.weak;" getFastWeakTicketWeak' :: FastWeakTicket a -> IO (FastWeak a)
178−{-# INLINE getFastWeakTicketWeak #-}
179−getFastWeakTicketWeak = getFastWeakTicketWeak'
180−#else
181−getFastWeakTicketWeak = return . _fastWeakTicket_weak
182−#endif
183−
184−-- | A weak reference that is always empty
185−emptyFastWeak :: FastWeak a
186−emptyFastWeak = unsafeCoerce w
187− where w :: FastWeak Any
188−#ifdef GHCJS_FAST_WEAK
189− w = js_emptyWeak
190−#else
191− w = unsafePerformIO $ do
192− w' <- mkWeakPtr undefined Nothing
193− finalize w'
194− return w'
195−#endif
196−{-# NOINLINE emptyFastWeak #-}
197−
198−#ifdef GHCJS_FAST_WEAK
199−foreign import javascript unsafe "$r = new h$FastWeak(null);" js_emptyWeak :: FastWeak Any
200−#endif
src/Reflex/FunctorMaybe.hsdeleted−47
@@ -1,47 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−#if MIN_VERSION_base(4,9,0)
3−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4−{-# LANGUAGE StandaloneDeriving #-}
5−#endif
6−
7−-- |
8−-- Module:
9−-- Reflex.FunctorMaybe
10−-- Description:
11−-- This module defines the FunctorMaybe class, which extends Functors with the
12−-- ability to delete values.
13−module Reflex.FunctorMaybe
14− ( FunctorMaybe (..)
15− ) where
16−
17−import Data.IntMap (IntMap)
18−import Data.Map (Map)
19−#if MIN_VERSION_base(4,9,0)
20−import Data.Semigroup (Option(..))
21−#endif
22−import Data.Witherable
23−
24−--TODO: See if there's a better class in the standard libraries already
25−
26−-- | A class for values that combines filtering and mapping using 'Maybe'.
27−-- Morally, @'FunctorMaybe' ~ KleisliFunctor 'Maybe'@.
28−{-# DEPRECATED FunctorMaybe "Use 'Filterable' from Data.Witherable instead" #-}
29−class FunctorMaybe f where
30− -- | Combined mapping and filtering function.
31− fmapMaybe :: (a -> Maybe b) -> f a -> f b
32−
33−instance FunctorMaybe Maybe where
34− fmapMaybe = mapMaybe
35−
36−#if MIN_VERSION_base(4,9,0)
37−deriving instance FunctorMaybe Option
38−#endif
39−
40−instance FunctorMaybe [] where
41− fmapMaybe = mapMaybe
42−
43−instance FunctorMaybe (Map k) where
44− fmapMaybe = mapMaybe
45−
46−instance FunctorMaybe IntMap where
47− fmapMaybe = mapMaybe
src/Reflex/Host/Class.hsdeleted−279
@@ -1,279 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE RoleAnnotations #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−#ifdef USE_REFLEX_OPTIMIZER
13−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
14−#endif
15−-- | This module provides the interface for hosting 'Reflex' engines. This
16−-- should only be necessary if you're writing a binding or some other library
17−-- that provides a core event loop.
18−module Reflex.Host.Class
19− ( ReflexHost (..)
20− , MonadSubscribeEvent (..)
21− , MonadReadEvent (..)
22− , MonadReflexCreateTrigger (..)
23− , MonadReflexHost (..)
24− , fireEvents
25− , newEventWithTriggerRef
26− , fireEventRef
27− , fireEventRefAndRead
28− ) where
29−
30−import Reflex.Class
31−
32−import Control.Monad.Fix
33−import Control.Monad.Identity
34−import Control.Monad.Ref
35−import Control.Monad.Trans
36−import Control.Monad.Trans.Cont (ContT)
37−import Control.Monad.Trans.Except (ExceptT)
38−import Control.Monad.Trans.Reader (ReaderT)
39−import Control.Monad.Trans.RWS (RWST)
40−import Control.Monad.Trans.State (StateT)
41−import qualified Control.Monad.Trans.State.Strict as Strict
42−import Control.Monad.Trans.Writer (WriterT)
43−import Data.Dependent.Sum (DSum (..))
44−import Data.GADT.Compare
45−
46−-- | Framework implementation support class for the reflex implementation
47−-- represented by @t@.
48−class ( Reflex t
49− , MonadReflexCreateTrigger t (HostFrame t)
50− , MonadSample t (HostFrame t)
51− , MonadHold t (HostFrame t)
52− , MonadFix (HostFrame t)
53− , MonadSubscribeEvent t (HostFrame t)
54− ) => ReflexHost t where
55− type EventTrigger t :: * -> *
56− type EventHandle t :: * -> *
57− type HostFrame t :: * -> *
58−
59−-- | Monad in which Events can be 'subscribed'. This forces all underlying
60−-- event sources to be initialized, so that the event will fire whenever it
61−-- ought to. Events must be subscribed before they are read using readEvent
62−class (Reflex t, Monad m) => MonadSubscribeEvent t m | m -> t where
63− -- | Subscribe to an event and set it up if needed.
64− --
65− -- This function will create a new 'EventHandle' from an 'Event'. This handle
66− -- may then be used via 'readEvent' in the read callback of
67− -- 'fireEventsAndRead'.
68− --
69− -- If the event wasn't subscribed to before (either manually or through a
70− -- dependent event or behavior) then this function will cause the event and
71− -- all dependencies of this event to be set up. For example, if the event was
72− -- created by 'newEventWithTrigger', then it's callback will be executed.
73− --
74− -- It's safe to call this function multiple times.
75− subscribeEvent :: Event t a -> m (EventHandle t a)
76−
77−-- | Monad that allows to read events' values.
78−class (ReflexHost t, Applicative m, Monad m) => MonadReadEvent t m | m -> t where
79− -- | Read the value of an 'Event' from an 'EventHandle' (created by calling
80− -- 'subscribeEvent').
81− --
82− -- After event propagation is done, all events can be in two states: either
83− -- they are firing with some value or they are not firing. In the former
84− -- case, this function returns @Just act@, where @act@ in an action to read
85− -- the current value of the event. In the latter case, the function returns
86− -- @Nothing@.
87− --
88− -- This function is normally used in the calllback for 'fireEventsAndRead'.
89− readEvent :: EventHandle t a -> m (Maybe (m a))
90−
91−-- | A monad where new events feed from external sources can be created.
92−class (Applicative m, Monad m) => MonadReflexCreateTrigger t m | m -> t where
93− -- | Creates a root 'Event' (one that is not based on any other event).
94− --
95− -- When a subscriber first subscribes to an event (building another event that
96− -- depends on the subscription) the given callback function is run and passed
97− -- a trigger. The callback function can then set up the event source in IO.
98− -- After this is done, the callback function must return an accompanying
99− -- teardown action.
100− --
101− -- Any time between setup and teardown the trigger can be used to fire the
102− -- event, by passing it to 'fireEventsAndRead'.
103− --
104− -- Note: An event may be set up multiple times. So after the teardown action
105− -- is executed, the event may still be set up again in the future.
106− newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)
107− newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k)
108−
109−-- | 'MonadReflexHost' designates monads that can run reflex frames.
110−class ( ReflexHost t
111− , MonadReflexCreateTrigger t m
112− , MonadSubscribeEvent t m
113− , MonadReadEvent t (ReadPhase m)
114− , MonadSample t (ReadPhase m)
115− , MonadHold t (ReadPhase m)
116− ) => MonadReflexHost t m | m -> t where
117− type ReadPhase m :: * -> *
118− -- | Propagate some events firings and read the values of events afterwards.
119− --
120− -- This function will create a new frame to fire the given events. It will
121− -- then update all dependent events and behaviors. After that is done, the
122− -- given callback is executed which allows to read the final values of events
123− -- and check whether they have fired in this frame or not.
124− --
125− -- All events that are given are fired at the same time.
126− --
127− -- This function is typically used in the main loop of a reflex framework
128− -- implementation. The main loop waits for external events to happen (such as
129− -- keyboard input or a mouse click) and then fires the corresponding events
130− -- using this function. The read callback can be used to read output events
131− -- and perform a corresponding response action to the external event.
132− fireEventsAndRead :: [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m a
133−
134− -- | Run a frame without any events firing.
135− --
136− -- This function should be used when you want to use 'sample' and 'hold' when
137− -- no events are currently firing. Using this function in that case can
138− -- improve performance, since the implementation can assume that no events are
139− -- firing when 'sample' or 'hold' are called.
140− --
141− -- This function is commonly used to set up the basic event network when the
142− -- application starts up.
143− runHostFrame :: HostFrame t a -> m a
144−
145−-- | Like 'fireEventsAndRead', but without reading any events.
146−fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t) Identity] -> m ()
147−fireEvents dm = fireEventsAndRead dm $ return ()
148−{-# INLINE fireEvents #-}
149−
150−-- | Create a new event and store its trigger in an 'IORef' while it's active.
151−--
152−-- An event is only active between the set up (when it's first subscribed to)
153−-- and the teardown phases (when noboby is subscribing the event anymore). This
154−-- function returns an Event and an 'IORef'. As long as the event is active, the
155−-- 'IORef' will contain 'Just' the event trigger to trigger this event. When the
156−-- event is not active, the 'IORef' will contain 'Nothing'. This allows event
157−-- sources to be more efficient, since they don't need to produce events when
158−-- nobody is listening.
159−newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
160−newEventWithTriggerRef = do
161− rt <- newRef Nothing
162− e <- newEventWithTrigger $ \t -> do
163− writeRef rt $ Just t
164− return $ writeRef rt Nothing
165− return (e, rt)
166−{-# INLINE newEventWithTriggerRef #-}
167−
168−-- | Fire the given trigger if it is not 'Nothing'.
169−fireEventRef :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> m ()
170−fireEventRef mtRef input = do
171− mt <- readRef mtRef
172− case mt of
173− Nothing -> return ()
174− Just trigger -> fireEvents [trigger :=> Identity input]
175−
176−-- | Fire the given trigger if it is not 'Nothing', and read from the given
177−-- 'EventHandle'.
178−fireEventRefAndRead :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> EventHandle t b -> m (Maybe b)
179−fireEventRefAndRead mtRef input e = do
180− mt <- readRef mtRef
181− case mt of
182− Nothing -> return Nothing -- Since we aren't firing the input, the output can't fire
183− Just trigger -> fireEventsAndRead [trigger :=> Identity input] $ do
184− mGetValue <- readEvent e
185− case mGetValue of
186− Nothing -> return Nothing
187− Just getValue -> fmap Just getValue
188−
189−
190−--------------------------------------------------------------------------------
191−-- Instances
192−--------------------------------------------------------------------------------
193−
194−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ReaderT r m) where
195− newEventWithTrigger = lift . newEventWithTrigger
196− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
197−
198−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ReaderT r m) where
199− subscribeEvent = lift . subscribeEvent
200−
201−instance MonadReflexHost t m => MonadReflexHost t (ReaderT r m) where
202− type ReadPhase (ReaderT r m) = ReadPhase m
203− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
204− runHostFrame = lift . runHostFrame
205−
206−instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (WriterT w m) where
207− newEventWithTrigger = lift . newEventWithTrigger
208− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
209−
210−instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (WriterT w m) where
211− subscribeEvent = lift . subscribeEvent
212−
213−instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (WriterT w m) where
214− type ReadPhase (WriterT w m) = ReadPhase m
215− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
216− runHostFrame = lift . runHostFrame
217−
218−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StateT s m) where
219− newEventWithTrigger = lift . newEventWithTrigger
220− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
221−
222−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (StateT r m) where
223− subscribeEvent = lift . subscribeEvent
224−
225−instance MonadReflexHost t m => MonadReflexHost t (StateT s m) where
226− type ReadPhase (StateT s m) = ReadPhase m
227− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
228− runHostFrame = lift . runHostFrame
229−
230−
231−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where
232− newEventWithTrigger = lift . newEventWithTrigger
233− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
234−
235−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (Strict.StateT r m) where
236− subscribeEvent = lift . subscribeEvent
237−
238−instance MonadReflexHost t m => MonadReflexHost t (Strict.StateT s m) where
239− type ReadPhase (Strict.StateT s m) = ReadPhase m
240− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
241− runHostFrame = lift . runHostFrame
242−
243−
244−
245−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where
246− newEventWithTrigger = lift . newEventWithTrigger
247− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
248−
249−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ContT r m) where
250− subscribeEvent = lift . subscribeEvent
251−
252−instance MonadReflexHost t m => MonadReflexHost t (ContT r m) where
253− type ReadPhase (ContT r m) = ReadPhase m
254− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
255− runHostFrame = lift . runHostFrame
256−
257−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ExceptT e m) where
258− newEventWithTrigger = lift . newEventWithTrigger
259− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
260−
261−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ExceptT r m) where
262− subscribeEvent = lift . subscribeEvent
263−
264−instance MonadReflexHost t m => MonadReflexHost t (ExceptT e m) where
265− type ReadPhase (ExceptT e m) = ReadPhase m
266− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
267− runHostFrame = lift . runHostFrame
268−
269−instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (RWST r w s m) where
270− newEventWithTrigger = lift . newEventWithTrigger
271− newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
272−
273−instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (RWST r w s m) where
274− subscribeEvent = lift . subscribeEvent
275−
276−instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (RWST r w s m) where
277− type ReadPhase (RWST r w s m) = ReadPhase m
278− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
279− runHostFrame = lift . runHostFrame
src/Reflex/Network.hsdeleted−45
@@ -1,45 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE MultiParamTypeClasses #-}
3−#ifdef USE_REFLEX_OPTIMIZER
4−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5−#endif
6−-- |
7−-- Module:
8−-- Reflex.Network
9−-- Description:
10−-- This module provides combinators for building FRP graphs/networks and modifying them dynamically.
11−module Reflex.Network
12− ( networkView
13− , networkHold
14− , untilReady
15− ) where
16−
17−import Reflex.Class
18−import Reflex.Adjustable.Class
19−import Reflex.NotReady.Class
20−import Reflex.PostBuild.Class
21−
22−-- | A 'Dynamic' "network": Takes a 'Dynamic' of network-creating actions and replaces the network whenever the 'Dynamic' updates.
23−-- The returned Event of network results fires at post-build time and when the 'Dynamic' updates.
24−-- Note: Often, the type 'a' is an Event, in which case the return value is an Event-of-Events, where the outer 'Event' fires
25−-- when switching networks. Such an 'Event' would typically be flattened (via 'switchPromptly').
26−networkView :: (NotReady t m, Adjustable t m, PostBuild t m) => Dynamic t (m a) -> m (Event t a)
27−networkView child = do
28− postBuild <- getPostBuild
29− let newChild = leftmost [updated child, tagCheap (current child) postBuild]
30− snd <$> runWithReplace notReady newChild
31−
32−-- | Given an initial "network" and an 'Event' of network-creating actions, create a network that is recreated whenever the Event fires.
33−-- The returned Dynamic of network results occurs when the Event does.
34−-- Note: Often, the type 'a' is an Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
35−networkHold :: (Adjustable t m, MonadHold t m) => m a -> Event t (m a) -> m (Dynamic t a)
36−networkHold child0 newChild = do
37− (result0, newResult) <- runWithReplace child0 newChild
38− holdDyn result0 newResult
39−
40−-- | Render a placeholder network to be shown while another network is not yet
41−-- done building
42−untilReady :: (Adjustable t m, PostBuild t m) => m a -> m b -> m (a, Event t b)
43−untilReady a b = do
44− postBuild <- getPostBuild
45− runWithReplace a $ b <$ postBuild
src/Reflex/NotReady/Class.hsdeleted−77
@@ -1,77 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DefaultSignatures #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE TypeFamilies #-}
7−{-# LANGUAGE UndecidableInstances #-}
8−#ifdef USE_REFLEX_OPTIMIZER
9−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10−#endif
11−module Reflex.NotReady.Class
12− ( NotReady(..)
13− ) where
14−
15−import Control.Monad.Reader (ReaderT)
16−import Control.Monad.Trans
17−import Control.Monad.Trans.Writer (WriterT)
18−
19−import Reflex.BehaviorWriter.Base (BehaviorWriterT)
20−import Reflex.Class
21−import Reflex.DynamicWriter.Base (DynamicWriterT)
22−import Reflex.EventWriter.Base (EventWriterT)
23−import Reflex.Host.Class
24−import Reflex.PerformEvent.Base (PerformEventT (..))
25−import Reflex.PostBuild.Base (PostBuildT)
26−import Reflex.Query.Base (QueryT)
27−import Reflex.Requester.Base (RequesterT)
28−import Reflex.TriggerEvent.Base (TriggerEventT)
29−
30−class Monad m => NotReady t m | m -> t where
31− notReadyUntil :: Event t a -> m ()
32− default notReadyUntil :: (MonadTrans f, m ~ f m', NotReady t m') => Event t a -> m ()
33− notReadyUntil = lift . notReadyUntil
34−
35− notReady :: m ()
36− default notReady :: (MonadTrans f, m ~ f m', NotReady t m') => m ()
37− notReady = lift notReady
38−
39−instance NotReady t m => NotReady t (ReaderT r m) where
40− notReadyUntil = lift . notReadyUntil
41− notReady = lift notReady
42−
43−instance (NotReady t m, Monoid w) => NotReady t (WriterT w m) where
44− notReadyUntil = lift . notReadyUntil
45− notReady = lift notReady
46−
47−instance NotReady t m => NotReady t (PostBuildT t m) where
48− notReadyUntil = lift . notReadyUntil
49− notReady = lift notReady
50−
51−instance NotReady t m => NotReady t (EventWriterT t w m) where
52− notReadyUntil = lift . notReadyUntil
53− notReady = lift notReady
54−
55−instance NotReady t m => NotReady t (DynamicWriterT t w m) where
56− notReadyUntil = lift . notReadyUntil
57− notReady = lift notReady
58−
59−instance NotReady t m => NotReady t (BehaviorWriterT t w m) where
60− notReadyUntil = lift . notReadyUntil
61− notReady = lift notReady
62−
63−instance NotReady t m => NotReady t (QueryT t q m) where
64− notReadyUntil = lift . notReadyUntil
65− notReady = lift notReady
66−
67−instance (ReflexHost t, NotReady t (HostFrame t)) => NotReady t (PerformEventT t m) where
68− notReadyUntil = PerformEventT . notReadyUntil
69− notReady = PerformEventT notReady
70−
71−instance NotReady t m => NotReady t (RequesterT t request response m) where
72− notReadyUntil = lift . notReadyUntil
73− notReady = lift notReady
74−
75−instance NotReady t m => NotReady t (TriggerEventT t m) where
76− notReadyUntil = lift . notReadyUntil
77− notReady = lift notReady
src/Reflex/Optimizer.hsdeleted−65
@@ -1,65 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−-- |
5−-- Module:
6−-- Reflex.Optimizer
7−-- Description:
8−-- This module provides a GHC plugin designed to improve code that uses
9−-- Reflex. Currently, it just adds an INLINABLE pragma to any top-level
10−-- definition that doesn't have an explicit inlining pragma. In the future,
11−-- additional optimizations are likely to be added.
12−module Reflex.Optimizer
13− ( plugin
14− ) where
15−
16−#ifdef ghcjs_HOST_OS
17−import Plugins
18−#else
19−import Control.Arrow
20−import CoreMonad
21−import Data.String
22−import GhcPlugins
23−
24−#if MIN_VERSION_base(4,9,0)
25−import Prelude hiding ((<>))
26−#endif
27−
28−#endif
29−
30−#ifdef ghcjs_HOST_OS
31−
32−-- | The GHCJS build of Reflex.Optimizer just throws an error; instead, the version built with GHC should be used.
33−plugin :: Plugin
34−plugin = error "The GHCJS build of Reflex.Optimizer cannot be used. Instead, build with GHC and use the result with GHCJS."
35−
36−#else
37−
38−-- | The GHC plugin itself. See "GhcPlugins" for more details.
39−plugin :: Plugin
40−plugin = defaultPlugin { installCoreToDos = install }
41−
42−install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
43−install [] p = do
44− liftIO $ putStrLn $ showSDocUnsafe $ ppr p
45− let f = \case
46− simpl@(CoreDoSimplify _ _) -> [CoreDoSpecialising, simpl]
47− x -> [x]
48− return $ makeInlinable : concatMap f p
49−install options@(_:_) p = do
50− warnMsg $ "Reflex.Optimizer: ignoring " <> fromString (show $ length options) <> " command-line options"
51− install [] p
52−
53−makeInlinable :: CoreToDo
54−makeInlinable = CoreDoPluginPass "MakeInlinable" $ \modGuts -> do
55− let f v = setIdInfo v $ let i = idInfo v in
56− setInlinePragInfo i $ let p = inlinePragInfo i in
57− if isDefaultInlinePragma p
58− then defaultInlinePragma { inl_inline = Inlinable }
59− else p
60− newBinds = flip map (mg_binds modGuts) $ \case
61− NonRec b e -> NonRec (f b) e
62− Rec bes -> Rec $ map (first f) bes
63− return $ modGuts { mg_binds = newBinds }
64−
65−#endif
src/Reflex/Patch.hsdeleted−46
@@ -1,46 +0,0 @@
1−{-# LANGUAGE TypeFamilies #-}
2−-- |
3−-- Module:
4−-- Reflex.Patch
5−-- Description:
6−-- This module defines the 'Patch' class, which is used by Reflex to manage
7−-- changes to 'Reflex.Class.Incremental' values.
8−module Reflex.Patch
9− ( module Reflex.Patch
10− , module X
11− ) where
12−
13−import Reflex.Patch.Class as X
14−import Reflex.Patch.DMap as X hiding (getDeletions)
15−import Reflex.Patch.DMapWithMove as X (PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove,
16− patchDMapWithMoveToPatchMapWithMoveWith,
17− traversePatchDMapWithMoveWithKey, unPatchDMapWithMove,
18− unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith)
19−import Reflex.Patch.IntMap as X hiding (getDeletions)
20−import Reflex.Patch.Map as X
21−import Reflex.Patch.MapWithMove as X (PatchMapWithMove, patchMapWithMoveNewElements,
22− patchMapWithMoveNewElementsMap, unPatchMapWithMove,
23− unsafePatchMapWithMove)
24−import Data.Map.Monoidal (MonoidalMap)
25−import Data.Semigroup (Semigroup (..), (<>))
26−
27−-- | A 'Group' is a 'Monoid' where every element has an inverse.
28−class (Semigroup q, Monoid q) => Group q where
29− negateG :: q -> q
30− (~~) :: q -> q -> q
31− r ~~ s = r <> negateG s
32−
33−-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
34−class Semigroup q => Additive q where
35−
36−-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
37−newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
38−
39−instance Additive p => Patch (AdditivePatch p) where
40− type PatchTarget (AdditivePatch p) = p
41− apply (AdditivePatch p) q = Just $ p <> q
42−
43−instance (Ord k, Group q) => Group (MonoidalMap k q) where
44− negateG = fmap negateG
45−
46−instance (Ord k, Additive q) => Additive (MonoidalMap k q)
src/Reflex/Patch/MapWithMove.hsdeleted−270
@@ -1,270 +0,0 @@
1−{-# LANGUAGE DeriveFoldable #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE DeriveTraversable #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE PatternGuards #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
10−-- another
11−module Reflex.Patch.MapWithMove where
12−
13−import Reflex.Patch.Class
14−
15−import Control.Arrow
16−import Control.Monad.State
17−import Data.Foldable
18−import Data.Function
19−import Data.List
20−import Data.Map (Map)
21−import qualified Data.Map as Map
22−import Data.Maybe
23−import Data.Semigroup (Semigroup (..), (<>))
24−import qualified Data.Set as Set
25−import Data.These (These(..))
26−import Data.Tuple
27−
28−-- | Patch a DMap with additions, deletions, and moves. Invariant: If key @k1@
29−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
30−-- and vice versa. There should never be any unpaired From/To keys.
31−newtype PatchMapWithMove k v = PatchMapWithMove (Map k (NodeInfo k v)) deriving (Show, Eq, Ord, Functor, Foldable, Traversable)
32−
33−-- | Holds the information about each key: where its new value should come from,
34−-- and where its old value should go to
35−data NodeInfo k v = NodeInfo
36− { _nodeInfo_from :: !(From k v)
37− -- ^ Where do we get the new value for this key?
38− , _nodeInfo_to :: !(To k)
39− -- ^ If the old value is being kept (i.e. moved rather than deleted or
40− -- replaced), where is it going?
41− }
42− deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
43−
44−-- | Describe how a key's new value should be produced
45−data From k v
46− = From_Insert v -- ^ Insert the given value here
47− | From_Delete -- ^ Delete the existing value, if any, from here
48− | From_Move !k -- ^ Move the value here from the given key
49− deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
50−
51−-- | Describe where a key's old value will go. If this is 'Just', that means
52−-- the key's old value will be moved to the given other key; if it is 'Nothing',
53−-- that means it will be deleted.
54−type To = Maybe
55−
56−-- | Create a 'PatchMapWithMove', validating it
57−patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
58−patchMapWithMove m = if valid then Just $ PatchMapWithMove m else Nothing
59− where valid = forwardLinks == backwardLinks
60− forwardLinks = Map.mapMaybe _nodeInfo_to m
61− backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, v) ->
62− case _nodeInfo_from v of
63− From_Move from -> Just (from, to)
64− _ -> Nothing
65−
66−-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
67−patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
68−patchMapWithMoveInsertAll m = PatchMapWithMove $ flip fmap m $ \v -> NodeInfo
69− { _nodeInfo_from = From_Insert v
70− , _nodeInfo_to = Nothing
71− }
72−
73−-- | Extract the internal representation of the 'PatchMapWithMove'
74−unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
75−unPatchMapWithMove (PatchMapWithMove p) = p
76−
77−-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
78−insertMapKey :: k -> v -> PatchMapWithMove k v
79−insertMapKey k v = PatchMapWithMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
80−
81−-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
82−--
83−-- @
84−-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
85−-- @
86−moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
87−moveMapKey src dst
88− | src == dst = mempty
89− | otherwise =
90− PatchMapWithMove $ Map.fromList
91− [ (dst, NodeInfo (From_Move src) Nothing)
92− , (src, NodeInfo From_Delete (Just dst))
93− ]
94−
95−-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
96−--
97−-- @
98−-- let aMay = Map.lookup a map
99−-- bMay = Map.lookup b map
100−-- in maybe id (Map.insert a) (bMay `mplus` aMay)
101−-- . maybe id (Map.insert b) (aMay `mplus` bMay)
102−-- . Map.delete a . Map.delete b $ map
103−-- @
104−swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
105−swapMapKey src dst
106− | src == dst = mempty
107− | otherwise =
108− PatchMapWithMove $ Map.fromList
109− [ (dst, NodeInfo (From_Move src) (Just src))
110− , (src, NodeInfo (From_Move dst) (Just dst))
111− ]
112−
113−-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
114−deleteMapKey :: k -> PatchMapWithMove k v
115−deleteMapKey k = PatchMapWithMove . Map.singleton k $ NodeInfo From_Delete Nothing
116−
117−-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
118−--
119−-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
120−unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
121−unsafePatchMapWithMove = PatchMapWithMove
122−
123−-- | Apply the insertions, deletions, and moves to a given 'Map'
124−instance Ord k => Patch (PatchMapWithMove k v) where
125− type PatchTarget (PatchMapWithMove k v) = Map k v
126− apply (PatchMapWithMove p) old = Just $! insertions `Map.union` (old `Map.difference` deletions) --TODO: return Nothing sometimes --Note: the strict application here is critical to ensuring that incremental merges don't hold onto all their prerequisite events forever; can we make this more robust?
127− where insertions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
128− From_Insert v -> Just v
129− From_Move k -> Map.lookup k old
130− From_Delete -> Nothing
131− deletions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
132− From_Delete -> Just ()
133− _ -> Nothing
134−
135−-- | Returns all the new elements that will be added to the 'Map'.
136−patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
137−patchMapWithMoveNewElements = Map.elems . patchMapWithMoveNewElementsMap
138−
139−-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
140−patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
141−patchMapWithMoveNewElementsMap (PatchMapWithMove p) = Map.mapMaybe f p
142− where f ni = case _nodeInfo_from ni of
143− From_Insert v -> Just v
144− From_Move _ -> Nothing
145− From_Delete -> Nothing
146−
147−-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
148−-- its values using the given ordering function. The set keys of the 'Map' is
149−-- not changed.
150−patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
151−patchThatSortsMapWith cmp m = PatchMapWithMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
152− where unsorted = Map.toList m
153− sorted = sortBy (cmp `on` snd) unsorted
154− f (to, _) (from, _) = if to == from then Nothing else
155− Just (from, to)
156− reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
157− g (to, _) (from, _) = if to == from then Nothing else
158− let Just movingTo = Map.lookup to reverseMapping
159− in Just (to, NodeInfo (From_Move from) $ Just movingTo)
160−
161−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
162−-- will produce a 'Map' with the same values as the second 'Map' but with the
163−-- values sorted with the given ordering function.
164−patchThatChangesAndSortsMapWith :: forall k v. (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
165−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
166− where newList = Map.toList newByIndexUnsorted
167− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
168−
169−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
170−-- will produce the second 'Map'.
171−patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
172−patchThatChangesMap oldByIndex newByIndex = patch
173− where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
174− (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
175− let f k v = do
176− remainingValues <- get
177− let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
178− then Map.delete v remainingValues
179− else Map.insert v remainingKeys remainingValues
180− case Map.lookup v remainingValues of
181− Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
182− Just fromKs ->
183− if k `Set.member` fromKs
184− then do
185− putRemainingKeys $ Set.delete k fromKs
186− return $ NodeInfo (From_Move k) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
187− else do
188− (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
189− putRemainingKeys remainingKeys
190− return $ NodeInfo (From_Move fromK) $ Just undefined
191− Map.traverseWithKey f newByIndex
192− unusedOldKeys = fold unusedValuesByValue
193− pointlessMove k = \case
194− From_Move k' | k == k' -> True
195− _ -> False
196− keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
197− then Just undefined
198− else Nothing
199− patch = unsafePatchMapWithMove $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
200−
201−-- | Change the 'From' value of a 'NodeInfo'
202−nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
203−nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
204−
205−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
206−-- 'Applicative', 'Monad', etc.) action to get the new value
207−nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
208−nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
209−
210−-- | Set the 'To' field of a 'NodeInfo'
211−nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
212−nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
213−
214−-- |Helper data structure used for composing patches using the monoid instance.
215−data Fixup k v
216− = Fixup_Delete
217− | Fixup_Update (These (From k v) (To k))
218−
219−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
220−instance Ord k => Semigroup (PatchMapWithMove k v) where
221− PatchMapWithMove ma <> PatchMapWithMove mb = PatchMapWithMove m
222− where
223− connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
224− h :: (k, (Maybe k, From k v)) -> [(k, Fixup k v)]
225− h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
226− (Just toAfter, From_Move fromBefore)
227− | fromBefore == toAfter
228− -> [(toAfter, Fixup_Delete)]
229− | otherwise
230− -> [ (toAfter, Fixup_Update (This editBefore))
231− , (fromBefore, Fixup_Update (That mToAfter))
232− ]
233− (Nothing, From_Move fromBefore) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
234− (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
235− (Nothing, _) -> []
236− mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
237− mergeFixups _ (Fixup_Update a) (Fixup_Update b)
238− | This x <- a, That y <- b
239− = Fixup_Update $ These x y
240− | That y <- a, This x <- b
241− = Fixup_Update $ These x y
242− mergeFixups _ _ _ = error "PatchMapWithMove: incompatible fixups"
243− fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
244− combineNodeInfos _ nia nib = NodeInfo
245− { _nodeInfo_from = _nodeInfo_from nia
246− , _nodeInfo_to = _nodeInfo_to nib
247− }
248− applyFixup _ ni = \case
249− Fixup_Delete -> Nothing
250− Fixup_Update u -> Just $ NodeInfo
251− { _nodeInfo_from = fromMaybe (_nodeInfo_from ni) $ getHere u
252− , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
253− }
254− m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
255− getHere :: These a b -> Maybe a
256− getHere = \case
257− This a -> Just a
258− These a _ -> Just a
259− That _ -> Nothing
260− getThere :: These a b -> Maybe b
261− getThere = \case
262− This _ -> Nothing
263− These _ b -> Just b
264− That b -> Just b
265−
266−--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
267−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
268−instance Ord k => Monoid (PatchMapWithMove k v) where
269− mempty = PatchMapWithMove mempty
270− mappend = (<>)
src/Reflex/PerformEvent/Base.hsdeleted−179
@@ -1,179 +0,0 @@
1−-- | This module provides 'PerformEventT', the standard implementation of
2−-- 'PerformEvent'.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE ExistentialQuantification #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE GADTs #-}
8−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE PartialTypeSignatures #-}
11−{-# LANGUAGE PolyKinds #-}
12−{-# LANGUAGE RankNTypes #-}
13−{-# LANGUAGE ScopedTypeVariables #-}
14−{-# LANGUAGE StandaloneDeriving #-}
15−{-# LANGUAGE TypeFamilies #-}
16−{-# LANGUAGE TypeOperators #-}
17−{-# LANGUAGE UndecidableInstances #-}
18−#ifdef USE_REFLEX_OPTIMIZER
19−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20−#endif
21−module Reflex.PerformEvent.Base
22− ( PerformEventT (..)
23− , FireCommand (..)
24− , hostPerformEventT
25− ) where
26−
27−import Reflex.Class
28−import Reflex.Adjustable.Class
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.Requester.Base
32−import Reflex.Requester.Class
33−
34−import Control.Lens
35−import Control.Monad.Exception
36−import Control.Monad.Identity
37−import Control.Monad.Primitive
38−import Control.Monad.Reader
39−import Control.Monad.Ref
40−import Data.Coerce
41−import Data.Dependent.Map (DMap)
42−import qualified Data.Dependent.Map as DMap
43−import Data.Dependent.Sum
44−import Data.IntMap.Strict (IntMap)
45−import qualified Data.IntMap.Strict as IntMap
46−import qualified Data.Semigroup as S
47−
48−-- | A function that fires events for the given 'EventTrigger's and then runs
49−-- any followup actions provided via 'PerformEvent'. The given 'ReadPhase'
50−-- action will be run once for the initial trigger execution as well as once for
51−-- each followup.
52−newtype FireCommand t m = FireCommand { runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a] } --TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?
53−
54−-- | Provides a basic implementation of 'PerformEvent'. Note that, despite the
55−-- name, 'PerformEventT' is not an instance of 'MonadTrans'.
56−newtype PerformEventT t m a = PerformEventT { unPerformEventT :: RequesterT t (HostFrame t) Identity (HostFrame t) a }
57−
58−deriving instance ReflexHost t => Functor (PerformEventT t m)
59−deriving instance ReflexHost t => Applicative (PerformEventT t m)
60−deriving instance ReflexHost t => Monad (PerformEventT t m)
61−deriving instance ReflexHost t => MonadFix (PerformEventT t m)
62−deriving instance (ReflexHost t, MonadIO (HostFrame t)) => MonadIO (PerformEventT t m)
63−deriving instance (ReflexHost t, MonadException (HostFrame t)) => MonadException (PerformEventT t m)
64−deriving instance (ReflexHost t, Monoid a) => Monoid (PerformEventT t m a)
65−deriving instance (ReflexHost t, S.Semigroup a) => S.Semigroup (PerformEventT t m a)
66−
67−instance (PrimMonad (HostFrame t), ReflexHost t) => PrimMonad (PerformEventT t m) where
68− type PrimState (PerformEventT t m) = PrimState (HostFrame t)
69− primitive = PerformEventT . lift . primitive
70−
71−instance (ReflexHost t, Ref m ~ Ref IO) => PerformEvent t (PerformEventT t m) where
72− type Performable (PerformEventT t m) = HostFrame t
73− {-# INLINABLE performEvent_ #-}
74− performEvent_ = PerformEventT . requesting_
75− {-# INLINABLE performEvent #-}
76− performEvent = PerformEventT . requestingIdentity
77−
78−instance (ReflexHost t, PrimMonad (HostFrame t)) => Adjustable t (PerformEventT t m) where
79− runWithReplace outerA0 outerA' = PerformEventT $ runWithReplaceRequesterTWith f (coerce outerA0) (coerceEvent outerA')
80− where f :: HostFrame t a -> Event t (HostFrame t b) -> RequesterT t (HostFrame t) Identity (HostFrame t) (a, Event t b)
81− f a0 a' = do
82− result0 <- lift a0
83− result' <- requestingIdentity a'
84− return (result0, result')
85− traverseIntMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseIntMapWithKeyWithAdjustRequesterTWith (defaultAdjustIntBase traverseIntMapPatchWithKey) patchIntMapNewElementsMap mergeIntIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
86− traverseDMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithKey) mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
87− traverseDMapWithKeyWithAdjustWithMove f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithMoveWithKey) mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
88−
89−defaultAdjustBase :: forall t v v2 k' p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
90− => ((forall a. k' a -> v a -> HostFrame t (v2 a)) -> p k' v -> HostFrame t (p k' v2))
91− -> (forall a. k' a -> v a -> HostFrame t (v2 a))
92− -> DMap k' v
93− -> Event t (p k' v)
94− -> RequesterT t (HostFrame t) Identity (HostFrame t) (DMap k' v2, Event t (p k' v2))
95−defaultAdjustBase traversePatchWithKey f' dm0 dm' = do
96− result0 <- lift $ DMap.traverseWithKey f' dm0
97− result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
98− return (result0, result')
99−
100−defaultAdjustIntBase :: forall t v v2 p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
101− => ((IntMap.Key -> v -> HostFrame t v2) -> p v -> HostFrame t (p v2))
102− -> (IntMap.Key -> v -> HostFrame t v2)
103− -> IntMap v
104− -> Event t (p v)
105− -> RequesterT t (HostFrame t) Identity (HostFrame t) (IntMap v2, Event t (p v2))
106−defaultAdjustIntBase traversePatchWithKey f' dm0 dm' = do
107− result0 <- lift $ IntMap.traverseWithKey f' dm0
108− result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
109− return (result0, result')
110−
111−instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where
112− {-# INLINABLE newEventWithTrigger #-}
113− newEventWithTrigger = PerformEventT . lift . newEventWithTrigger
114− {-# INLINABLE newFanEventWithTrigger #-}
115− newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f
116−
117−-- | Run a 'PerformEventT' action, returning a 'FireCommand' that allows the
118−-- caller to trigger 'Event's while ensuring that 'performEvent' actions are run
119−-- at the appropriate time.
120−{-# INLINABLE hostPerformEventT #-}
121−hostPerformEventT :: forall t m a.
122− ( Monad m
123− , MonadSubscribeEvent t m
124− , MonadReflexHost t m
125− , MonadRef m
126− , Ref m ~ Ref IO
127− )
128− => PerformEventT t m a
129− -> m (a, FireCommand t m)
130−hostPerformEventT a = do
131− (response, responseTrigger) <- newEventWithTriggerRef
132− (result, eventToPerform) <- runHostFrame $ runRequesterT (unPerformEventT a) response
133− eventToPerformHandle <- subscribeEvent eventToPerform
134− return $ (,) result $ FireCommand $ \triggers (readPhase :: ReadPhase m a') -> do
135− let go :: [DSum (EventTrigger t) Identity] -> m [a']
136− go ts = do
137− (result', mToPerform) <- fireEventsAndRead ts $ do
138− mToPerform <- sequence =<< readEvent eventToPerformHandle
139− result' <- readPhase
140− return (result', mToPerform)
141− case mToPerform of
142− Nothing -> return [result']
143− Just toPerform -> do
144− responses <- runHostFrame $ traverseRequesterData (fmap Identity) toPerform
145− mrt <- readRef responseTrigger
146− let followupEventTriggers = case mrt of
147− Just rt -> [rt :=> Identity responses]
148− Nothing -> []
149− (result':) <$> go followupEventTriggers
150− go triggers
151−
152−instance ReflexHost t => MonadSample t (PerformEventT t m) where
153− {-# INLINABLE sample #-}
154− sample = PerformEventT . lift . sample
155−
156−instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where
157− {-# INLINABLE hold #-}
158− hold v0 v' = PerformEventT $ lift $ hold v0 v'
159− {-# INLINABLE holdDyn #-}
160− holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'
161− {-# INLINABLE holdIncremental #-}
162− holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'
163− {-# INLINABLE buildDynamic #-}
164− buildDynamic getV0 v' = PerformEventT $ lift $ buildDynamic getV0 v'
165− {-# INLINABLE headE #-}
166− headE = PerformEventT . lift . headE
167−
168−instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where
169− type Ref (PerformEventT t m) = Ref (HostFrame t)
170− {-# INLINABLE newRef #-}
171− newRef = PerformEventT . lift . newRef
172− {-# INLINABLE readRef #-}
173− readRef = PerformEventT . lift . readRef
174− {-# INLINABLE writeRef #-}
175− writeRef r = PerformEventT . lift . writeRef r
176−
177−instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where
178− {-# INLINABLE atomicModifyRef #-}
179− atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
src/Reflex/PerformEvent/Class.hsdeleted−63
@@ -1,63 +0,0 @@
1−-- | This module defines 'PerformEvent' and 'TriggerEvent', which mediate the
2−-- interaction between a "Reflex"-based program and the external side-effecting
3−-- actions such as 'IO'.
4−{-# LANGUAGE CPP #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE TypeOperators #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−#ifdef USE_REFLEX_OPTIMIZER
14−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15−#endif
16−module Reflex.PerformEvent.Class
17− ( PerformEvent (..)
18− , performEventAsync
19− ) where
20−
21−import Reflex.Class
22−import Reflex.TriggerEvent.Class
23−
24−import Control.Monad.Reader
25−
26−-- | 'PerformEvent' represents actions that can trigger other actions based on
27−-- 'Event's.
28−class (Reflex t, Monad (Performable m), Monad m) => PerformEvent t m | m -> t where
29− -- | The type of action to be triggered; this is often not the same type as
30− -- the triggering action.
31− type Performable m :: * -> *
32− -- | Perform the action contained in the given 'Event' whenever the 'Event'
33− -- fires. Return the result in another 'Event'. Note that the output 'Event'
34− -- will generally occur later than the input 'Event', since most 'Performable'
35− -- actions cannot be performed during 'Event' propagation.
36− performEvent :: Event t (Performable m a) -> m (Event t a)
37− -- | Like 'performEvent', but do not return the result. May have slightly
38− -- better performance.
39− performEvent_ :: Event t (Performable m ()) -> m ()
40−
41−-- | Like 'performEvent', but the resulting 'Event' occurs only when the
42−-- callback (@a -> IO ()@) is called, not when the included action finishes.
43−--
44−-- NOTE: Despite the name, 'performEventAsync' does not run its action in a
45−-- separate thread - although the action is free to invoke forkIO and then call
46−-- the callback whenever it is ready. This will work properly, even in GHCJS
47−-- (which fully implements concurrency even though JavaScript does not have
48−-- built in concurrency).
49−{-# INLINABLE performEventAsync #-}
50−performEventAsync :: (TriggerEvent t m, PerformEvent t m) => Event t ((a -> IO ()) -> Performable m ()) -> m (Event t a)
51−performEventAsync e = do
52− (eOut, triggerEOut) <- newTriggerEvent
53− performEvent_ $ fmap ($ triggerEOut) e
54− return eOut
55−
56−instance PerformEvent t m => PerformEvent t (ReaderT r m) where
57− type Performable (ReaderT r m) = ReaderT r (Performable m)
58− performEvent_ e = do
59− r <- ask
60− lift $ performEvent_ $ flip runReaderT r <$> e
61− performEvent e = do
62− r <- ask
63− lift $ performEvent $ flip runReaderT r <$> e
src/Reflex/PostBuild/Base.hsdeleted−197
@@ -1,197 +0,0 @@
1−-- | This module defines 'PostBuildT', the standard implementation of
2−-- 'PostBuild'.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE DataKinds #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RecursiveDo #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE TypeOperators #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−#ifdef USE_REFLEX_OPTIMIZER
15−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
16−#endif
17−module Reflex.PostBuild.Base
18− ( PostBuildT (..)
19− , runPostBuildT
20− -- * Internal
21− , mapIntMapWithAdjustImpl
22− , mapDMapWithAdjustImpl
23− ) where
24−
25−import Reflex.Class
26−import Reflex.Adjustable.Class
27−import Reflex.Host.Class
28−import Reflex.PerformEvent.Class
29−import Reflex.PostBuild.Class
30−import Reflex.TriggerEvent.Class
31−
32−import Control.Applicative (liftA2)
33−import Control.Monad.Exception
34−import Control.Monad.Identity
35−import Control.Monad.Primitive
36−import Control.Monad.Reader
37−import Control.Monad.Ref
38−import qualified Control.Monad.Trans.Control as TransControl
39−import Data.Dependent.Map (DMap)
40−import qualified Data.Dependent.Map as DMap
41−import Data.Functor.Compose
42−import Data.IntMap.Strict (IntMap)
43−import qualified Data.IntMap.Strict as IntMap
44−import qualified Data.Semigroup as S
45−
46−-- | Provides a basic implementation of 'PostBuild'.
47−newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException)
48−
49−-- | Run a 'PostBuildT' action. An 'Event' should be provided that fires
50−-- immediately after the action is finished running; no other 'Event's should
51−-- fire first.
52−{-# INLINABLE runPostBuildT #-}
53−runPostBuildT :: PostBuildT t m a -> Event t () -> m a
54−runPostBuildT (PostBuildT a) = runReaderT a
55−
56−-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
57−instance (Monoid a, Applicative m) => Monoid (PostBuildT t m a) where
58− mempty = pure mempty
59− mappend = liftA2 mappend
60−
61−instance (S.Semigroup a, Applicative m) => S.Semigroup (PostBuildT t m a) where
62− (<>) = liftA2 (S.<>)
63−
64−instance PrimMonad m => PrimMonad (PostBuildT x m) where
65− type PrimState (PostBuildT x m) = PrimState m
66− primitive = lift . primitive
67−
68−instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where
69− {-# INLINABLE getPostBuild #-}
70− getPostBuild = PostBuildT ask
71−
72−instance MonadSample t m => MonadSample t (PostBuildT t m) where
73− {-# INLINABLE sample #-}
74− sample = lift . sample
75−
76−instance MonadHold t m => MonadHold t (PostBuildT t m) where
77− {-# INLINABLE hold #-}
78− hold v0 = lift . hold v0
79− {-# INLINABLE holdDyn #-}
80− holdDyn v0 = lift . holdDyn v0
81− {-# INLINABLE holdIncremental #-}
82− holdIncremental v0 = lift . holdIncremental v0
83− {-# INLINABLE buildDynamic #-}
84− buildDynamic a0 = lift . buildDynamic a0
85− {-# INLINABLE headE #-}
86− headE = lift . headE
87−
88−instance PerformEvent t m => PerformEvent t (PostBuildT t m) where
89− type Performable (PostBuildT t m) = Performable m
90− {-# INLINABLE performEvent_ #-}
91− performEvent_ = lift . performEvent_
92− {-# INLINABLE performEvent #-}
93− performEvent = lift . performEvent
94−
95−instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where
96− {-# INLINABLE newEventWithTrigger #-}
97− newEventWithTrigger = PostBuildT . lift . newEventWithTrigger
98− {-# INLINABLE newFanEventWithTrigger #-}
99− newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f
100−
101−instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where
102− {-# INLINABLE newTriggerEvent #-}
103− newTriggerEvent = lift newTriggerEvent
104− {-# INLINABLE newTriggerEventWithOnComplete #-}
105− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
106− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
107−
108−instance MonadRef m => MonadRef (PostBuildT t m) where
109− type Ref (PostBuildT t m) = Ref m
110− {-# INLINABLE newRef #-}
111− newRef = lift . newRef
112− {-# INLINABLE readRef #-}
113− readRef = lift . readRef
114− {-# INLINABLE writeRef #-}
115− writeRef r = lift . writeRef r
116−
117−instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where
118− {-# INLINABLE atomicModifyRef #-}
119− atomicModifyRef r = lift . atomicModifyRef r
120−
121−instance (Reflex t, MonadHold t m, MonadFix m, Adjustable t m, PerformEvent t m) => Adjustable t (PostBuildT t m) where
122− runWithReplace a0 a' = do
123− postBuild <- getPostBuild
124− lift $ do
125− rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a'
126− let voidResult' = fmapCheap (\_ -> ()) result'
127− return result
128− {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
129− traverseIntMapWithKeyWithAdjust = mapIntMapWithAdjustImpl traverseIntMapWithKeyWithAdjust
130− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
131− traverseDMapWithKeyWithAdjust = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap
132− traverseDMapWithKeyWithAdjustWithMove = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove
133−
134−{-# INLINABLE mapIntMapWithAdjustImpl #-}
135−mapIntMapWithAdjustImpl :: forall t m v v' p. (Reflex t, MonadFix m, MonadHold t m, Functor p)
136− => ( (IntMap.Key -> (Event t (), v) -> m v')
137− -> IntMap (Event t (), v)
138− -> Event t (p (Event t (), v))
139− -> m (IntMap v', Event t (p v'))
140− )
141− -> (IntMap.Key -> v -> PostBuildT t m v')
142− -> IntMap v
143− -> Event t (p v)
144− -> PostBuildT t m (IntMap v', Event t (p v'))
145−mapIntMapWithAdjustImpl base f dm0 dm' = do
146− postBuild <- getPostBuild
147− let loweredDm0 = fmap ((,) postBuild) dm0
148− f' :: IntMap.Key -> (Event t (), v) -> m v'
149− f' k (e, v) = do
150− runPostBuildT (f k v) e
151− lift $ do
152− rec (result0, result') <- base f' loweredDm0 loweredDm'
153− cohortDone <- numberOccurrencesFrom_ 1 result'
154− numberedDm' <- numberOccurrencesFrom 1 dm'
155− let postBuild' = fanInt $ fmapCheap (`IntMap.singleton` ()) cohortDone
156− loweredDm' = flip pushAlways numberedDm' $ \(n, p) -> do
157− return $ fmap ((,) (selectInt postBuild' n)) p
158− return (result0, result')
159−
160−{-# INLINABLE mapDMapWithAdjustImpl #-}
161−mapDMapWithAdjustImpl :: forall t m k v v' p. (Reflex t, MonadFix m, MonadHold t m)
162− => ( (forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a))
163− -> DMap k (Compose ((,) (Bool, Event t ())) v)
164− -> Event t (p k (Compose ((,) (Bool, Event t ())) v))
165− -> m (DMap k v', Event t (p k v'))
166− )
167− -> ((forall a. v a -> Compose ((,) (Bool, Event t ())) v a) -> p k v -> p k (Compose ((,) (Bool, Event t ())) v))
168− -> (forall a. k a -> v a -> PostBuildT t m (v' a))
169− -> DMap k v
170− -> Event t (p k v)
171− -> PostBuildT t m (DMap k v', Event t (p k v'))
172−mapDMapWithAdjustImpl base mapPatch f dm0 dm' = do
173− postBuild <- getPostBuild
174− let loweredDm0 = DMap.map (Compose . (,) (False, postBuild)) dm0
175− f' :: forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a)
176− f' k (Compose ((shouldHeadE, e), v)) = do
177− eOnce <- if shouldHeadE
178− then headE e --TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence
179− else return e
180− runPostBuildT (f k v) eOnce
181− lift $ do
182− rec (result0, result') <- base f' loweredDm0 loweredDm'
183− let voidResult' = fmapCheap (\_ -> ()) result'
184− let loweredDm' = ffor dm' $ mapPatch (Compose . (,) (True, voidResult'))
185− return (result0, result')
186−
187−--------------------------------------------------------------------------------
188−-- Deprecated functionality
189−--------------------------------------------------------------------------------
190−
191−-- | Deprecated
192−instance TransControl.MonadTransControl (PostBuildT t) where
193− type StT (PostBuildT t) a = TransControl.StT (ReaderT (Event t ())) a
194− {-# INLINABLE liftWith #-}
195− liftWith = TransControl.defaultLiftWith PostBuildT unPostBuildT
196− {-# INLINABLE restoreT #-}
197− restoreT = TransControl.defaultRestoreT PostBuildT
src/Reflex/PostBuild/Class.hsdeleted−41
@@ -1,41 +0,0 @@
1−-- | This module defines 'PostBuild', which indicates that an action will be
2−-- notified when it, and any action it's a part of, has finished executing.
3−{-# LANGUAGE CPP #-}
4−{-# LANGUAGE DataKinds #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE FunctionalDependencies #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE TypeOperators #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−#ifdef USE_REFLEX_OPTIMIZER
12−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
13−#endif
14−module Reflex.PostBuild.Class
15− ( PostBuild (..)
16− ) where
17−
18−import Reflex.Class
19−
20−import Control.Monad.Reader
21−import Control.Monad.State
22−import qualified Control.Monad.State.Strict as Strict
23−
24−-- | 'PostBuild' represents an action that is notified via an 'Event' when it
25−-- has finished executing. Note that the specific definition of "finished" is
26−-- determined by the instance of 'PostBuild', but the intent is to allow
27−-- 'Behavior's and 'Dynamic's to be safely sampled, regardless of where they
28−-- were created, when the post-build 'Event' fires. The post-build 'Event' will
29−-- fire exactly once for an given action.
30−class (Reflex t, Monad m) => PostBuild t m | m -> t where
31− -- | Retrieve the post-build 'Event' for this action.
32− getPostBuild :: m (Event t ())
33−
34−instance PostBuild t m => PostBuild t (ReaderT r m) where
35− getPostBuild = lift getPostBuild
36−
37−instance PostBuild t m => PostBuild t (StateT s m) where
38− getPostBuild = lift getPostBuild
39−
40−instance PostBuild t m => PostBuild t (Strict.StateT s m) where
41− getPostBuild = lift getPostBuild
src/Reflex/Profiled.hsdeleted−227
@@ -1,227 +0,0 @@
1−{-# LANGUAGE EmptyDataDecls #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE InstanceSigs #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE StandaloneDeriving #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−{-# LANGUAGE PolyKinds #-}
12−{-# LANGUAGE TypeApplications #-}
13−{-# LANGUAGE RankNTypes #-}
14−-- |
15−-- Module:
16−-- Reflex.Profiled
17−-- Description:
18−-- This module contains an instance of the 'Reflex' class that provides
19−-- profiling/cost-center information.
20−module Reflex.Profiled where
21−
22−import Control.Monad
23−import Control.Monad.Exception
24−import Control.Monad.Fix
25−import Control.Monad.Primitive
26−import Control.Monad.Reader
27−import Control.Monad.Ref
28−import Control.Monad.State.Strict (StateT, execStateT, modify)
29−import Data.Coerce
30−import Data.Dependent.Map (DMap, GCompare)
31−import Data.FastMutableIntMap
32−import Data.IORef
33−import Data.List
34−import Data.Map (Map)
35−import qualified Data.Map.Strict as Map
36−import Data.Monoid ((<>))
37−import Data.Ord
38−import Data.Profunctor.Unsafe ((#.))
39−import qualified Data.Semigroup as S
40−import Data.Type.Coercion
41−import Foreign.Ptr
42−import GHC.Foreign
43−import GHC.IO.Encoding
44−import GHC.Stack
45−import Reflex.Class
46−import Reflex.Host.Class
47−import Reflex.PerformEvent.Class
48−
49−import System.IO.Unsafe
50−import Unsafe.Coerce
51−
52−data ProfiledTimeline t
53−
54−{-# NOINLINE profilingData #-}
55−profilingData :: IORef (Map (Ptr CostCentreStack) Int)
56−profilingData = unsafePerformIO $ newIORef Map.empty
57−
58−data CostCentreTree = CostCentreTree
59− { _costCentreTree_ownEntries :: !Int
60− , _costCentreTree_cumulativeEntries :: !Int
61− , _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
62− }
63− deriving (Show, Eq, Ord)
64−
65−instance S.Semigroup CostCentreTree where
66− (CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
67− CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
68−
69−instance Monoid CostCentreTree where
70− mempty = CostCentreTree 0 0 mempty
71− mappend = (S.<>)
72−
73−getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
74−getCostCentreStack = go []
75− where go l ccs = if ccs == nullPtr
76− then return l
77− else do
78− cc <- ccsCC ccs
79− parent <- ccsParent ccs
80− go (cc : l) parent
81−
82−toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
83−toCostCentreTree ccs n =
84− foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty)
85− <$> getCostCentreStack ccs
86−
87−getCostCentreTree :: IO CostCentreTree
88−getCostCentreTree = do
89− vals <- readIORef profilingData
90− mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
91−
92−formatCostCentreTree :: CostCentreTree -> IO String
93−formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
94− where go :: Int -> CostCentreTree -> StateT [String] IO ()
95− go depth cct = do
96− let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
97− indent = mconcat $ replicate depth " "
98− forM_ children $ \(cc, childCct) -> do
99− lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
100− mdl <- liftIO $ peekCString utf8 =<< ccModule cc
101− loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
102− let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
103− modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
104− go (succ depth) childCct
105−
106−showProfilingData :: IO ()
107−showProfilingData = do
108− putStr =<< formatCostCentreTree =<< getCostCentreTree
109−
110−writeProfilingData :: FilePath -> IO ()
111−writeProfilingData p = do
112− writeFile p =<< formatCostCentreTree =<< getCostCentreTree
113−
114−newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
115− deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
116−
117−profileEvent :: Reflex t => Event t a -> Event t a
118−profileEvent e = unsafePerformIO $ do
119− stack <- getCurrentCCS e
120− let f x = unsafePerformIO $ do
121− modifyIORef' profilingData $ Map.insertWith (+) stack 1
122− return $ return $ Just x
123− return $ pushCheap f e
124−
125−--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
126−
127−instance Reflex t => Reflex (ProfiledTimeline t) where
128− newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
129− newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
130− newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
131− newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
132− type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
133− type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
134− never = Event_Profiled never
135− constant = Behavior_Profiled . constant
136− push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
137− pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
138− pull = Behavior_Profiled . pull . coerce
139− fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)
140− mergeG :: forall (k :: z -> *) q v. GCompare k
141− => (forall a. q a -> Event (ProfiledTimeline t) (v a))
142− -> DMap k q -> Event (ProfiledTimeline t) (DMap k v)
143− mergeG nt = Event_Profiled #. mergeG (coerce nt)
144− switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
145− coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
146− current (Dynamic_Profiled d) = coerce $ current d
147− updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
148− unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
149− unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
150− mergeIncrementalG nt = (Event_Profiled . coerce) #. mergeIncrementalG nt
151− mergeIncrementalWithMoveG nt = (Event_Profiled . coerce) #. mergeIncrementalWithMoveG nt
152− currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
153− updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
154− incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
155− behaviorCoercion c =
156− Coercion `trans` behaviorCoercion @t c `trans` Coercion
157− eventCoercion c =
158− Coercion `trans` eventCoercion @t c `trans` Coercion
159− dynamicCoercion c =
160− Coercion `trans` dynamicCoercion @t c `trans` Coercion
161− incrementalCoercion c d =
162− Coercion `trans` incrementalCoercion @t c d `trans` Coercion
163− mergeIntIncremental = Event_Profiled . mergeIntIncremental .
164− coerceWith (Coercion `trans` incrementalCoercion Coercion Coercion `trans` Coercion)
165− fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
166−
167−deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
168−deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
169−deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
170−
171−instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
172− hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
173− holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
174− holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
175− buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
176− headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
177−
178−instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
179− sample (Behavior_Profiled b) = ProfiledM $ sample b
180−
181−instance MonadTrans ProfiledM where
182− lift = ProfiledM
183−
184−instance MonadIO m => MonadIO (ProfiledM m) where
185− liftIO = lift . liftIO
186−
187−instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
188− type Performable (ProfiledM m) = Performable m
189− performEvent_ = lift . performEvent_ . coerce
190− performEvent = lift . fmap coerce . performEvent . coerce
191−
192−instance MonadRef m => MonadRef (ProfiledM m) where
193− type Ref (ProfiledM m) = Ref m
194− newRef = lift . newRef
195− readRef = lift . readRef
196− writeRef r = lift . writeRef r
197−
198−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
199− newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
200− newFanEventWithTrigger f = do
201− es <- lift $ newFanEventWithTrigger f
202− return $ EventSelector $ \k -> coerce $ select es k
203−
204−instance MonadReader r m => MonadReader r (ProfiledM m) where
205− ask = lift ask
206− local f (ProfiledM a) = ProfiledM $ local f a
207− reader = lift . reader
208−
209−instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
210− type EventTrigger (ProfiledTimeline t) = EventTrigger t
211− type EventHandle (ProfiledTimeline t) = EventHandle t
212− type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
213−
214−instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
215− subscribeEvent = lift . subscribeEvent . coerce
216−
217−instance PrimMonad m => PrimMonad (ProfiledM m) where
218− type PrimState (ProfiledM m) = PrimState m
219− primitive = lift . primitive
220−
221−instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
222− type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
223− fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
224− runHostFrame = lift . runHostFrame . coerce
225−
226−instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
227− readEvent = lift . fmap coerce . readEvent
src/Reflex/Pure.hsdeleted−212
@@ -1,212 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE EmptyDataDecls #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE InstanceSigs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TypeFamilies #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE PolyKinds #-}
10−
11−#ifdef USE_REFLEX_OPTIMIZER
12−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
13−#endif
14−
15−-- There are two expected orphan instances in this module:
16−-- * MonadSample (Pure t) ((->) t)
17−-- * MonadHold (Pure t) ((->) t)
18−{-# OPTIONS_GHC -fno-warn-orphans #-}
19−-- |
20−-- Module: Reflex.Pure
21−-- Description:
22−-- This module provides a pure implementation of Reflex, which is intended to
23−-- serve as a reference for the semantics of the Reflex class. All
24−-- implementations of Reflex should produce the same results as this
25−-- implementation, although performance and laziness/strictness may differ.
26−module Reflex.Pure
27− ( Pure
28− , Behavior (..)
29− , Event (..)
30− , Dynamic (..)
31− , Incremental (..)
32− ) where
33−
34−import Control.Monad
35−import Data.Dependent.Map (DMap, GCompare)
36−import qualified Data.Dependent.Map as DMap
37−import Data.IntMap (IntMap)
38−import qualified Data.IntMap as IntMap
39−import Data.Maybe
40−import Data.MemoTrie
41−import Data.Monoid
42−import Data.Type.Coercion
43−import Reflex.Class
44−import Data.Kind (Type)
45−
46−-- | A completely pure-functional 'Reflex' timeline, identifying moments in time
47−-- with the type @/t/@.
48−data Pure (t :: Type)
49−
50−-- | The 'Enum' instance of @/t/@ must be dense: for all @/x :: t/@, there must not exist
51−-- any @/y :: t/@ such that @/'pred' x < y < x/@. The 'HasTrie' instance will be used
52−-- exclusively to memoize functions of @/t/@, not for any of its other capabilities.
53−instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where
54−
55− newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }
56− newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }
57− newtype Dynamic (Pure t) a = Dynamic { unDynamic :: t -> (a, Maybe a) }
58− newtype Incremental (Pure t) p = Incremental { unIncremental :: t -> (PatchTarget p, Maybe p) }
59−
60− type PushM (Pure t) = (->) t
61− type PullM (Pure t) = (->) t
62−
63− never :: Event (Pure t) a
64− never = Event $ \_ -> Nothing
65−
66− constant :: a -> Behavior (Pure t) a
67− constant x = Behavior $ \_ -> x
68−
69− push :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
70− push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t
71−
72− pushCheap :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
73− pushCheap = push
74−
75− pull :: PullM (Pure t) a -> Behavior (Pure t) a
76− pull = Behavior . memo
77−
78− -- [UNUSED_CONSTRAINT]: The following type signature for merge will produce a
79− -- warning because the GCompare instance is not used; however, removing the
80− -- GCompare instance produces a different warning, due to that constraint
81− -- being present in the original class definition.
82−
83− --mergeG :: GCompare k => (forall a. q a -> Event (Pure t) (v a))
84− -- -> DMap k q -> Event (Pure t) (DMap k v)
85− mergeG nt events = Event $ memo $ \t ->
86− let currentOccurrences = DMap.mapMaybeWithKey (\_ q -> case nt q of Event a -> a t) events
87− in if DMap.null currentOccurrences
88− then Nothing
89− else Just currentOccurrences
90−
91−-- The instance signature doeesn't compile, leave commented for documentation
92−-- fanG :: GCompare k => Event (Pure t) (DMap k v) -> EventSelectorG (Pure t) k v
93− fanG e = EventSelectorG $ \k -> Event $ \t -> unEvent e t >>= DMap.lookup k
94−
95− switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a
96− switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
97−
98− coincidence :: Event (Pure t) (Event (Pure t) a) -> Event (Pure t) a
99− coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
100−
101− current :: Dynamic (Pure t) a -> Behavior (Pure t) a
102− current d = Behavior $ \t -> fst $ unDynamic d t
103−
104− updated :: Dynamic (Pure t) a -> Event (Pure t) a
105− updated d = Event $ \t -> snd $ unDynamic d t
106−
107− unsafeBuildDynamic :: PullM (Pure t) a -> Event (Pure t) a -> Dynamic (Pure t) a
108− unsafeBuildDynamic readV0 v' = Dynamic $ \t -> (readV0 t, unEvent v' t)
109−
110− -- See UNUSED_CONSTRAINT, above.
111−
112− --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p
113− --a) -> Incremental (Pure t) p a
114− unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)
115−
116− mergeIncrementalG = mergeIncrementalImpl
117− mergeIncrementalWithMoveG = mergeIncrementalImpl
118−
119− currentIncremental i = Behavior $ \t -> fst $ unIncremental i t
120−
121− updatedIncremental i = Event $ \t -> snd $ unIncremental i t
122−
123− incrementalToDynamic i = Dynamic $ \t ->
124− let (old, mPatch) = unIncremental i t
125− e = case mPatch of
126− Nothing -> Nothing
127− Just patch -> apply patch old
128− in (old, e)
129− behaviorCoercion Coercion = Coercion
130− eventCoercion Coercion = Coercion
131− dynamicCoercion Coercion = Coercion
132− incrementalCoercion Coercion Coercion = Coercion
133−
134− fanInt e = EventSelectorInt $ \k -> Event $ \t -> unEvent e t >>= IntMap.lookup k
135−
136− mergeIntIncremental = mergeIntIncrementalImpl
137−
138−mergeIncrementalImpl :: (PatchTarget p ~ DMap k q, GCompare k)
139− => (forall a. q a -> Event (Pure t) (v a))
140− -> Incremental (Pure t) p -> Event (Pure t) (DMap k v)
141−mergeIncrementalImpl nt i = Event $ \t ->
142− let results = DMap.mapMaybeWithKey (\_ q -> case nt q of Event e -> e t) $ fst $ unIncremental i t
143− in if DMap.null results
144− then Nothing
145− else Just results
146−
147−mergeIntIncrementalImpl :: (PatchTarget p ~ IntMap (Event (Pure t) a)) => Incremental (Pure t) p -> Event (Pure t) (IntMap a)
148−mergeIntIncrementalImpl i = Event $ \t ->
149− let results = IntMap.mapMaybeWithKey (\_ (Event e) -> e t) $ fst $ unIncremental i t
150− in if IntMap.null results
151− then Nothing
152− else Just results
153−
154−instance Functor (Dynamic (Pure t)) where
155− fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t
156− in (f cur, fmap f upd)
157−
158−instance Applicative (Dynamic (Pure t)) where
159− pure a = Dynamic $ \_ -> (a, Nothing)
160− (<*>) = ap
161−
162−instance Monad (Dynamic (Pure t)) where
163− return = pure
164− (x :: Dynamic (Pure t) a) >>= (f :: a -> Dynamic (Pure t) b) = Dynamic $ \t ->
165− let (curX :: a, updX :: Maybe a) = unDynamic x t
166− (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t
167− (updInner :: Maybe b, updBoth :: Maybe b) = case updX of
168− Nothing -> (Nothing, Nothing)
169− Just nextX -> let (c, u) = unDynamic (f nextX) t
170− in (Just c, u)
171− in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])
172−
173−instance MonadSample (Pure t) ((->) t) where
174−
175− sample :: Behavior (Pure t) a -> (t -> a)
176− sample = unBehavior
177−
178−instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
179−
180− hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a
181− hold initialValue e initialTime = Behavior f
182− where f = memo $ \sampleTime ->
183− -- Really, the sampleTime should never be prior to the initialTime,
184− -- because that would mean the Behavior is being sampled before
185− -- being created.
186− if sampleTime <= initialTime
187− then initialValue
188− else let lastTime = pred sampleTime
189− in fromMaybe (f lastTime) $ unEvent e lastTime
190−
191− holdDyn v0 = buildDynamic (return v0)
192−
193− buildDynamic :: (t -> a) -> Event (Pure t) a -> t -> Dynamic (Pure t) a
194− buildDynamic initialValue e initialTime =
195− let Behavior f = hold (initialValue initialTime) e initialTime
196− in Dynamic $ \t -> (f t, unEvent e t)
197−
198− holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p
199− holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)
200− where f = memo $ \sampleTime ->
201− -- Really, the sampleTime should never be prior to the initialTime,
202− -- because that would mean the Behavior is being sampled before
203− -- being created.
204− if sampleTime <= initialTime
205− then initialValue
206− else let lastTime = pred sampleTime
207− lastValue = f lastTime
208− in case unEvent e lastTime of
209− Nothing -> lastValue
210− Just x -> fromMaybe lastValue $ apply x lastValue
211−
212− headE = slowHeadE
src/Reflex/Query/Base.hsdeleted−335
@@ -1,335 +0,0 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3−{-# LANGUAGE InstanceSigs #-}
4−{-# LANGUAGE LambdaCase #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−{-# LANGUAGE StandaloneDeriving #-}
11−
12−module Reflex.Query.Base
13− ( QueryT (..)
14− , runQueryT
15− , mapQuery
16− , mapQueryResult
17− , dynWithQueryT
18− , withQueryT
19− ) where
20−
21−import Control.Applicative (liftA2)
22−import Control.Monad.Exception
23−import Control.Monad.Fix
24−import Control.Monad.Primitive
25−import Control.Monad.Reader
26−import Control.Monad.Ref
27−import Control.Monad.State.Strict
28−import Data.Align
29−import Data.Dependent.Map (DMap, DSum (..))
30−import qualified Data.Dependent.Map as DMap
31−import Data.Foldable
32−import Data.Functor.Compose
33−import Data.Functor.Misc
34−import Data.IntMap (IntMap)
35−import qualified Data.IntMap as IntMap
36−import Data.Map (Map)
37−import qualified Data.Map as Map
38−import Data.Monoid ((<>))
39−import qualified Data.Semigroup as S
40−import Data.Some (Some(Some))
41−import Data.These
42−
43−import Reflex.Class
44−import Reflex.Adjustable.Class
45−import Reflex.DynamicWriter.Class
46−import Reflex.EventWriter.Base
47−import Reflex.EventWriter.Class
48−import Reflex.Host.Class
49−import qualified Reflex.Patch.MapWithMove as MapWithMove
50−import Reflex.PerformEvent.Class
51−import Reflex.PostBuild.Class
52−import Reflex.Query.Class
53−import Reflex.Requester.Class
54−import Reflex.TriggerEvent.Class
55−
56−newtype QueryT t q m a = QueryT { unQueryT :: StateT [Behavior t q] (EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m)) a }
57− deriving (Functor, Applicative, Monad, MonadException, MonadFix, MonadIO, MonadAtomicRef)
58−
59−deriving instance MonadHold t m => MonadHold t (QueryT t q m)
60−deriving instance MonadSample t m => MonadSample t (QueryT t q m)
61−
62−runQueryT :: (MonadFix m, Additive q, Group q, Reflex t) => QueryT t q m a -> Dynamic t (QueryResult q) -> m (a, Incremental t (AdditivePatch q))
63−runQueryT (QueryT a) qr = do
64− ((r, bs), es) <- runReaderT (runEventWriterT (runStateT a mempty)) qr
65− return (r, unsafeBuildIncremental (foldlM (\b c -> (b <>) <$> sample c) mempty bs) (fmapCheap AdditivePatch es))
66−
67−newtype QueryTLoweredResult t q v = QueryTLoweredResult (v, [Behavior t q])
68−
69−getQueryTLoweredResultValue :: QueryTLoweredResult t q v -> v
70−getQueryTLoweredResultValue (QueryTLoweredResult (v, _)) = v
71−
72−getQueryTLoweredResultWritten :: QueryTLoweredResult t q v -> [Behavior t q]
73−getQueryTLoweredResultWritten (QueryTLoweredResult (_, w)) = w
74−
75−maskMempty :: (Eq a, Monoid a) => a -> Maybe a
76−maskMempty x = if x == mempty then Nothing else Just x
77−
78−instance (Reflex t, MonadFix m, Group q, Additive q, Query q, Eq q, MonadHold t m, Adjustable t m) => Adjustable t (QueryT t q m) where
79− runWithReplace (QueryT a0) a' = do
80− ((r0, bs0), r') <- QueryT $ lift $ runWithReplace (runStateT a0 []) $ fmapCheap (flip runStateT [] . unQueryT) a'
81− let sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
82− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
83− bs' = fmapCheap snd $ r'
84− bbs <- hold bs0 bs'
85− let patches = flip pushCheap bs' $ \newBs -> do
86− oldBs <- sample bbs
87− maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
88− QueryT $ modify $ (:) $ pull $ sampleBs =<< sample bbs
89− QueryT $ lift $ tellEvent patches
90− return (r0, fmapCheap fst r')
91−
92− traverseIntMapWithKeyWithAdjust :: forall v v'. (IntMap.Key -> v -> QueryT t q m v') -> IntMap v -> Event t (PatchIntMap v) -> QueryT t q m (IntMap v', Event t (PatchIntMap v'))
93− traverseIntMapWithKeyWithAdjust f im0 im' = do
94− let f' :: IntMap.Key -> v -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (QueryTLoweredResult t q v')
95− f' k v = fmap QueryTLoweredResult $ flip runStateT [] $ unQueryT $ f k v
96− (result0, result') <- QueryT $ lift $ traverseIntMapWithKeyWithAdjust f' im0 im'
97− let liftedResult0 = IntMap.map getQueryTLoweredResultValue result0
98− liftedResult' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
99− IntMap.map (fmap getQueryTLoweredResultValue) p
100− liftedBs0 :: IntMap [Behavior t q]
101− liftedBs0 = IntMap.map getQueryTLoweredResultWritten result0
102− liftedBs' :: Event t (PatchIntMap [Behavior t q])
103− liftedBs' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
104− IntMap.map (fmap getQueryTLoweredResultWritten) p
105− sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
106− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
107− accumBehaviors :: forall m'. MonadHold t m'
108− => IntMap [Behavior t q]
109− -> PatchIntMap [Behavior t q]
110− -> m' ( Maybe (IntMap [Behavior t q])
111− , Maybe (AdditivePatch q))
112− -- f accumulates the child behavior state we receive from running traverseIntMapWithKeyWithAdjust for the underlying monad.
113− -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
114− -- bs0 is a Map denoting the behaviors of the current children.
115− -- pbs is a PatchMap denoting an update to the behaviors of the current children
116− accumBehaviors bs0 pbs@(PatchIntMap bs') = do
117− let p k bs = case IntMap.lookup k bs0 of
118− Nothing -> case bs of
119− -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
120− Nothing -> return mempty
121− -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
122− Just newBs -> sampleBs newBs
123− Just oldBs -> case bs of
124− -- If the update is to delete the state for a child that already exists, the patch is the negation of the child's current state
125− Nothing -> negateG <$> sampleBs oldBs
126− -- If the update is to update the state for a child that already exists, the patch is the negation of sampling the child's current state
127− -- composed with the sampling the child's new state.
128− Just newBs -> (~~) <$> sampleBs newBs <*> sampleBs oldBs
129− -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
130− -- child patches and wrap them in AdditivePatch.
131− patch <- AdditivePatch . fold <$> IntMap.traverseWithKey p bs'
132− return (apply pbs bs0, Just patch)
133− (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
134− tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
135− return (liftedResult0, liftedResult')
136−
137− traverseDMapWithKeyWithAdjust :: forall (k :: * -> *) v v'. (DMap.GCompare k) => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMap k v) -> QueryT t q m (DMap k v', Event t (PatchDMap k v'))
138− traverseDMapWithKeyWithAdjust f dm0 dm' = do
139− let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
140− f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
141− (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjust f' dm0 dm'
142− let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
143− liftedResult' = fforCheap result' $ \(PatchDMap p) -> PatchDMap $
144− mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (getQueryTLoweredResultValue . getCompose) mr)) p
145− liftedBs0 :: Map (Some k) [Behavior t q]
146− liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
147− liftedBs' :: Event t (PatchMap (Some k) [Behavior t q])
148− liftedBs' = fforCheap result' $ \(PatchDMap p) -> PatchMap $
149− Map.fromDistinctAscList $ (\(k :=> ComposeMaybe mr) -> (Some k, fmap (getQueryTLoweredResultWritten . getCompose) mr)) <$> DMap.toList p
150− sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
151− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
152− accumBehaviors :: forall m'. MonadHold t m'
153− => Map (Some k) [Behavior t q]
154− -> PatchMap (Some k) [Behavior t q]
155− -> m' ( Maybe (Map (Some k) [Behavior t q])
156− , Maybe (AdditivePatch q))
157− -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjust for the underlying monad.
158− -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
159− -- bs0 is a Map denoting the behaviors of the current children.
160− -- pbs is a PatchMap denoting an update to the behaviors of the current children
161− accumBehaviors bs0 pbs@(PatchMap bs') = do
162− let p k bs = case Map.lookup k bs0 of
163− Nothing -> case bs of
164− -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
165− Nothing -> return Nothing
166− -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
167− Just newBs -> maskMempty <$> sampleBs newBs
168− Just oldBs -> case bs of
169− -- If the update is to delete the state for a child that already exists, the patch is the negation of the child's current state
170− Nothing -> maskMempty . negateG <$> sampleBs oldBs
171− -- If the update is to update the state for a child that already exists, the patch is the negation of sampling the child's current state
172− -- composed with the sampling the child's new state.
173− Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
174− -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
175− -- child patches and wrap them in AdditivePatch.
176− patch <- fold <$> Map.traverseWithKey p bs'
177− return (apply pbs bs0, AdditivePatch <$> patch)
178− (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
179− tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
180− return (liftedResult0, liftedResult')
181−
182− traverseDMapWithKeyWithAdjustWithMove :: forall (k :: * -> *) v v'. (DMap.GCompare k) => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMapWithMove k v) -> QueryT t q m (DMap k v', Event t (PatchDMapWithMove k v'))
183− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
184− let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
185− f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
186− (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjustWithMove f' dm0 dm'
187− let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
188− liftedResult' = fforCheap result' $ mapPatchDMapWithMove (getQueryTLoweredResultValue . getCompose)
189− liftedBs0 :: Map (Some k) [Behavior t q]
190− liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
191− liftedBs' :: Event t (PatchMapWithMove (Some k) [Behavior t q])
192− liftedBs' = fforCheap result' $ weakenPatchDMapWithMoveWith (getQueryTLoweredResultWritten . getCompose) {- \(PatchDMap p) -> PatchMapWithMove $
193− Map.fromDistinctAscList $ (\(k :=> mr) -> (Some k, fmap (fmap (getQueryTLoweredResultWritten . getCompose)) mr)) <$> DMap.toList p -}
194− sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
195− sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
196− accumBehaviors' :: forall m'. MonadHold t m'
197− => Map (Some k) [Behavior t q]
198− -> PatchMapWithMove (Some k) [Behavior t q]
199− -> m' ( Maybe (Map (Some k) [Behavior t q])
200− , Maybe (AdditivePatch q))
201− -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjustWithMove for the underlying monad.
202− -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
203− -- bs0 is a Map denoting the behaviors of the current children.
204− -- pbs is a PatchMapWithMove denoting an update to the behaviors of the current children
205− accumBehaviors' bs0 pbs = do
206− let bs' = unPatchMapWithMove pbs
207− p k bs = case Map.lookup k bs0 of
208− Nothing -> case MapWithMove._nodeInfo_from bs of
209− -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
210− MapWithMove.From_Delete -> return Nothing
211− -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
212− MapWithMove.From_Insert newBs -> maskMempty <$> sampleBs newBs
213− MapWithMove.From_Move k' -> case Map.lookup k' bs0 of
214− Nothing -> return Nothing
215− Just newBs -> maskMempty <$> sampleBs newBs
216− Just oldBs -> case MapWithMove._nodeInfo_from bs of
217− -- If the update is to delete the state for a child that already exists, the patch is the negation of the child's current state
218− MapWithMove.From_Delete -> maskMempty . negateG <$> sampleBs oldBs
219− -- If the update is to update the state for a child that already exists, the patch is the negation of sampling the child's current state
220− -- composed with the sampling the child's new state.
221− MapWithMove.From_Insert newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
222− MapWithMove.From_Move k'
223− | k' == k -> return Nothing
224− | otherwise -> case Map.lookup k' bs0 of
225− -- If we are moving from a non-existent key, that is a delete
226− Nothing -> maskMempty . negateG <$> sampleBs oldBs
227− Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
228− -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
229− -- child patches and wrap them in AdditivePatch.
230− patch <- fold <$> Map.traverseWithKey p bs'
231− return (apply pbs bs0, AdditivePatch <$> patch)
232− (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors' liftedBs0 liftedBs'
233− tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
234− return (liftedResult0, liftedResult')
235−
236−instance MonadTrans (QueryT t q) where
237− lift = QueryT . lift . lift . lift
238−
239−instance PrimMonad m => PrimMonad (QueryT t q m) where
240− type PrimState (QueryT t q m) = PrimState m
241− primitive = lift . primitive
242−
243−instance PostBuild t m => PostBuild t (QueryT t q m) where
244− getPostBuild = lift getPostBuild
245−
246−instance (MonadAsyncException m) => MonadAsyncException (QueryT t q m) where
247− mask f = QueryT $ mask $ \unMask -> unQueryT $ f $ QueryT . unMask . unQueryT
248−
249−instance TriggerEvent t m => TriggerEvent t (QueryT t q m) where
250− newTriggerEvent = lift newTriggerEvent
251− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
252− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
253−
254−instance PerformEvent t m => PerformEvent t (QueryT t q m) where
255− type Performable (QueryT t q m) = Performable m
256− performEvent_ = lift . performEvent_
257− performEvent = lift . performEvent
258−
259−instance MonadRef m => MonadRef (QueryT t q m) where
260− type Ref (QueryT t q m) = Ref m
261− newRef = QueryT . newRef
262− readRef = QueryT . readRef
263− writeRef r = QueryT . writeRef r
264−
265−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (QueryT t q m) where
266− newEventWithTrigger = QueryT . newEventWithTrigger
267− newFanEventWithTrigger a = QueryT . lift $ newFanEventWithTrigger a
268−
269−-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
270−instance (Monoid a, Monad m) => Monoid (QueryT t q m a) where
271− mempty = pure mempty
272− mappend = (<>)
273−
274−instance (S.Semigroup a, Monad m) => S.Semigroup (QueryT t q m a) where
275− (<>) = liftA2 (S.<>)
276−
277−-- | withQueryT's QueryMorphism argument needs to be a group homomorphism in order to behave correctly
278−withQueryT :: (MonadFix m, PostBuild t m, Group q, Group q', Additive q, Additive q', Query q')
279− => QueryMorphism q q'
280− -> QueryT t q m a
281− -> QueryT t q' m a
282−withQueryT f a = do
283− r' <- askQueryResult
284− (result, q) <- lift $ runQueryT a $ mapQueryResult f <$> r'
285− tellQueryIncremental $ unsafeBuildIncremental
286− (fmap (mapQuery f) (sample (currentIncremental q)))
287− (fmapCheap (AdditivePatch . mapQuery f . unAdditivePatch) $ updatedIncremental q)
288− return result
289−
290−-- | dynWithQueryT's (Dynamic t QueryMorphism) argument needs to be a group homomorphism at all times in order to behave correctly
291−dynWithQueryT :: (MonadFix m, PostBuild t m, Group q, Additive q, Group q', Additive q', Query q')
292− => Dynamic t (QueryMorphism q q')
293− -> QueryT t q m a
294− -> QueryT t q' m a
295−dynWithQueryT f q = do
296− r' <- askQueryResult
297− (result, q') <- lift $ runQueryT q $ zipDynWith mapQueryResult f r'
298− tellQueryIncremental $ zipDynIncrementalWith mapQuery f q'
299− return result
300− where zipDynIncrementalWith g da ib =
301− let eab = align (updated da) (updatedIncremental ib)
302− ec = flip push eab $ \case
303− This a -> do
304− aOld <- sample $ current da
305− b <- sample $ currentIncremental ib
306− return $ Just $ AdditivePatch (g a b ~~ g aOld b)
307− That (AdditivePatch b) -> do
308− a <- sample $ current da
309− return $ Just $ AdditivePatch $ g a b
310− These a (AdditivePatch b) -> do
311− aOld <- sample $ current da
312− bOld <- sample $ currentIncremental ib
313− return $ Just $ AdditivePatch $ mconcat [ g a bOld, negateG (g aOld bOld), g a b]
314− in unsafeBuildIncremental (g <$> sample (current da) <*> sample (currentIncremental ib)) ec
315−
316−instance (Monad m, Group q, Additive q, Query q, Reflex t) => MonadQuery t q (QueryT t q m) where
317− tellQueryIncremental q = do
318− QueryT (modify (currentIncremental q:))
319− QueryT (lift (tellEvent (fmapCheap unAdditivePatch (updatedIncremental q))))
320− askQueryResult = QueryT ask
321− queryIncremental q = do
322− tellQueryIncremental q
323− zipDynWith crop (incrementalToDynamic q) <$> askQueryResult
324−
325−instance Requester t m => Requester t (QueryT t q m) where
326− type Request (QueryT t q m) = Request m
327− type Response (QueryT t q m) = Response m
328− requesting = lift . requesting
329− requesting_ = lift . requesting_
330−
331−instance EventWriter t w m => EventWriter t w (QueryT t q m) where
332− tellEvent = lift . tellEvent
333−
334−instance DynamicWriter t w m => DynamicWriter t w (QueryT t q m) where
335− tellDyn = lift . tellDyn
src/Reflex/Query/Class.hsdeleted−118
@@ -1,118 +0,0 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE TypeFamilies #-}
7−{-# LANGUAGE UndecidableInstances #-}
8−-- |
9−-- Module:
10−-- Reflex.Query.Class
11−-- Description:
12−-- A class that ties together queries to some data source and their results,
13−-- providing methods for requesting data from the source and accumulating
14−-- streamed results.
15−module Reflex.Query.Class
16− ( Query (..)
17− , QueryMorphism (..)
18− , SelectedCount (..)
19− , combineSelectedCounts
20−
21− , MonadQuery (..)
22− , tellQueryDyn
23− , queryDyn
24− , mapQuery
25− , mapQueryResult
26− ) where
27−
28−import Control.Category (Category)
29−import qualified Control.Category as Cat
30−import Control.Monad.Reader
31−import Data.Bits
32−import Data.Data
33−import Data.Ix
34−import Data.Map.Monoidal (MonoidalMap)
35−import qualified Data.Map.Monoidal as MonoidalMap
36−import Data.Semigroup (Semigroup(..))
37−import Foreign.Storable
38−
39−import Reflex.Class
40−
41−-- | A 'Query' can be thought of as a declaration of interest in some set of data.
42−-- A 'QueryResult' is the set of data associated with that interest set.
43−-- The @crop@ function provides a way to determine what part of a given 'QueryResult'
44−-- is relevant to a given 'Query'.
45−class (Monoid (QueryResult a), Semigroup (QueryResult a)) => Query a where
46− type QueryResult a :: *
47− crop :: a -> QueryResult a -> QueryResult a
48−
49−instance (Ord k, Query v) => Query (MonoidalMap k v) where
50− type QueryResult (MonoidalMap k v) = MonoidalMap k (QueryResult v)
51− crop q r = MonoidalMap.intersectionWith (flip crop) r q
52−
53−-- | QueryMorphism's must be group homomorphisms when acting on the query type
54−-- and compatible with the query relationship when acting on the query result.
55−data QueryMorphism q q' = QueryMorphism
56− { _queryMorphism_mapQuery :: q -> q'
57− , _queryMorphism_mapQueryResult :: QueryResult q' -> QueryResult q
58− }
59−
60−instance Category QueryMorphism where
61− id = QueryMorphism id id
62− qm . qm' = QueryMorphism
63− { _queryMorphism_mapQuery = mapQuery qm . mapQuery qm'
64− , _queryMorphism_mapQueryResult = mapQueryResult qm' . mapQueryResult qm
65− }
66−
67−-- | Apply a 'QueryMorphism' to a 'Query'
68−mapQuery :: QueryMorphism q q' -> q -> q'
69−mapQuery = _queryMorphism_mapQuery
70−
71−-- | Map a 'QueryMorphism' to a 'QueryResult'
72−mapQueryResult :: QueryMorphism q q' -> QueryResult q' -> QueryResult q
73−mapQueryResult = _queryMorphism_mapQueryResult
74−
75−-- | This type can be used to track of the frequency of interest in a given 'Query'. See note on
76−-- 'combineSelectedCounts'
77−newtype SelectedCount = SelectedCount { unSelectedCount :: Int }
78− deriving (Eq, Ord, Show, Read, Integral, Num, Bounded, Enum, Real, Ix, Bits, FiniteBits, Storable, Data)
79−
80−instance Semigroup SelectedCount where
81− SelectedCount a <> SelectedCount b = SelectedCount (a + b)
82−
83−instance Monoid SelectedCount where
84− mempty = SelectedCount 0
85− mappend = (<>)
86−
87−instance Group SelectedCount where
88− negateG (SelectedCount a) = SelectedCount (negate a)
89−
90−instance Additive SelectedCount
91−
92−-- | The Semigroup/Monoid/Group instances for a Query containing 'SelectedCount's should use
93−-- this function which returns Nothing if the result is 0. This allows the pruning of leaves
94−-- of the 'Query' that are no longer wanted.
95−combineSelectedCounts :: SelectedCount -> SelectedCount -> Maybe SelectedCount
96−combineSelectedCounts (SelectedCount i) (SelectedCount j) = if i == negate j then Nothing else Just $ SelectedCount (i + j)
97−
98−-- | A class that allows sending of 'Query's and retrieval of 'QueryResult's. See 'queryDyn' for a commonly
99−-- used interface.
100−class (Group q, Additive q, Query q) => MonadQuery t q m | m -> q t where
101− tellQueryIncremental :: Incremental t (AdditivePatch q) -> m ()
102− askQueryResult :: m (Dynamic t (QueryResult q))
103− queryIncremental :: Incremental t (AdditivePatch q) -> m (Dynamic t (QueryResult q))
104−
105−instance (Monad m, MonadQuery t q m) => MonadQuery t q (ReaderT r m) where
106− tellQueryIncremental = lift . tellQueryIncremental
107− askQueryResult = lift askQueryResult
108− queryIncremental = lift . queryIncremental
109−
110−-- | Produce and send an 'Incremental' 'Query' from a 'Dynamic' 'Query'.
111−tellQueryDyn :: (Reflex t, MonadQuery t q m) => Dynamic t q -> m ()
112−tellQueryDyn d = tellQueryIncremental $ unsafeBuildIncremental (sample (current d)) $ attachWith (\old new -> AdditivePatch $ new ~~ old) (current d) (updated d)
113−
114−-- | Retrieve 'Dynamic'ally updating 'QueryResult's for a 'Dynamic'ally updating 'Query'.
115−queryDyn :: (Reflex t, Monad m, MonadQuery t q m) => Dynamic t q -> m (Dynamic t (QueryResult q))
116−queryDyn q = do
117− tellQueryDyn q
118− zipDynWith crop q <$> askQueryResult
src/Reflex/Requester/Base.hsdeleted−537
@@ -1,537 +0,0 @@
1−-- | This module provides 'RequesterT', the standard implementation of
2−-- 'Requester'.
3−{-# LANGUAGE AllowAmbiguousTypes #-}
4−{-# LANGUAGE CPP #-}
5−{-# LANGUAGE EmptyDataDecls #-}
6−{-# LANGUAGE ExistentialQuantification #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10−{-# LANGUAGE MultiParamTypeClasses #-}
11−{-# LANGUAGE Rank2Types #-}
12−{-# LANGUAGE RecursiveDo #-}
13−{-# LANGUAGE ScopedTypeVariables #-}
14−{-# LANGUAGE StandaloneDeriving #-}
15−{-# LANGUAGE TypeFamilies #-}
16−{-# LANGUAGE TypeOperators #-}
17−{-# LANGUAGE UndecidableInstances #-}
18−#ifdef USE_REFLEX_OPTIMIZER
19−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20−#endif
21−module Reflex.Requester.Base
22− ( RequesterT (..)
23− , runRequesterT
24− , withRequesterT
25− , runWithReplaceRequesterTWith
26− , traverseIntMapWithKeyWithAdjustRequesterTWith
27− , traverseDMapWithKeyWithAdjustRequesterTWith
28− , RequesterData
29− , RequesterDataKey
30− , traverseRequesterData
31− , forRequesterData
32− , requesterDataToList
33− , singletonRequesterData
34− , matchResponsesWithRequests
35− , multiEntry
36− , unMultiEntry
37− , requesting'
38− ) where
39−
40−import Reflex.Class
41−import Reflex.Adjustable.Class
42−import Reflex.Dynamic
43−import Reflex.Host.Class
44−import Reflex.PerformEvent.Class
45−import Reflex.PostBuild.Class
46−import Reflex.Requester.Class
47−import Reflex.TriggerEvent.Class
48−
49−import Control.Applicative (liftA2)
50−import Control.Monad.Exception
51−import Control.Monad.Identity
52−import Control.Monad.Primitive
53−import Control.Monad.Reader
54−import Control.Monad.Ref
55−import Control.Monad.State.Strict
56−import Data.Bits
57−import Data.Coerce
58−import Data.Dependent.Map (DMap, DSum (..))
59−import qualified Data.Dependent.Map as DMap
60−import Data.Functor.Compose
61−import Data.Functor.Misc
62−import Data.IntMap.Strict (IntMap)
63−import qualified Data.IntMap.Strict as IntMap
64−import Data.Map (Map)
65−import qualified Data.Map as Map
66−import Data.Monoid ((<>))
67−import Data.Proxy
68−import qualified Data.Semigroup as S
69−import Data.Some (Some(Some))
70−import Data.Type.Equality
71−import Data.Unique.Tag
72−
73−import GHC.Exts (Any)
74−import Unsafe.Coerce
75−
76−--TODO: Make this module type-safe
77−
78−newtype TagMap (f :: * -> *) = TagMap (IntMap Any)
79−
80−newtype RequesterData f = RequesterData (TagMap (Entry f))
81−
82−data RequesterDataKey a where
83− RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a
84− RequesterDataKey_Multi :: {-# UNPACK #-} !(MyTag Multi) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a --TODO: Don't put a second Int here (or in the other Multis); use a single Int instead
85− RequesterDataKey_Multi2 :: {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
86− RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
87−
88−singletonRequesterData :: RequesterDataKey a -> f a -> RequesterData f
89−singletonRequesterData rdk v = case rdk of
90− RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v
91− RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v
92− RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
93− RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
94−
95−requesterDataToList :: RequesterData f -> [DSum RequesterDataKey f]
96−requesterDataToList (RequesterData m) = do
97− k :=> Entry e <- tagMapToList m
98− case myKeyType k of
99− MyTagType_Single -> return $ RequesterDataKey_Single k :=> e
100− MyTagType_Multi -> do
101− (k', e') <- IntMap.toList e
102− k'' :=> e'' <- requesterDataToList e'
103− return $ RequesterDataKey_Multi k k' k'' :=> e''
104− MyTagType_Multi2 -> do
105− (k', e') <- Map.toList e
106− (k'', e'') <- IntMap.toList e'
107− k''' :=> e''' <- requesterDataToList e''
108− return $ RequesterDataKey_Multi2 k k' k'' k''' :=> e'''
109− MyTagType_Multi3 -> do
110− (k', e') <- IntMap.toList e
111− (k'', e'') <- IntMap.toList e'
112− k''' :=> e''' <- requesterDataToList e''
113− return $ RequesterDataKey_Multi3 k k' k'' k''' :=> e'''
114−
115−singletonTagMap :: forall f a. MyTag a -> f a -> TagMap f
116−singletonTagMap (MyTag k) v = TagMap $ IntMap.singleton k $ (unsafeCoerce :: f a -> Any) v
117−
118−tagMapToList :: forall f. TagMap f -> [DSum MyTag f]
119−tagMapToList (TagMap m) = f <$> IntMap.toList m
120− where f :: (Int, Any) -> DSum MyTag f
121− f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v
122−
123−traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g)
124−traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m
125− where
126− g :: Int -> Any -> t Any
127− g k v = (unsafeCoerce :: g a -> Any) <$> f (MyTag k) ((unsafeCoerce :: Any -> f a) v)
128−
129−-- | Runs in reverse to accommodate for the fact that we accumulate it in reverse
130−traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response)
131−traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order
132− where go :: forall x. MyTag x -> Entry request x -> m (Entry response x)
133− go k (Entry request) = Entry <$> case myKeyType k of
134− MyTagType_Single -> f request
135− MyTagType_Multi -> traverse (traverseRequesterData f) request
136− MyTagType_Multi2 -> traverse (traverse (traverseRequesterData f)) request
137− MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request
138−
139−-- | 'traverseRequesterData' with its arguments flipped
140−forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response)
141−forRequesterData r f = traverseRequesterData f r
142−
143−data MyTagType :: * -> * where
144− MyTagType_Single :: MyTagType (Single a)
145− MyTagType_Multi :: MyTagType Multi
146− MyTagType_Multi2 :: MyTagType (Multi2 k)
147− MyTagType_Multi3 :: MyTagType Multi3
148−
149−myKeyType :: MyTag x -> MyTagType x
150−myKeyType (MyTag k) = case k .&. 0x3 of
151− 0x0 -> unsafeCoerce MyTagType_Single
152− 0x1 -> unsafeCoerce MyTagType_Multi
153− 0x2 -> unsafeCoerce MyTagType_Multi2
154− 0x3 -> unsafeCoerce MyTagType_Multi3
155− t -> error $ "Reflex.Requester.Base.myKeyType: no such key type" <> show t
156−
157−data Single a
158−data Multi
159−data Multi2 (k :: * -> *)
160−data Multi3
161−
162−class MyTagTypeOffset x where
163− myTagTypeOffset :: proxy x -> Int
164−
165−instance MyTagTypeOffset (Single a) where
166− myTagTypeOffset _ = 0x0
167−
168−instance MyTagTypeOffset Multi where
169− myTagTypeOffset _ = 0x1
170−
171−instance MyTagTypeOffset (Multi2 k) where
172− myTagTypeOffset _ = 0x2
173−
174−instance MyTagTypeOffset Multi3 where
175− myTagTypeOffset _ = 0x3
176−
177−type family EntryContents request a where
178− EntryContents request (Single a) = request a
179− EntryContents request Multi = IntMap (RequesterData request)
180− EntryContents request (Multi2 k) = Map (Some k) (IntMap (RequesterData request))
181− EntryContents request Multi3 = IntMap (IntMap (RequesterData request))
182−
183−newtype Entry request x = Entry { unEntry :: EntryContents request x }
184−
185−{-# INLINE singleEntry #-}
186−singleEntry :: f a -> Entry f (Single a)
187−singleEntry = Entry
188−
189−{-# INLINE multiEntry #-}
190−multiEntry :: IntMap (RequesterData f) -> Entry f Multi
191−multiEntry = Entry
192−
193−{-# INLINE unMultiEntry #-}
194−unMultiEntry :: Entry f Multi -> IntMap (RequesterData f)
195−unMultiEntry = unEntry
196−
197−-- | We use a hack here to pretend we have x ~ request a; we don't want to use a GADT, because GADTs (even with zero-size existential contexts) can't be newtypes
198−-- WARNING: This type should never be exposed. In particular, this is extremely unsound if a MyTag from one run of runRequesterT is ever compared against a MyTag from another
199−newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum)
200−
201−newtype MyTagWrap (f :: * -> *) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum)
202−
203−{-# INLINE castMyTagWrap #-}
204−castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x)
205−castMyTagWrap = coerce
206−
207−instance GEq MyTag where
208− (MyTag a) `geq` (MyTag b) =
209− if a == b
210− then Just $ unsafeCoerce Refl
211− else Nothing
212−
213−instance GCompare MyTag where
214− (MyTag a) `gcompare` (MyTag b) =
215− case a `compare` b of
216− LT -> GLT
217− EQ -> unsafeCoerce GEQ
218− GT -> GGT
219−
220−instance GEq (MyTagWrap f) where
221− (MyTagWrap a) `geq` (MyTagWrap b) =
222− if a == b
223− then Just $ unsafeCoerce Refl
224− else Nothing
225−
226−instance GCompare (MyTagWrap f) where
227− (MyTagWrap a) `gcompare` (MyTagWrap b) =
228− case a `compare` b of
229− LT -> GLT
230− EQ -> unsafeCoerce GEQ
231− GT -> GGT
232−
233−data RequesterState t (request :: * -> *) = RequesterState
234− { _requesterState_nextMyTag :: {-# UNPACK #-} !Int -- Starts at -4 and goes down by 4 each time, to accommodate two 'type' bits at the bottom
235− , _requesterState_requests :: ![(Int, Event t Any)]
236− }
237−
238−-- | A basic implementation of 'Requester'.
239−newtype RequesterT t request (response :: * -> *) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a }
240− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
241−-- MonadAsyncException can't be derived on ghc-8.0.1; we use base-4.9.1 as a proxy for ghc-8.0.2
242−#if MIN_VERSION_base(4,9,1)
243− , MonadAsyncException
244−#endif
245− )
246−
247−deriving instance MonadSample t m => MonadSample t (RequesterT t request response m)
248−deriving instance MonadHold t m => MonadHold t (RequesterT t request response m)
249−deriving instance PostBuild t m => PostBuild t (RequesterT t request response m)
250−deriving instance TriggerEvent t m => TriggerEvent t (RequesterT t request response m)
251−
252−instance PrimMonad m => PrimMonad (RequesterT t request response m) where
253− type PrimState (RequesterT t request response m) = PrimState m
254− primitive = lift . primitive
255−
256−-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
257−instance (Monoid a, Monad m) => Monoid (RequesterT t request response m a) where
258− mempty = pure mempty
259− mappend = liftA2 mappend
260−
261−instance (S.Semigroup a, Monad m) => S.Semigroup (RequesterT t request response m a) where
262− (<>) = liftA2 (S.<>)
263−
264−
265−-- | Run a 'RequesterT' action. The resulting 'Event' will fire whenever
266−-- requests are made, and responses should be provided in the input 'Event'.
267−-- The 'Tag' keys will be used to return the responses to the same place the
268−-- requests were issued.
269−runRequesterT :: (Reflex t, Monad m)
270− => RequesterT t request response m a
271− -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse
272− -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild
273−runRequesterT (RequesterT a) responses = do
274− (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $
275− coerceEvent responses
276− return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s)
277−
278−-- | Map a function over the request and response of a 'RequesterT'
279−withRequesterT
280− :: (Reflex t, MonadFix m)
281− => (forall x. req x -> req' x) -- ^ The function to map over the request
282− -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response
283− -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed
284− -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT'
285−withRequesterT freq frsp child = do
286− rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp'
287− (a, req) <- lift $ runRequesterT child rsp
288− rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $
289− fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req
290− return a
291−
292−instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where
293− type Request (RequesterT t request response m) = request
294− type Response (RequesterT t request response m) = response
295− requesting = fmap coerceEvent . responseFromTag . castMyTagWrap <=< tagRequest . (coerceEvent :: Event t (request a) -> Event t (Entry request (Single a)))
296− requesting_ = void . tagRequest . fmapCheap singleEntry
297−
298−{-# INLINE tagRequest #-}
299−tagRequest :: forall m x t request response. (Monad m, MyTagTypeOffset x) => Event t (Entry request x) -> RequesterT t request response m (MyTagWrap request (Entry request x))
300−tagRequest req = do
301− old <- RequesterT get
302− let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x)
303− t = MyTagWrap n
304− RequesterT $ put $ RequesterState
305− { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4
306− , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old
307− }
308− return t
309−
310−{-# INLINE responseFromTag #-}
311−responseFromTag :: Monad m => MyTagWrap response (Entry response x) -> RequesterT t request response m (Event t (Entry response x))
312−responseFromTag (MyTagWrap t) = do
313− responses :: EventSelectorInt t Any <- RequesterT ask
314− return $ (unsafeCoerce :: Event t Any -> Event t (Entry response x)) $ selectInt responses t
315−
316−instance MonadTrans (RequesterT t request response) where
317− lift = RequesterT . lift . lift
318−
319−instance PerformEvent t m => PerformEvent t (RequesterT t request response m) where
320− type Performable (RequesterT t request response m) = Performable m
321− performEvent_ = lift . performEvent_
322− performEvent = lift . performEvent
323−
324−instance MonadRef m => MonadRef (RequesterT t request response m) where
325− type Ref (RequesterT t request response m) = Ref m
326− newRef = lift . newRef
327− readRef = lift . readRef
328− writeRef r = lift . writeRef r
329−
330−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequesterT t request response m) where
331− newEventWithTrigger = lift . newEventWithTrigger
332− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
333−
334−instance MonadReader r m => MonadReader r (RequesterT t request response m) where
335− ask = lift ask
336− local f (RequesterT a) = RequesterT $ mapStateT (mapReaderT $ local f) a
337− reader = lift . reader
338−
339−instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where
340− runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
341− traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental
342− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
343− traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental
344− traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove
345−
346−requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x))
347−requesting' = responseFromTag . castMyTagWrap <=< tagRequest
348−
349−{-# INLINABLE runWithReplaceRequesterTWith #-}
350−runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m
351− , MonadFix m
352− )
353− => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))
354− -> RequesterT t request response m a
355− -> Event t (RequesterT t request response m b)
356− -> RequesterT t request response m (a, Event t b)
357−runWithReplaceRequesterTWith f a0 a' = do
358− rec na' <- numberOccurrencesFrom 1 a'
359− responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here
360− let responses' = fanInt responses
361− ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na'
362− requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v'
363− return (result0, fmapCheap (fst . snd) v')
364−
365−{-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-}
366−traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p.
367− ( Reflex t
368− , MonadHold t m
369− , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))
370− , Patch (p (Event t (IntMap (RequesterData request))))
371− , Functor p
372− , MonadFix m
373− )
374− => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))
375− -> IntMap (IntMap.Key, v)
376− -> Event t (p (IntMap.Key, v))
377− -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))
378− )
379− -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))
380− -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))
381− -> (IntMap.Key -> v -> RequesterT t request response m v')
382− -> IntMap v
383− -> Event t (p v)
384− -> RequesterT t request response m (IntMap v', Event t (p v'))
385−traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do
386− rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
387− let responses :: EventSelectorInt t (IntMap (RequesterData response))
388− responses = fanInt $ fmapCheap unpack response
389− unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response))
390− unpack = unEntry
391− pack :: IntMap (IntMap (RequesterData request)) -> Entry request Multi3
392− pack = Entry
393− f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v')
394− f' k (n, v) = do
395− (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ selectInt responses k --TODO: Instead of doing mapMaybeCheap, can we share a fanInt across all instances of a given key, or at least the ones that are adjacent in time?
396− return (fmapCheap (IntMap.singleton n) myRequests, result)
397− ndm' <- numberOccurrencesFrom 1 dm'
398− (children0, children') <- base f' (fmap ((,) 0) dm0) $ fmap (\(n, dm) -> fmap ((,) n) dm) ndm' --TODO: Avoid this somehow, probably by adding some sort of per-cohort information passing to Adjustable
399− let result0 = fmap snd children0
400− result' = fforCheap children' $ fmap snd
401− requests0 :: IntMap (Event t (IntMap (RequesterData request)))
402− requests0 = fmap fst children0
403− requests' :: Event t (p (Event t (IntMap (RequesterData request))))
404− requests' = fforCheap children' $ fmap fst
405− promptRequests :: Event t (IntMap (IntMap (RequesterData request)))
406− promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
407− requests <- holdIncremental requests0 requests'
408− return (result0, result')
409−
410−{-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-}
411−traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'.
412− ( GCompare k
413− , Reflex t
414− , MonadHold t m
415− , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))
416− , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))
417− , MonadFix m
418− )
419− => (forall k' v1 v2. GCompare k'
420− => (forall a. k' a -> v1 a -> m (v2 a))
421− -> DMap k' v1
422− -> Event t (p k' v1)
423− -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))
424− )
425− -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)
426− -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)
427− -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)
428− -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))
429− -> (forall a. k a -> v a -> RequesterT t request response m (v' a))
430− -> DMap k v
431− -> Event t (p k v)
432− -> RequesterT t request response m (DMap k v', Event t (p k v'))
433−traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do
434− rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
435− let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response)))
436− responses = fanMap $ fmapCheap unpack response
437− unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response))
438− unpack = unEntry
439− pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k)
440− pack = Entry
441− f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a)
442− f' k (Compose (n, v)) = do
443− (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some k))
444− return $ Compose (fmapCheap (IntMap.singleton n) myRequests, result)
445− ndm' <- numberOccurrencesFrom 1 dm'
446− (children0, children') <- base f' (DMap.map (\v -> Compose (0, v)) dm0) $ fmap (\(n, dm) -> mapPatch (\v -> Compose (n, v)) dm) ndm'
447− let result0 = DMap.map (snd . getCompose) children0
448− result' = fforCheap children' $ mapPatch $ snd . getCompose
449− requests0 :: Map (Some k) (Event t (IntMap (RequesterData request)))
450− requests0 = weakenDMapWith (fst . getCompose) children0
451− requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request))))
452− requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
453− promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request)))
454− promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
455− requests <- holdIncremental requests0 requests'
456− return (result0, result')
457−
458−data Decoder rawResponse response =
459− forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)
460−
461−-- | Matches incoming responses with previously-sent requests
462−-- and uses the provided request "decoder" function to process
463−-- incoming responses.
464−matchResponsesWithRequests
465− :: forall t rawRequest rawResponse request response m.
466− ( MonadFix m
467− , MonadHold t m
468− , Reflex t
469− )
470− => (forall a. request a -> (rawRequest, rawResponse -> response a))
471− -- ^ Given a request (from 'Requester'), produces the wire format of the
472− -- request and a function used to process the associated response
473− -> Event t (RequesterData request)
474− -- ^ The outgoing requests
475− -> Event t (Int, rawResponse)
476− -- ^ The incoming responses, tagged by an identifying key
477− -> m ( Event t (Map Int rawRequest)
478− , Event t (RequesterData response)
479− )
480− -- ^ A map of outgoing wire-format requests and an event of responses keyed
481− -- by the 'RequesterData' key of the associated outgoing request
482−matchResponsesWithRequests f send recv = do
483− rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing
484− waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <-
485− holdIncremental mempty $ leftmost
486− [ fmap (\(_, outstanding, _) -> outstanding) outgoing
487− , snd <$> incoming
488− ]
489− let outgoing = processOutgoing nextId send
490− incoming = processIncoming waitingFor recv
491− return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming)
492− where
493− -- Tags each outgoing request with an identifying integer key
494− -- and returns the next available key, a map of response decoders
495− -- for requests for which there are outstanding responses, and the
496− -- raw requests to be sent out.
497− processOutgoing
498− :: Behavior t Int
499− -- The next available key
500− -> Event t (RequesterData request)
501− -- The outgoing request
502− -> Event t ( Int
503− , PatchMap Int (Decoder rawResponse response)
504− , Map Int rawRequest )
505− -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests
506− processOutgoing nextId out = flip pushAlways out $ \dm -> do
507− oldNextId <- sample nextId
508− let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do
509− n <- get
510− put $ succ n
511− let (rawReq, rspF) = f v
512− return (n, rawReq, Decoder k rspF)
513− patchWaitingFor = PatchMap $ Map.fromList $
514− (\(n, _, dec) -> (n, Just dec)) <$> result
515− toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result
516− return (newNextId, patchWaitingFor, toSend)
517− -- Looks up the each incoming raw response in a map of response
518− -- decoders and returns the decoded response and a patch that can
519− -- be used to clear the ID of the consumed response out of the queue
520− -- of expected responses.
521− processIncoming
522− :: Incremental t (PatchMap Int (Decoder rawResponse response))
523− -- A map of outstanding expected responses
524− -> Event t (Int, rawResponse)
525− -- A incoming response paired with its identifying key
526− -> Event t (RequesterData response, PatchMap Int v)
527− -- The decoded response and a patch that clears the outstanding responses queue
528− processIncoming waitingFor inc = flip push inc $ \(n, rawRsp) -> do
529− wf <- sample $ currentIncremental waitingFor
530− case Map.lookup n wf of
531− Nothing -> return Nothing -- TODO How should lookup failures be handled here? They shouldn't ever happen..
532− Just (Decoder k rspF) -> do
533− let rsp = rspF rawRsp
534− return $ Just
535− ( singletonRequesterData k rsp
536− , PatchMap $ Map.singleton n Nothing
537− )
src/Reflex/Requester/Class.hsdeleted−72
@@ -1,72 +0,0 @@
1−-- | This module defines 'Requester', which indicates that an action can make
2−-- requests and receive responses to them. Typically, this is used for things
3−-- like a WebSocket, where it's desirable to collect many potential sources of
4−-- events and send them over a single channel, then distribute the results back
5−-- out efficiently to their original request sites.
6−{-# LANGUAGE CPP #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
9−{-# LANGUAGE RecursiveDo #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−#ifdef USE_REFLEX_OPTIMIZER
13−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
14−#endif
15−module Reflex.Requester.Class
16− ( Requester (..)
17− , withRequesting
18− , requestingIdentity
19− ) where
20−
21−import Control.Monad.Identity
22−import Control.Monad.Reader
23−import qualified Control.Monad.State.Lazy as Lazy
24−import Control.Monad.State.Strict
25−import Reflex.Class
26−
27−-- | A 'Requester' action can trigger requests of type @Request m a@ based on
28−-- 'Event's, and receive responses of type @Response m a@ in return. Note that
29−-- the @a@ type can vary within the 'Requester' action, but will be linked for a
30−-- given request. For example, if @Request m@ is 'IO' and @Response m@ is
31−-- 'Identity', then 'requestingIdentity' has the same type as
32−-- 'Reflex.PerformEvent.Class.performEvent'.
33−class (Reflex t, Monad m) => Requester t m | m -> t where
34− -- | The type of requests that this 'Requester' can emit
35− type Request m :: * -> *
36− -- | The type of responses that this 'Requester' can receive
37− type Response m :: * -> *
38− -- | Emit a request whenever the given 'Event' fires, and return responses in
39− -- the resulting 'Event'.
40− requesting :: Event t (Request m a) -> m (Event t (Response m a))
41− -- | Emit a request whenever the given 'Event' fires, and ignore all responses.
42− requesting_ :: Event t (Request m a) -> m ()
43−
44−
45−instance Requester t m => Requester t (ReaderT r m) where
46− type Request (ReaderT r m) = Request m
47− type Response (ReaderT r m) = Response m
48− requesting = lift . requesting
49− requesting_ = lift . requesting_
50−
51−instance Requester t m => Requester t (StateT s m) where
52− type Request (StateT s m) = Request m
53− type Response (StateT s m) = Response m
54− requesting = lift . requesting
55− requesting_ = lift . requesting_
56−
57−instance Requester t m => Requester t (Lazy.StateT s m) where
58− type Request (Lazy.StateT s m) = Request m
59− type Response (Lazy.StateT s m) = Response m
60− requesting = lift . requesting
61− requesting_ = lift . requesting_
62−
63−-- | Emit a request whenever the given 'Event' fires, and unwrap the responses
64−-- before returning them. @Response m@ must be 'Identity'.
65−requestingIdentity :: (Requester t m, Response m ~ Identity) => Event t (Request m a) -> m (Event t a)
66−requestingIdentity = fmap coerceEvent . requesting
67−
68−withRequesting :: (Requester t m, MonadFix m) => (Event t (Response m a) -> m (Event t (Request m a), r)) -> m r
69−withRequesting f = do
70− rec response <- requesting request
71− (request, result) <- f response
72− return result
src/Reflex/Spider.hsdeleted−20
@@ -1,20 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−-- |
3−-- Module:
4−-- Reflex.Spider
5−-- Description:
6−-- This module exports all of the user-facing functionality of the 'Spider' 'Reflex' engine
7−module Reflex.Spider
8− ( Spider
9− , SpiderTimeline
10− , Global
11− , SpiderHost
12− , runSpiderHost
13− , runSpiderHostForTimeline
14− , newSpiderTimeline
15− , withSpiderTimeline
16− -- * Deprecated
17− , SpiderEnv
18− ) where
19−
20−import Reflex.Spider.Internal
src/Reflex/Spider/Internal.hsdeleted−2716
@@ -1,2716 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE ExistentialQuantification #-}
6−{-# LANGUAGE FlexibleContexts #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
9−{-# LANGUAGE GADTs #-}
10−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11−{-# LANGUAGE LambdaCase #-}
12−{-# LANGUAGE MultiWayIf #-}
13−{-# LANGUAGE RankNTypes #-}
14−{-# LANGUAGE RoleAnnotations #-}
15−{-# LANGUAGE ScopedTypeVariables #-}
16−{-# LANGUAGE TypeFamilies #-}
17−{-# LANGUAGE TypeOperators #-}
18−{-# LANGUAGE UndecidableInstances #-}
19−{-# LANGUAGE PolyKinds #-}
20−{-# LANGUAGE DeriveFunctor #-}
21−{-# LANGUAGE StandaloneDeriving #-}
22−{-# LANGUAGE InstanceSigs #-}
23−
24−#ifdef USE_REFLEX_OPTIMIZER
25−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
26−#endif
27−{-# OPTIONS_GHC -Wunused-binds #-}
28−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
29−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
30−module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
31−
32−#if MIN_VERSION_base(4,10,0)
33−import Control.Applicative (liftA2)
34−#endif
35−import Control.Concurrent
36−import Control.Exception
37−import Control.Monad hiding (forM, forM_, mapM, mapM_)
38−import Control.Monad.Exception
39−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
40−import Control.Monad.Primitive
41−--import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
42−import Control.Monad.Reader.Class
43−import Control.Monad.IO.Class
44−import Control.Monad.ReaderIO
45−import Control.Monad.Ref
46−import Data.Align
47−import Data.Coerce
48−import Data.Dependent.Map (DMap, DSum (..))
49−import qualified Data.Dependent.Map as DMap
50−import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
51−import qualified Data.FastMutableIntMap as FastMutableIntMap
52−import Data.Foldable hiding (concat, elem, sequence_)
53−import Data.Functor.Constant
54−import Data.Functor.Misc
55−import Data.Functor.Product
56−import Data.GADT.Compare
57−import Data.IntMap.Strict (IntMap)
58−import qualified Data.IntMap.Strict as IntMap
59−import Data.IORef
60−import Data.Kind (Type)
61−import Data.Maybe hiding (mapMaybe)
62−import Data.Monoid ((<>))
63−import Data.Proxy
64−import Data.These
65−import Data.Traversable
66−import Data.Witherable (Filterable, mapMaybe)
67−import GHC.Exts
68−import GHC.IORef (IORef (..))
69−import GHC.Stack
70−import Reflex.FastWeak
71−import System.IO.Unsafe
72−import System.Mem.Weak
73−import Unsafe.Coerce
74−
75−#ifdef MIN_VERSION_semialign
76−#if MIN_VERSION_these(0,8,0)
77−import Data.These.Combinators (justThese)
78−#endif
79−#if MIN_VERSION_semialign(1,1,0)
80−import Data.Zip (Zip (..))
81−#endif
82−#endif
83−
84−#ifdef DEBUG_CYCLES
85−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
86−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
87−import qualified Data.List.NonEmpty as NonEmpty
88−import Data.Monoid (mempty)
89−import Data.Tree (Forest, Tree (..), drawForest)
90−#endif
91−
92−import Data.FastWeakBag (FastWeakBag)
93−import qualified Data.FastWeakBag as FastWeakBag
94−import Data.Reflection
95−import Data.Some (Some(Some))
96−import Data.Type.Coercion
97−import Data.Profunctor.Unsafe ((#.), (.#))
98−import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
99−import qualified Data.WeakBag as WeakBag
100−import qualified Reflex.Class
101−import qualified Reflex.Class as R
102−import qualified Reflex.Host.Class
103−import Reflex.NotReady.Class
104−import Reflex.Patch
105−import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
106−import Reflex.PerformEvent.Base (PerformEventT)
107−
108−#ifdef DEBUG_TRACE_EVENTS
109−import qualified Data.ByteString.Char8 as BS8
110−import System.IO (stderr)
111−#endif
112−
113−#ifdef DEBUG_TRACE_EVENTS
114−
115−withStackOneLine :: (BS8.ByteString -> a) -> a
116−withStackOneLine expr = unsafePerformIO $ do
117− stack <- currentCallStack
118− return (expr (BS8.pack (unwords (reverse stack))))
119−
120−#endif
121−
122−debugPropagate :: Bool
123−
124−debugInvalidateHeight :: Bool
125−
126−debugInvalidate :: Bool
127−
128−#ifdef DEBUG
129−
130−#define DEBUG_NODEIDS
131−
132−debugPropagate = True
133−
134−debugInvalidateHeight = False
135−
136−debugInvalidate = True
137−
138−class HasNodeId a where
139− getNodeId :: a -> Int
140−
141−instance HasNodeId (Hold x p a) where
142− getNodeId = holdNodeId
143−
144−instance HasNodeId (PushSubscribed x a b) where
145− getNodeId = pushSubscribedNodeId
146−
147−instance HasNodeId (SwitchSubscribed x a) where
148− getNodeId = switchSubscribedNodeId
149−
150−instance HasNodeId (FanSubscribed x a) where
151− getNodeId = fanSubscribedNodeId
152−
153−instance HasNodeId (CoincidenceSubscribed x a) where
154− getNodeId = coincidenceSubscribedNodeId
155−
156−instance HasNodeId (RootSubscribed x a) where
157− getNodeId = rootSubscribedNodeId
158−
159−instance HasNodeId (Pull x a) where
160− getNodeId = pullNodeId
161−
162−{-# INLINE showNodeId #-}
163−showNodeId :: HasNodeId a => a -> String
164−showNodeId = ("#"<>) . show . getNodeId
165−
166−showSubscriberType :: Subscriber x a -> String
167−showSubscriberType = \case
168− SubscriberPush _ _ -> "SubscriberPush"
169− SubscriberMerge _ _ -> "SubscriberMerge"
170− SubscriberFan _ -> "SubscriberFan"
171− SubscriberMergeChange _ -> "SubscriberMergeChange"
172− SubscriberHold _ -> "SubscriberHold"
173− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
174− SubscriberSwitch _ -> "SubscriberSwitch"
175− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
176− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
177− SubscriberHandle -> "SubscriberHandle"
178−
179−showEventType :: Event x a -> String
180−showEventType = \case
181− EventRoot _ _ -> "EventRoot"
182− EventNever -> "EventNever"
183− EventPush _ -> "EventPush"
184− EventMerge _ -> "EventMerge"
185− EventFan _ _ -> "EventFan"
186− EventSwitch _ -> "EventSwitch"
187− EventCoincidence _ -> "EventCoincidence"
188− EventHold _ -> "EventHold"
189− EventDyn _ -> "EventDyn"
190− EventHoldIdentity _ -> "EventHoldIdentity"
191− EventDynIdentity _ -> "EventDynIdentity"
192−
193−#else
194−
195−debugPropagate = False
196−
197−debugInvalidateHeight = False
198−
199−debugInvalidate = False
200−
201−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
202−{-# INLINE showNodeId #-}
203−showNodeId :: a -> String
204−showNodeId _ = ""
205−
206−#endif
207−
208−#ifdef DEBUG_NODEIDS
209−{-# NOINLINE nextNodeIdRef #-}
210−nextNodeIdRef :: IORef Int
211−nextNodeIdRef = unsafePerformIO $ newIORef 1
212−
213−newNodeId :: IO Int
214−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
215−#endif
216−
217−--------------------------------------------------------------------------------
218−-- EventSubscription
219−--------------------------------------------------------------------------------
220−
221−--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
222−-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
223−data EventSubscription x = EventSubscription
224− { _eventSubscription_unsubscribe :: !(IO ())
225− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
226− }
227−
228−unsubscribe :: EventSubscription x -> IO ()
229−unsubscribe (EventSubscription u _) = u
230−
231−--------------------------------------------------------------------------------
232−-- Event
233−--------------------------------------------------------------------------------
234−
235−newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
236−
237−{-# INLINE subscribeAndRead #-}
238−subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
239−subscribeAndRead = unEvent
240−
241−{-# RULES
242−"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
243−"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
244−"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
245− #-}
246−
247−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
248−-- caching; if the computation function is very cheap, this is (much) more
249−-- efficient than 'push'
250−{-# INLINE [1] pushCheap #-}
251−pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
252−pushCheap !f e = Event $ \sub -> do
253− (subscription, occ) <- subscribeAndRead e $ sub
254− { subscriberPropagate = \a -> do
255− mb <- f a
256− mapM_ (subscriberPropagate sub) mb
257− }
258− occ' <- join <$> mapM f occ
259− return (subscription, occ')
260−
261−-- | A subscriber that never triggers other 'Event's
262−{-# INLINE terminalSubscriber #-}
263−terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
264−terminalSubscriber p = Subscriber
265− { subscriberPropagate = p
266− , subscriberInvalidateHeight = \_ -> return ()
267− , subscriberRecalculateHeight = \_ -> return ()
268− }
269−
270−-- | Subscribe to an Event only for the duration of one occurrence
271−{-# INLINE subscribeAndReadHead #-}
272−subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
273−subscribeAndReadHead e sub = do
274− subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
275− (subscription, occ) <- subscribeAndRead e $ sub
276− { subscriberPropagate = \a -> do
277− liftIO $ unsubscribe =<< readIORef subscriptionRef
278− subscriberPropagate sub a
279− }
280− liftIO $ case occ of
281− Nothing -> writeIORef subscriptionRef $! subscription
282− Just _ -> unsubscribe subscription
283− return (subscription, occ)
284−
285−--TODO: Make this lazy in its input event
286−headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
287−headE originalE = do
288− parent <- liftIO $ newIORef $ Just originalE
289− defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
290− let clearParent = liftIO $ writeIORef parent Nothing
291− (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
292− when (isJust occ) clearParent
293− return $ Event $ \sub -> do
294− liftIO (readIORef parent) >>= \case
295− Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
296− Just e -> subscribeAndReadHead e sub
297−
298−data CacheSubscribed x a
299− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
300− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
301− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
302− }
303−
304−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
305−-- repeatedly
306−--
307−--TODO: Try a caching strategy where we subscribe directly to the parent when
308−--there's only one subscriber, and then build our own FastWeakBag only when a second
309−--subscriber joins
310−{-# NOINLINE [0] cacheEvent #-}
311−cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
312−cacheEvent e =
313−#ifdef DEBUG_TRACE_EVENTS
314− withStackOneLine $ \callSite -> Event $
315−#else
316− Event $
317−#endif
318− unsafePerformIO $ do
319− mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
320− <- newIORef emptyFastWeak
321− pure $ \sub -> {-# SCC "cacheEvent" #-} do
322−#ifdef DEBUG_TRACE_EVENTS
323− unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
324−#endif
325− subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
326− Just subscribedTicket -> return subscribedTicket
327− Nothing -> do
328− subscribers <- liftIO FastWeakBag.empty
329− occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
330− (parentSub, occ) <- subscribeAndRead e $ Subscriber
331− { subscriberPropagate = \a -> do
332− liftIO $ writeIORef occRef $ Just a
333− scheduleClear occRef
334− propagateFast a subscribers
335− , subscriberInvalidateHeight = \old -> do
336− FastWeakBag.traverse_ subscribers $ invalidateSubscriberHeight old
337− , subscriberRecalculateHeight = \new -> do
338− FastWeakBag.traverse_ subscribers $ recalculateSubscriberHeight new
339− }
340− when (isJust occ) $ do
341− liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
342− scheduleClear occRef
343− let !subscribed = CacheSubscribed
344− { _cacheSubscribed_subscribers = subscribers
345− , _cacheSubscribed_parent = parentSub
346− , _cacheSubscribed_occurrence = occRef
347− }
348− subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
349− liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
350− return subscribedTicket
351− liftIO $ do
352− subscribed <- getFastWeakTicketValue subscribedTicket
353− ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
354− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
355− let es = EventSubscription
356− { _eventSubscription_unsubscribe = do
357− FastWeakBag.remove ticket
358− isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
359− when isEmpty $ do
360− writeIORef mSubscribedRef emptyFastWeak
361− unsubscribe $ _cacheSubscribed_parent subscribed
362− touch ticket
363− touch subscribedTicket
364− , _eventSubscription_subscribed = EventSubscribed
365− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
366− , eventSubscribedRetained = toAny subscribedTicket
367− }
368− }
369− return (es, occ)
370−
371−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
372−subscribe e s = fst <$> subscribeAndRead e s
373−
374−{-# INLINE wrap #-}
375−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
376−wrap tag getSpecificSubscribed sub = do
377− (sln, subd, occ) <- getSpecificSubscribed sub
378− let es = tag subd
379− return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
380−
381−eventRoot :: GCompare k => k a -> Root x k -> Event x a
382−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
383−
384−eventNever :: Event x a
385−eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
386−
387−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
388−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
389−
390−eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
391−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
392−
393−eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
394−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
395−
396−eventHold :: Hold x p -> Event x p
397−eventHold !h = Event $ subscribeHoldEvent h
398−
399−eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
400−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
401−
402−{-# INLINE subscribeCoincidenceInner #-}
403−subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
404−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
405− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
406− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
407− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
408− let height = max innerHeight outerHeight
409− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
410− return (innerOcc, height, innerSubd)
411−
412−--------------------------------------------------------------------------------
413−-- Subscriber
414−--------------------------------------------------------------------------------
415−
416−data Subscriber x a = Subscriber
417− { subscriberPropagate :: !(a -> EventM x ())
418− , subscriberInvalidateHeight :: !(Height -> IO ())
419− , subscriberRecalculateHeight :: !(Height -> IO ())
420− }
421−
422−--TODO: Move this comment to WeakBag
423−-- These function are constructor functions that are marked NOINLINE so they are
424−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
425−-- so any weak references that are attached to the constructors will have their
426−-- finalizer run. Using the opaque constructor, does not see the
427−-- constructor application, so it behaves like an IORef and cannot be fused away.
428−--
429−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
430−-- the weak pointer to it in some cases.
431−
432−newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
433−newSubscriberHold h = return $ Subscriber
434− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
435− , subscriberInvalidateHeight = \_ -> return ()
436− , subscriberRecalculateHeight = \_ -> return ()
437− }
438−
439−newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
440−newSubscriberFan subscribed = return $ Subscriber
441− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
442− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
443− tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
444− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
445− scheduleClear $ fanSubscribedOccurrence subscribed
446− let f _ (Pair v subsubs) = do
447− propagate v $ _fanSubscribedChildren_list subsubs
448− return $ Constant ()
449− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
450− return ()
451− , subscriberInvalidateHeight = \old -> do
452− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
453− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
454− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
455− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
456− , subscriberRecalculateHeight = \new -> do
457− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
458− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
459− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
460− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
461− }
462−
463−newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
464−newSubscriberSwitch subscribed = return $ Subscriber
465− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
466− tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
467− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
468− scheduleClear $ switchSubscribedOccurrence subscribed
469− propagate a $ switchSubscribedSubscribers subscribed
470− , subscriberInvalidateHeight = \_ -> do
471− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
472− oldHeight <- readIORef $ switchSubscribedHeight subscribed
473− when (oldHeight /= invalidHeight) $ do
474− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
475− WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
476− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
477− , subscriberRecalculateHeight = \new -> do
478− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
479− updateSwitchHeight new subscribed
480− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
481− }
482−
483−newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
484−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
485− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
486− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
487− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
488− tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
489− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
490− tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
491− tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
492− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
493− scheduleClear $ coincidenceSubscribedInnerParent subscribed
494− case occ of
495− Nothing -> do
496− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
497− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
498− WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
499− WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
500− Just o -> do -- Since it's already firing, no need to adjust height
501− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
502− scheduleClear $ coincidenceSubscribedOccurrence subscribed
503− propagate o $ coincidenceSubscribedSubscribers subscribed
504− , subscriberInvalidateHeight = \_ -> do
505− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
506− invalidateCoincidenceHeight subscribed
507− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
508− , subscriberRecalculateHeight = \_ -> do
509− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
510− recalculateCoincidenceHeight subscribed
511− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
512− }
513−
514−newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
515−newSubscriberCoincidenceInner subscribed = return $ Subscriber
516− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
517− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
518− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
519− case occ of
520− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
521− Nothing -> do
522− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
523− scheduleClear $ coincidenceSubscribedOccurrence subscribed
524− propagate a $ coincidenceSubscribedSubscribers subscribed
525− , subscriberInvalidateHeight = \_ -> do
526− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
527− invalidateCoincidenceHeight subscribed
528− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
529− , subscriberRecalculateHeight = \_ -> do
530− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
531− recalculateCoincidenceHeight subscribed
532− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
533− }
534−
535−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
536−invalidateSubscriberHeight = flip subscriberInvalidateHeight
537−
538−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
539−recalculateSubscriberHeight = flip subscriberRecalculateHeight
540−
541−-- | Propagate everything at the current height
542−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
543−propagate a subscribers = withIncreasedDepth $ do
544− -- Note: in the following traversal, we do not visit nodes that are added to the list during our traversal; they are new events, which will necessarily have full information already, so there is no need to traverse them
545− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
546− WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
547−
548−-- | Propagate everything at the current height
549−propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
550−propagateFast a subscribers = withIncreasedDepth $ do
551− -- Note: in the following traversal, we do not visit nodes that are added to the list during our traversal; they are new events, which will necessarily have full information already, so there is no need to traverse them
552− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
553− FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
554−
555−--------------------------------------------------------------------------------
556−-- EventSubscribed
557−--------------------------------------------------------------------------------
558−
559−toAny :: a -> Any
560−toAny = unsafeCoerce
561−
562−-- Why do we use Any here, instead of just giving eventSubscribedRetained an
563−-- existential type? Sadly, GHC does not currently know how to unbox types
564−-- with existentially quantified fields. So instead we just coerce values
565−-- to type Any on the way in. Since we never coerce them back, this is
566−-- perfectly safe.
567−data EventSubscribed x = EventSubscribed
568− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
569− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
570−#ifdef DEBUG_CYCLES
571− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
572− , eventSubscribedHasOwnHeightRef :: !Bool
573− , eventSubscribedWhoCreated :: !(IO [String])
574−#endif
575− }
576−
577−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
578−eventSubscribedRoot !r = EventSubscribed
579− { eventSubscribedHeightRef = zeroRef
580− , eventSubscribedRetained = toAny r
581−#ifdef DEBUG_CYCLES
582− , eventSubscribedGetParents = return []
583− , eventSubscribedHasOwnHeightRef = False
584− , eventSubscribedWhoCreated = return ["root"]
585−#endif
586− }
587−
588−eventSubscribedNever :: EventSubscribed x
589−eventSubscribedNever = EventSubscribed
590− { eventSubscribedHeightRef = zeroRef
591− , eventSubscribedRetained = toAny ()
592−#ifdef DEBUG_CYCLES
593− , eventSubscribedGetParents = return []
594− , eventSubscribedHasOwnHeightRef = False
595− , eventSubscribedWhoCreated = return ["never"]
596−#endif
597− }
598−
599−eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
600−eventSubscribedFan !subscribed = EventSubscribed
601− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
602− , eventSubscribedRetained = toAny subscribed
603−#ifdef DEBUG_CYCLES
604− , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
605− , eventSubscribedHasOwnHeightRef = False
606− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
607−#endif
608− }
609−
610−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
611−eventSubscribedSwitch !subscribed = EventSubscribed
612− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
613− , eventSubscribedRetained = toAny subscribed
614−#ifdef DEBUG_CYCLES
615− , eventSubscribedGetParents = do
616− s <- readIORef $ switchSubscribedCurrentParent subscribed
617− return [Some $ _eventSubscription_subscribed s]
618− , eventSubscribedHasOwnHeightRef = True
619− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
620−#endif
621− }
622−
623−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
624−eventSubscribedCoincidence !subscribed = EventSubscribed
625− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
626− , eventSubscribedRetained = toAny subscribed
627−#ifdef DEBUG_CYCLES
628− , eventSubscribedGetParents = do
629− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
630− let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
631− innerParents = maybeToList $ fmap Some innerSubscription
632− return $ outerParent : innerParents
633− , eventSubscribedHasOwnHeightRef = True
634− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
635−#endif
636− }
637−
638−getEventSubscribedHeight :: EventSubscribed x -> IO Height
639−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
640−
641−#ifdef DEBUG_CYCLES
642−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
643−whoCreatedEventSubscribed = eventSubscribedWhoCreated
644−
645−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
646−walkInvalidHeightParents s0 = do
647− subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
648− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
649− when (h == invalidHeight) $ do
650− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
651− modify (Some s :)
652− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
653− forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
654− return subscribers
655−#endif
656−
657−{-# INLINE subscribeHoldEvent #-}
658−subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
659−subscribeHoldEvent = subscribeAndRead . holdEvent
660−
661−--------------------------------------------------------------------------------
662−-- Behavior
663−--------------------------------------------------------------------------------
664−
665−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
666−
667−behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
668−behaviorHold !h = Behavior $ readHoldTracked h
669−
670−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
671−behaviorHoldIdentity = behaviorHold
672−
673−behaviorConst :: a -> Behavior x a
674−behaviorConst !a = Behavior $ return a
675−
676−behaviorPull :: Pull x a -> Behavior x a
677−behaviorPull !p = Behavior $ do
678− val <- liftIO $ readIORef $ pullValue p
679− case val of
680− Just subscribed -> do
681− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
682− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
683− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
684− return $ pullSubscribedValue subscribed
685− Nothing -> do
686− i <- liftIO $ newInvalidatorPull p
687− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
688− parentsRef <- liftIO $ newIORef []
689− holdInits <- askBehaviorHoldInits
690− a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
691− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
692− parents <- liftIO $ readIORef parentsRef
693− let subscribed = PullSubscribed
694− { pullSubscribedValue = a
695− , pullSubscribedInvalidators = invsRef
696− , pullSubscribedOwnInvalidator = i
697− , pullSubscribedParents = parents
698− }
699− liftIO $ writeIORef (pullValue p) $ Just subscribed
700− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
701− return a
702−
703−behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
704−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
705−
706−{-# INLINE readHoldTracked #-}
707−readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
708−readHoldTracked h = do
709− result <- liftIO $ readIORef $ holdValue h
710− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
711− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
712− liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
713− return result
714−
715−{-# INLINABLE readBehaviorUntracked #-}
716−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
717−readBehaviorUntracked b = do
718− holdInits <- getDeferralQueue
719− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
720−
721−--------------------------------------------------------------------------------
722−-- Dynamic
723−--------------------------------------------------------------------------------
724−
725−type DynamicS x p = Dynamic x (PatchTarget p) p
726−
727−data Dynamic x target p = Dynamic
728− { dynamicCurrent :: !(Behavior x target)
729− , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
730− }
731−
732−deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
733−
734−
735−
736−
737−dynamicHold :: Hold x p -> DynamicS x p
738−dynamicHold !h = Dynamic
739− { dynamicCurrent = behaviorHold h
740− , dynamicUpdated = eventHold h
741− }
742−
743−dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
744−dynamicHoldIdentity = dynamicHold
745−
746−dynamicConst :: PatchTarget p -> DynamicS x p
747−dynamicConst !a = Dynamic
748− { dynamicCurrent = behaviorConst a
749− , dynamicUpdated = eventNever
750− }
751−
752−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
753−dynamicDyn !d = Dynamic
754− { dynamicCurrent = behaviorDyn d
755− , dynamicUpdated = eventDyn d
756− }
757−
758−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
759−dynamicDynIdentity = dynamicDyn
760−
761−--------------------------------------------------------------------------------
762−-- Combinators
763−--------------------------------------------------------------------------------
764−
765−--type role Hold representational
766−data Hold x p
767− = Hold { holdValue :: !(IORef (PatchTarget p))
768− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
769− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
770− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
771−#ifdef DEBUG_NODEIDS
772− , holdNodeId :: Int
773−#endif
774− }
775−
776−-- | A statically allocated 'SpiderTimeline'
777−data Global
778−
779−{-# NOINLINE globalSpiderTimelineEnv #-}
780−globalSpiderTimelineEnv :: SpiderTimelineEnv Global
781−globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
782−
783−-- | Stores all global data relevant to a particular Spider timeline; only one
784−-- value should exist for each type @x@
785−newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
786−-- We implement SpiderTimelineEnv with a newtype wrapper so
787−-- we can get the coercions we want safely.
788−type role SpiderTimelineEnv nominal
789−
790−data SpiderTimelineEnv' x = SpiderTimelineEnv
791− { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
792− , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
793−#ifdef DEBUG
794− , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
795−#endif
796− }
797−type role SpiderTimelineEnv' phantom
798−
799−instance Eq (SpiderTimelineEnv x) where
800− _ == _ = True -- Since only one exists of each type
801−
802−instance GEq SpiderTimelineEnv where
803− a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
804− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
805− else Nothing
806−
807−data EventEnv x
808− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
809− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
810− , eventEnvDynInits :: !(IORef [SomeDynInit x])
811− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
812− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
813− , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
814− , eventEnvIntClears :: !(IORef [Some IntClear])
815− , eventEnvRootClears :: !(IORef [Some RootClear])
816− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
817− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
818− , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
819− }
820−
821−{-# INLINE runEventM #-}
822−runEventM :: EventM x a -> IO a
823−runEventM = unEventM
824−
825−asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
826−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
827−
828−class MonadIO m => Defer a m where
829− getDeferralQueue :: m (IORef [a])
830−
831−{-# INLINE defer #-}
832−defer :: Defer a m => a -> m ()
833−defer a = do
834− q <- getDeferralQueue
835− liftIO $ modifyIORef' q (a:)
836−
837−instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
838− {-# INLINE getDeferralQueue #-}
839− getDeferralQueue = asksEventEnv eventEnvAssignments
840−
841−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
842− {-# INLINE getDeferralQueue #-}
843− getDeferralQueue = asksEventEnv eventEnvHoldInits
844−
845−instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
846− {-# INLINE getDeferralQueue #-}
847− getDeferralQueue = asksEventEnv eventEnvDynInits
848−
849−instance Defer (SomeHoldInit x) (BehaviorM x) where
850− {-# INLINE getDeferralQueue #-}
851− getDeferralQueue = BehaviorM $ asks snd
852−
853−instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
854− {-# INLINE getDeferralQueue #-}
855− getDeferralQueue = asksEventEnv eventEnvMergeUpdates
856−
857−instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
858− {-# INLINE getDeferralQueue #-}
859− getDeferralQueue = asksEventEnv eventEnvMergeInits
860−
861−class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
862− getCurrentHeight :: m Height
863− scheduleMerge :: Height -> EventM x () -> m ()
864−
865−instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
866− {-# INLINE getCurrentHeight #-}
867− getCurrentHeight = do
868− heightRef <- asksEventEnv eventEnvCurrentHeight
869− liftIO $ readIORef heightRef
870− {-# INLINE scheduleMerge #-}
871− scheduleMerge height subscribed = do
872− delayedRef <- asksEventEnv eventEnvDelayedMerges
873− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
874−
875−class HasSpiderTimeline x where
876− -- | Retrieve the current SpiderTimelineEnv
877− spiderTimeline :: SpiderTimelineEnv x
878−
879−instance HasSpiderTimeline Global where
880− spiderTimeline = globalSpiderTimelineEnv
881−
882−putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
883−putCurrentHeight h = do
884− heightRef <- asksEventEnv eventEnvCurrentHeight
885− liftIO $ writeIORef heightRef $! h
886−
887−instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
888− {-# INLINE getDeferralQueue #-}
889− getDeferralQueue = asksEventEnv eventEnvClears
890−
891−{-# INLINE scheduleClear #-}
892−scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
893−scheduleClear r = defer $ Some $ Clear r
894−
895−instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
896− {-# INLINE getDeferralQueue #-}
897− getDeferralQueue = asksEventEnv eventEnvIntClears
898−
899−{-# INLINE scheduleIntClear #-}
900−scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
901−scheduleIntClear r = defer $ Some $ IntClear r
902−
903−instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
904− {-# INLINE getDeferralQueue #-}
905− getDeferralQueue = asksEventEnv eventEnvRootClears
906−
907−{-# INLINE scheduleRootClear #-}
908−scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
909−scheduleRootClear r = defer $ Some $ RootClear r
910−
911−instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
912− {-# INLINE getDeferralQueue #-}
913− getDeferralQueue = asksEventEnv eventEnvResetCoincidences
914−
915−-- Note: hold cannot examine its event until after the phase is over
916−{-# INLINE [1] hold #-}
917−hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
918−hold v0 e = do
919− valRef <- liftIO $ newIORef v0
920− invsRef <- liftIO $ newIORef []
921− parentRef <- liftIO $ newIORef Nothing
922−#ifdef DEBUG_NODEIDS
923− nodeId <- liftIO newNodeId
924−#endif
925− let h = Hold
926− { holdValue = valRef
927− , holdInvalidators = invsRef
928− , holdEvent = e
929− , holdParent = parentRef
930−#ifdef DEBUG_NODEIDS
931− , holdNodeId = nodeId
932−#endif
933− }
934− defer $ SomeHoldInit h
935− return h
936−
937−{-# INLINE getHoldEventSubscription #-}
938−getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
939−getHoldEventSubscription h = do
940− ep <- liftIO $ readIORef $ holdParent h
941− case ep of
942− Just subd -> return subd
943− Nothing -> do
944− let e = holdEvent h
945− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
946− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
947− liftIO $ writeIORef subscriptionRef $! subscription
948− case occ of
949− Nothing -> return ()
950− Just o -> do
951− old <- liftIO $ readIORef $ holdValue h
952− case apply o old of
953− Nothing -> return ()
954− Just new -> do
955− -- Need to evaluate these so that we don't retain the Hold itself
956− v <- liftIO $ evaluate $ holdValue h
957− i <- liftIO $ evaluate $ holdInvalidators h
958− defer $ SomeAssignment v i new
959− liftIO $ writeIORef (holdParent h) $ Just subscription
960− return subscription
961−
962−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
963−
964−-- BehaviorM can sample behaviors
965−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
966− deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
967−
968−instance Monad (BehaviorM x) where
969− {-# INLINE (>>=) #-}
970− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
971− {-# INLINE (>>) #-}
972− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
973− {-# INLINE return #-}
974− return x = BehaviorM $ return x
975− {-# INLINE fail #-}
976− fail s = BehaviorM $ fail s
977−
978−data BehaviorSubscribed x a
979− = forall p. BehaviorSubscribedHold (Hold x p)
980− | BehaviorSubscribedPull (PullSubscribed x a)
981−
982−newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
983−
984−--type role PullSubscribed representational
985−data PullSubscribed x a
986− = PullSubscribed { pullSubscribedValue :: !a
987− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
988− , pullSubscribedOwnInvalidator :: !(Invalidator x)
989− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
990− }
991−
992−--type role Pull representational
993−data Pull x a
994− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
995− , pullCompute :: !(BehaviorM x a)
996−#ifdef DEBUG_NODEIDS
997− , pullNodeId :: Int
998−#endif
999− }
1000−
1001−data Invalidator x
1002− = forall a. InvalidatorPull (Pull x a)
1003− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
1004−
1005−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1006− { rootSubscribedKey :: !(k a)
1007− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1008− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1009− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1010− , rootSubscribedUninit :: IO ()
1011− , rootSubscribedWeakSelf :: !(IORef (Weak (RootSubscribed x a))) --TODO: Can we make this a lazy non-IORef and then force it manually to avoid an indirection each time we use it?
1012−#ifdef DEBUG_NODEIDS
1013− , rootSubscribedNodeId :: Int
1014−#endif
1015− }
1016−
1017−data Root x k
1018− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1019− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1020− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1021− }
1022−
1023−data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1024−
1025−data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1026−
1027−data SomeMergeUpdate x = SomeMergeUpdate
1028− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1029− , _someMergeUpdate_invalidateHeight :: !(IO ())
1030− , _someMergeUpdate_recalculateHeight :: !(IO ())
1031− }
1032−
1033−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1034−
1035−-- EventM can do everything BehaviorM can, plus create holds
1036−newtype EventM x a = EventM { unEventM :: IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over
1037−
1038−newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1039−
1040−data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1041− { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1042− , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1043− }
1044−
1045−data HeightBag = HeightBag
1046− { _heightBag_size :: {-# UNPACK #-} !Int
1047− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1048− }
1049− deriving (Show, Read, Eq, Ord)
1050−
1051−heightBagEmpty :: HeightBag
1052−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1053−
1054−heightBagSize :: HeightBag -> Int
1055−heightBagSize = _heightBag_size
1056−
1057−heightBagFromList :: [Height] -> HeightBag
1058−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1059−
1060−heightBagAdd :: Height -> HeightBag -> HeightBag
1061−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1062−
1063−heightBagRemove :: Height -> HeightBag -> HeightBag
1064−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1065− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1066− Just old -> HeightBag (pred s) $ case old of
1067− 0 -> IntMap.delete h c
1068− _ -> IntMap.insert h (pred old) c
1069−
1070−heightBagMax :: HeightBag -> Height
1071−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1072− Just ((h, _), _) -> Height h
1073− Nothing -> zeroHeight
1074−
1075−heightBagVerify :: HeightBag -> HeightBag
1076−#ifdef DEBUG
1077−heightBagVerify b@(HeightBag s c) = if
1078− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1079− -> error $ "heightBagVerify: size doesn't match: " <> show b
1080− | unHeight invalidHeight `IntMap.member` c
1081− -> error $ "heightBagVerify: contains invalid height: " <> show b
1082− | otherwise -> b
1083−#else
1084−heightBagVerify = id
1085−#endif
1086−
1087−data FanSubscribedChildren x k v a = FanSubscribedChildren
1088− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1089− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1090− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1091− }
1092−
1093−data FanSubscribed x k v
1094− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1095− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1096− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1097− , fanSubscribedParent :: !(EventSubscription x)
1098−#ifdef DEBUG_NODEIDS
1099− , fanSubscribedNodeId :: Int
1100−#endif
1101− }
1102−
1103−data Fan x k v
1104− = Fan { fanParent :: !(Event x (DMap k v))
1105− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1106− }
1107−
1108−data SwitchSubscribed x a
1109− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1110− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1111− , switchSubscribedHeight :: !(IORef Height)
1112− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1113− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1114− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1115− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1116− , switchSubscribedParent :: !(Behavior x (Event x a))
1117− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1118− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1119−#ifdef DEBUG_NODEIDS
1120− , switchSubscribedNodeId :: Int
1121−#endif
1122− }
1123−
1124−data Switch x a
1125− = Switch { switchParent :: !(Behavior x (Event x a))
1126− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1127− }
1128−
1129−#ifdef USE_TEMPLATE_HASKELL
1130−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1131−#endif
1132−data CoincidenceSubscribed x a
1133− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1134− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1135− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1136− , coincidenceSubscribedHeight :: !(IORef Height)
1137− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1138− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1139− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1140− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1141−#ifdef DEBUG_NODEIDS
1142− , coincidenceSubscribedNodeId :: Int
1143−#endif
1144− }
1145−
1146−data Coincidence x a
1147− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1148− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1149− }
1150−
1151−{-# NOINLINE newInvalidatorSwitch #-}
1152−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1153−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1154−
1155−{-# NOINLINE newInvalidatorPull #-}
1156−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1157−newInvalidatorPull p = return $! InvalidatorPull p
1158−
1159−instance HasSpiderTimeline x => Filterable (Event x) where
1160− mapMaybe f = push $ return . f
1161−
1162−instance HasSpiderTimeline x => Align (Event x) where
1163− nil = eventNever
1164−#if MIN_VERSION_these(0, 8, 0)
1165−instance HasSpiderTimeline x => Semialign (Event x) where
1166−#endif
1167− align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1168− DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1169−
1170−#ifdef MIN_VERSION_semialign
1171−#if MIN_VERSION_semialign(1,1,0)
1172−instance HasSpiderTimeline x => Zip (Event x) where
1173−#endif
1174− zip x y = mapMaybe justThese $ align x y
1175−#endif
1176−
1177−data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1178− | BuildDyn !(EventM x (PatchTarget p), Event x p)
1179− | HoldDyn !(Hold x p)
1180−
1181−newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1182−
1183−newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
1184−newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1185−
1186−--TODO: Avoid the duplication between this and R.zipDynWith
1187−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
1188−zipDynWith f da db =
1189− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1190− ec = flip push eab $ \o -> do
1191− (a, b) <- case o of
1192− This (Identity a) -> do
1193− b <- readBehaviorUntracked $ dynamicCurrent db
1194− return (a, b)
1195− That (Identity b) -> do
1196− a <- readBehaviorUntracked $ dynamicCurrent da
1197− return (a, b)
1198− These (Identity a) (Identity b) -> return (a, b)
1199− return $ Just $ Identity $ f a b
1200− in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1201−
1202−buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1203−buildDynamic readV0 v' = do
1204− result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1205− let !d = Dyn result
1206− defer $ SomeDynInit d
1207− return d
1208−
1209−unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1210−unsafeBuildDynamic readV0 v' =
1211− Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1212−
1213−-- ResultM can read behaviors and events
1214−type ResultM = EventM
1215−
1216−instance HasSpiderTimeline x => Functor (Event x) where
1217− fmap f = push $ return . Just . f
1218−
1219−instance Functor (Behavior x) where
1220− fmap f = pull . fmap f . readBehaviorTracked
1221−
1222−{-# INLINE push #-}
1223−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1224−push f e = cacheEvent (pushCheap f e)
1225−
1226−{-# INLINABLE pull #-}
1227−pull :: BehaviorM x a -> Behavior x a
1228−pull a = unsafePerformIO $ do
1229− ref <- newIORef Nothing
1230−#ifdef DEBUG_NODEIDS
1231− nid <- newNodeId
1232−#endif
1233− pure $ behaviorPull $ Pull
1234− { pullCompute = a
1235− , pullValue = ref
1236−#ifdef DEBUG_NODEIDS
1237− , pullNodeId = nid
1238−#endif
1239− }
1240−
1241−{-# INLINABLE switch #-}
1242−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1243−switch a = unsafePerformIO $ do
1244− ref <- newIORef Nothing
1245− pure $ eventSwitch $ Switch
1246− { switchParent = a
1247− , switchSubscribed = ref
1248− }
1249−
1250−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1251−coincidence a = unsafePerformIO $ do
1252− ref <- newIORef Nothing
1253− pure $ eventCoincidence $ Coincidence
1254− { coincidenceParent = a
1255− , coincidenceSubscribed = ref
1256− }
1257−
1258−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1259−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1260−run roots after = do
1261− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1262− let t = spiderTimeline :: SpiderTimelineEnv x
1263− result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
1264− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1265− occBefore <- liftIO $ do
1266− occBefore <- readIORef occRef
1267− writeIORef occRef $! DMap.insert k a occBefore
1268− return occBefore
1269− if DMap.null occBefore
1270− then do scheduleRootClear occRef
1271− return $ Just r
1272− else return Nothing
1273− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1274− propagate a subscribersRef
1275− delayedRef <- asksEventEnv eventEnvDelayedMerges
1276− let go = do
1277− delayed <- liftIO $ readIORef delayedRef
1278− case IntMap.minViewWithKey delayed of
1279− Nothing -> return ()
1280− Just ((currentHeight, cur), future) -> do
1281− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1282− putCurrentHeight $ Height currentHeight
1283− liftIO $ writeIORef delayedRef $! future
1284− sequence_ cur
1285− go
1286− go
1287− putCurrentHeight maxBound
1288− after
1289− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1290− return result
1291−
1292−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1293−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1294− height <- liftIO $ readIORef heightRef
1295− currentHeight <- getCurrentHeight
1296− case height `compare` currentHeight of
1297− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1298− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1299− EQ -> a
1300−
1301−newtype Clear a = Clear (IORef (Maybe a))
1302−
1303−newtype IntClear a = IntClear (IORef (IntMap a))
1304−
1305−newtype RootClear k = RootClear (IORef (DMap k Identity))
1306−
1307−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1308−
1309−debugFinalize :: Bool
1310−debugFinalize = False
1311−
1312−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1313−mkWeakPtrWithDebug x debugNote = do
1314− x' <- evaluate x
1315− mkWeakPtr x' $
1316− if debugFinalize
1317− then Just $ putStrLn $ "finalizing: " ++ debugNote
1318− else Nothing
1319−
1320−type WeakList a = [Weak a]
1321−
1322−{-# INLINE withIncreasedDepth #-}
1323−#ifdef DEBUG
1324−withIncreasedDepth :: CanTrace x m => m a -> m a
1325−withIncreasedDepth a = do
1326− spiderTimeline <- askSpiderTimelineEnv
1327− liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
1328− result <- a
1329− liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
1330− return result
1331−#else
1332−withIncreasedDepth :: m a -> m a
1333−withIncreasedDepth = id
1334−#endif
1335−
1336−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1337−
1338−{-# INLINE tracePropagate #-}
1339−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1340−tracePropagate p = traceWhen p debugPropagate
1341−
1342−{-# INLINE traceInvalidate #-}
1343−traceInvalidate :: String -> IO ()
1344−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1345−
1346−{-# INLINE traceWhen #-}
1347−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1348−traceWhen p b message = traceMWhen p b $ return message
1349−
1350−{-# INLINE traceMWhen #-}
1351−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1352−traceMWhen _ b getMessage = when b $ do
1353− message <- getMessage
1354−#ifdef DEBUG
1355− spiderTimeline <- askSpiderTimelineEnv
1356− d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
1357−#else
1358− let d = 0
1359−#endif
1360− liftIO $ putStrLn $ replicate d ' ' <> message
1361−
1362−whoCreatedIORef :: IORef a -> IO [String]
1363−whoCreatedIORef (IORef a) = whoCreated $! a
1364−
1365−#ifdef DEBUG_CYCLES
1366−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1367−groupByHead = \case
1368− [] -> []
1369− (x :| xs) : t -> case groupByHead t of
1370− [] -> [(x, xs :| [])]
1371− l@((y, yss) : t')
1372− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1373− | otherwise -> (x, xs :| []) : l
1374−
1375−listsToForest :: Eq a => [[a]] -> Forest a
1376−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1377−#endif
1378−
1379−{-# INLINE propagateSubscriberHold #-}
1380−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1381−propagateSubscriberHold h a = do
1382− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1383− invalidators <- liftIO $ readIORef $ holdInvalidators h
1384− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1385− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1386− case {-# SCC "apply" #-} apply a v of
1387− Nothing -> return ()
1388− Just v' -> do
1389− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1390− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1391− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1392− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1393−
1394−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1395−
1396−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1397−runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
1398−
1399−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1400−askInvalidator = do
1401− (!m, _) <- ask
1402− case m of
1403− Nothing -> return Nothing
1404− Just (!wi, _) -> return $ Just wi
1405−
1406−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1407−askParentsRef = do
1408− (!m, _) <- ask
1409− case m of
1410− Nothing -> return Nothing
1411− Just (_, !p) -> return $ Just p
1412−
1413−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1414−askBehaviorHoldInits = do
1415− (_, !his) <- ask
1416− return his
1417−
1418−{-# INLINE getDynHold #-}
1419−getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1420−getDynHold d = do
1421− mh <- liftIO $ readIORef $ unDyn d
1422− case mh of
1423− HoldDyn h -> return h
1424− UnsafeDyn (readV0, v') -> do
1425− holdInits <- getDeferralQueue
1426− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1427− hold' v0 v'
1428− BuildDyn (readV0, v') -> do
1429− v0 <- liftIO $ runEventM readV0
1430− hold' v0 v'
1431− where
1432− hold' v0 v' = do
1433− h <- hold v0 v'
1434− liftIO $ writeIORef (unDyn d) $ HoldDyn h
1435− return h
1436−
1437−
1438−-- Always refers to 0
1439−{-# NOINLINE zeroRef #-}
1440−zeroRef :: IORef Height
1441−zeroRef = unsafePerformIO $ newIORef zeroHeight
1442−
1443−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1444−getRootSubscribed k r sub = do
1445− mSubscribed <- readIORef $ rootSubscribed r
1446− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1447− case DMap.lookup k mSubscribed of
1448− Just subscribed -> {-# SCC "hitRoot" #-} do
1449− sln <- subscribeRootSubscribed subscribed sub
1450− occ <- getOcc
1451− return (sln, subscribed, occ)
1452− Nothing -> {-# SCC "missRoot" #-} do
1453− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1454− let !cached = rootSubscribed r
1455− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1456− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1457− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1458− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1459− writeIORef uninitRef $! uninit
1460−#ifdef DEBUG_NODEIDS
1461− nid <- newNodeId
1462−#endif
1463− let !subscribed = RootSubscribed
1464− { rootSubscribedKey = k
1465− , rootSubscribedCachedSubscribed = cached
1466− , rootSubscribedOccurrence = getOcc
1467− , rootSubscribedSubscribers = subs
1468− , rootSubscribedUninit = uninit
1469− , rootSubscribedWeakSelf = weakSelf
1470−#ifdef DEBUG_NODEIDS
1471− , rootSubscribedNodeId = nid
1472−#endif
1473− }
1474− -- If we die at the same moment that all our children die, they will
1475− -- try to clean us up but will fail because their Weak reference to us
1476− -- will also be dead. So, if we are dying, check if there are any
1477− -- children; since children don't bother cleaning themselves up if
1478− -- their parents are already dead, I don't think there's a race
1479− -- condition here. However, if there are any children, then we can
1480− -- infer that we need to clean ourselves up, so we do.
1481− finalCleanup = do
1482− cs <- readIORef $ _weakBag_children subs
1483− when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1484− writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1485− modifyIORef' (rootSubscribed r) $ DMap.insertWith (error $ "getRootSubscribed: duplicate key inserted into Root") k subscribed --TODO: I think we can just write back mSubscribed rather than re-reading it
1486− occ <- getOcc
1487− return (sln, subscribed, occ)
1488−
1489−#ifdef USE_TEMPLATE_HASKELL
1490−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1491−#endif
1492−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1493−cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1494− rootSubscribedUninit self
1495− modifyIORef' cached $ DMap.delete k
1496−
1497−{-# INLINE subscribeRootSubscribed #-}
1498−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1499−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1500−
1501−newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1502−
1503−data FanInt x a = FanInt
1504− { _fanInt_subscribers :: {-# UNPACK #-} !(FastMutableIntMap (FastWeakBag (Subscriber x a))) --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1505− , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1506− , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1507− }
1508−
1509−newFanInt :: IO (FanInt x a)
1510−newFanInt = do
1511− subscribers <- FastMutableIntMap.newEmpty --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1512− subscriptionRef <- newIORef $ error "fanInt: no subscription"
1513− occRef <- newIORef $ error "fanInt: no occurrence"
1514− return $ FanInt
1515− { _fanInt_subscribers = subscribers
1516− , _fanInt_subscriptionRef = subscriptionRef
1517− , _fanInt_occRef = occRef
1518− }
1519−
1520−fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1521−fanInt p = unsafePerformIO $ do
1522− self <- newFanInt
1523− pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1524− isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1525− when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1526− (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1527− { subscriberPropagate = \m -> do
1528− liftIO $ writeIORef (_fanInt_occRef self) m
1529− scheduleIntClear $ _fanInt_occRef self
1530− FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1531− FastWeakBag.traverse_ b $ \s -> do
1532− subscriberPropagate s v
1533− , subscriberInvalidateHeight = \old -> do
1534− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1535− FastWeakBag.traverse_ b $ \s -> do
1536− subscriberInvalidateHeight s old
1537− , subscriberRecalculateHeight = \new -> do
1538− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1539− FastWeakBag.traverse_ b $ \s -> do
1540− subscriberRecalculateHeight s new
1541− }
1542− liftIO $ do
1543− writeIORef (_fanInt_subscriptionRef self) subscription
1544− writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1545− scheduleIntClear $ _fanInt_occRef self
1546− liftIO $ do
1547− b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1548− Nothing -> do
1549− b <- FastWeakBag.empty
1550− FastMutableIntMap.insert (_fanInt_subscribers self) k b
1551− return b
1552− Just b -> return b
1553− t <- liftIO $ FastWeakBag.insert sub b
1554− currentOcc <- readIORef (_fanInt_occRef self)
1555− (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1556− return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1557−
1558−{-# INLINABLE getFanSubscribed #-}
1559−getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k v -> Subscriber x (v a) -> EventM x (WeakBagTicket, FanSubscribed x k v, Maybe (v a))
1560−getFanSubscribed k f sub = do
1561− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1562− case mSubscribed of
1563− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1564− sln <- subscribeFanSubscribed k subscribed sub
1565− occ <- readIORef $ fanSubscribedOccurrence subscribed
1566− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1567− Nothing -> {-# SCC "missFan" #-} do
1568− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1569− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1570− s <- liftIO $ newSubscriberFan subscribedUnsafe
1571− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1572− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1573− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1574− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1575− occRef <- liftIO $ newIORef parentOcc
1576− when (isJust parentOcc) $ scheduleClear occRef
1577−#ifdef DEBUG_NODEIDS
1578− nid <- liftIO newNodeId
1579−#endif
1580− let subscribed = FanSubscribed
1581− { fanSubscribedCachedSubscribed = fanSubscribed f
1582− , fanSubscribedOccurrence = occRef
1583− , fanSubscribedParent = subscription
1584− , fanSubscribedSubscribers = subscribersRef
1585−#ifdef DEBUG_NODEIDS
1586− , fanSubscribedNodeId = nid
1587−#endif
1588− }
1589− let !self = (k, subscribed)
1590− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1591− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1592− liftIO $ writeIORef subscribedRef $! subscribed
1593− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1594− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1595−
1596−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1597−cleanupFanSubscribed (k, subscribed) = do
1598− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1599− let reducedSubscribers = DMap.delete k subscribers
1600− if DMap.null reducedSubscribers
1601− then do
1602− unsubscribe $ fanSubscribedParent subscribed
1603− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1604− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1605− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1606−
1607−{-# INLINE subscribeFanSubscribed #-}
1608−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1609−subscribeFanSubscribed k subscribed sub = do
1610− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1611− case DMap.lookup k subscribers of
1612− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1613− let !self = (k, subscribed)
1614− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1615− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1616− writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeFanSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1617− return sln
1618− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1619−
1620−{-# INLINABLE getSwitchSubscribed #-}
1621−getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1622−getSwitchSubscribed s sub = do
1623− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1624− case mSubscribed of
1625− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1626− sln <- subscribeSwitchSubscribed subscribed sub
1627− occ <- readIORef $ switchSubscribedOccurrence subscribed
1628− return (sln, subscribed, occ)
1629− Nothing -> {-# SCC "missSwitch" #-} do
1630− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1631− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1632− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1633− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1634− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1635− wiRef <- liftIO $ newIORef wi
1636− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1637− holdInits <- getDeferralQueue
1638− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1639− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1640− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1641− subscriptionRef <- liftIO $ newIORef subscription
1642− occRef <- liftIO $ newIORef parentOcc
1643− when (isJust parentOcc) $ scheduleClear occRef
1644− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1645− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1646−#ifdef DEBUG_NODEIDS
1647− nid <- liftIO newNodeId
1648−#endif
1649− let !subscribed = SwitchSubscribed
1650− { switchSubscribedCachedSubscribed = switchSubscribed s
1651− , switchSubscribedOccurrence = occRef
1652− , switchSubscribedHeight = heightRef
1653− , switchSubscribedSubscribers = subs
1654− , switchSubscribedOwnInvalidator = i
1655− , switchSubscribedOwnWeakInvalidator = wiRef
1656− , switchSubscribedBehaviorParents = parentsRef
1657− , switchSubscribedParent = switchParent s
1658− , switchSubscribedCurrentParent = subscriptionRef
1659− , switchSubscribedWeakSelf = weakSelf
1660−#ifdef DEBUG_NODEIDS
1661− , switchSubscribedNodeId = nid
1662−#endif
1663− }
1664− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1665− liftIO $ writeIORef subscribedRef $! subscribed
1666− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1667− return (slnForSub, subscribed, parentOcc)
1668−
1669−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1670−cleanupSwitchSubscribed subscribed = do
1671− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1672− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1673− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1674−
1675−{-# INLINE subscribeSwitchSubscribed #-}
1676−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1677−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1678−
1679−{-# INLINABLE getCoincidenceSubscribed #-}
1680−getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1681−getCoincidenceSubscribed c sub = do
1682− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1683− case mSubscribed of
1684− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1685− sln <- subscribeCoincidenceSubscribed subscribed sub
1686− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1687− return (sln, subscribed, occ)
1688− Nothing -> {-# SCC "missCoincidence" #-} do
1689− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1690− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1691− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1692− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1693− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1694− (occ, height, mInnerSubd) <- case outerOcc of
1695− Nothing -> return (Nothing, outerHeight, Nothing)
1696− Just o -> do
1697− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1698− return (occ, height, Just innerSubd)
1699− occRef <- liftIO $ newIORef occ
1700− when (isJust occ) $ scheduleClear occRef
1701− heightRef <- liftIO $ newIORef height
1702− innerSubdRef <- liftIO $ newIORef mInnerSubd
1703− scheduleClear innerSubdRef
1704− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1705− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1706−#ifdef DEBUG_NODEIDS
1707− nid <- liftIO newNodeId
1708−#endif
1709− let subscribed = CoincidenceSubscribed
1710− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1711− , coincidenceSubscribedOccurrence = occRef
1712− , coincidenceSubscribedHeight = heightRef
1713− , coincidenceSubscribedSubscribers = subs
1714− , coincidenceSubscribedOuter = subOuter
1715− , coincidenceSubscribedOuterParent = outerSubscription
1716− , coincidenceSubscribedInnerParent = innerSubdRef
1717− , coincidenceSubscribedWeakSelf = weakSelf
1718−#ifdef DEBUG_NODEIDS
1719− , coincidenceSubscribedNodeId = nid
1720−#endif
1721− }
1722− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1723− liftIO $ writeIORef subscribedRef $! subscribed
1724− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1725− return (slnForSub, subscribed, occ)
1726−
1727−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1728−cleanupCoincidenceSubscribed subscribed = do
1729− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1730− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1731−
1732−{-# INLINE subscribeCoincidenceSubscribed #-}
1733−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1734−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1735−
1736−{-# INLINE mergeG #-}
1737−mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1738− => (forall a. q a -> Event x (v a))
1739− -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1740−mergeG nt d = cacheEvent (mergeCheap nt d)
1741−
1742−{-# INLINE mergeWithMove #-}
1743−mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1744− => (forall a. q a -> Event x (v a))
1745− -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1746−mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1747−
1748−{-# INLINE [1] mergeCheap #-}
1749−mergeCheap
1750− :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1751− => (forall a. q a -> Event x (v a))
1752− -> DynamicS x (PatchDMap k q)
1753− -> Event x (DMap k v)
1754−mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1755− where
1756− updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1757− updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1758− let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1759− (mOldSubd, newPs) <- case me of
1760− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1761− Just e -> do
1762− let s = subscriber $ return k
1763− subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1764− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1765− let newParent = MergeSubscribedParent subscription
1766− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1767− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1768− forM_ mOldSubd $ \oldSubd -> do
1769− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1770− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1771− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1772− foldM f ([], oldParents) $ DMap.toList p
1773−
1774− getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1775− getInitialSubscribers initialParents subscriber = do
1776− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1777− let s = subscriber $ return k
1778− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1779− height <- liftIO $ getEventSubscribedHeight parentSubd
1780− return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1781− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1782− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1783− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1784− )
1785−
1786− destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1787− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1788−
1789−{-# INLINE [1] mergeCheapWithMove #-}
1790−mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1791− => (forall a. q a -> Event x (v a))
1792− -> DynamicS x (PatchDMapWithMove k q)
1793− -> Event x (DMap k v)
1794−mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1795− where
1796− updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1797− updateMe subscriber heightBagRef oldParents p = do
1798− -- Prepare new parents for insertion
1799− let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1800− subscribeParent k e = do
1801− keyRef <- liftIO $ newIORef k
1802− let s = subscriber $ liftIO $ readIORef keyRef
1803− subscription@(EventSubscription _ subd) <- subscribe e s
1804− liftIO $ do
1805− newParentHeight <- getEventSubscribedHeight subd
1806− modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1807− return $ MergeSubscribedParentWithMove subscription keyRef
1808− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1809− -- Collect old parents for deletion and update the keys of moved parents
1810− let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1811− moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1812− Nothing -> do
1813− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1814− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1815− return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1816− Just toKey -> do
1817− liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1818− return Nothing
1819− toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1820− return (toDelete, applyAlways p' oldParents)
1821− getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1822− getInitialSubscribers initialParents subscriber = do
1823− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1824− keyRef <- liftIO $ newIORef k
1825− let s = subscriber $ liftIO $ readIORef keyRef
1826− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1827− height <- liftIO $ getEventSubscribedHeight parentSubd
1828− return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1829− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1830− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1831− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1832− )
1833−
1834− destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1835− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1836−
1837−type MergeUpdateFunc k v x p s
1838− = (forall a. EventM x (k a) -> Subscriber x (v a))
1839− -> IORef HeightBag
1840− -> DMap k s
1841− -> p
1842− -> EventM x ([EventSubscription x], DMap k s)
1843−
1844−type MergeInitFunc k v q x s
1845− = DMap k q
1846− -> (forall a. EventM x (k a) -> Subscriber x (v a))
1847− -> EventM x (DMap k v, [Height], DMap k s)
1848−
1849−type MergeDestroyFunc k s
1850− = DMap k s
1851− -> IO ()
1852−
1853−data Merge x k v s = Merge
1854− { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1855− , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1856− , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1857− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1858− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1859− }
1860−
1861−invalidateMergeHeight :: Merge x k v s -> IO ()
1862−invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1863−
1864−invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1865−invalidateMergeHeight' heightRef sub = do
1866− oldHeight <- readIORef heightRef
1867− when (oldHeight /= invalidHeight) $ do -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1868− writeIORef heightRef $! invalidHeight
1869− subscriberInvalidateHeight sub oldHeight
1870−
1871−revalidateMergeHeight :: Merge x k v s -> IO ()
1872−revalidateMergeHeight m = do
1873− currentHeight <- readIORef $ _merge_heightRef m
1874− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1875− heights <- readIORef $ _merge_heightBagRef m
1876− parents <- readIORef $ _merge_parentsRef m
1877− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1878− case heightBagSize heights `compare` DMap.size parents of
1879− LT -> return ()
1880− EQ -> do
1881− let height = succHeight $ heightBagMax heights
1882− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1883− writeIORef (_merge_heightRef m) $! height
1884− subscriberRecalculateHeight (_merge_sub m) height
1885− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1886−
1887−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1888−scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1889− vals <- liftIO $ readIORef $ _merge_accumRef m
1890− liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us, it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
1891− --TODO: Assert that m is not empty
1892− subscriberPropagate (_merge_sub m) vals
1893−
1894−mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1895−mergeSubscriber m getKey = Subscriber
1896− { subscriberPropagate = \a -> do
1897− oldM <- liftIO $ readIORef $ _merge_accumRef m
1898− k <- getKey
1899− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1900− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1901− liftIO $ writeIORef (_merge_accumRef m) $! newM
1902− when (DMap.null oldM) $ do -- Only schedule the firing once
1903− height <- liftIO $ readIORef $ _merge_heightRef m
1904− --TODO: assertions about height
1905− currentHeight <- getCurrentHeight
1906− when (height <= currentHeight) $ do
1907− if height /= invalidHeight
1908− then do
1909− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1910− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1911− else liftIO $ do
1912−#ifdef DEBUG_CYCLES
1913− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1914− stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1915− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1916−#else
1917− let cycleInfo = ""
1918−#endif
1919− error $ "Causality loop found" <> cycleInfo
1920− scheduleMergeSelf m height
1921− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1922− modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1923− invalidateMergeHeight m
1924− , subscriberRecalculateHeight = \new -> do
1925− modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1926− revalidateMergeHeight m
1927− }
1928−
1929−--TODO: Be able to run as much of this as possible promptly
1930−updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1931−updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1932− where updateMe = do
1933− oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1934− (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1935− liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1936− return subscriptionsToKill
1937−
1938−{-# INLINE mergeGCheap' #-}
1939−mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1940− => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1941−mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1942− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1943− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1944− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1945− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1946− parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1947− let m = Merge
1948− { _merge_parentsRef = parentsRef
1949− , _merge_heightBagRef = heightBagRef
1950− , _merge_heightRef = heightRef
1951− , _merge_sub = sub
1952− , _merge_accumRef = accumRef
1953− }
1954− (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1955− let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1956− myHeight = if invalidHeight `elem` heights
1957− then invalidHeight
1958− else succHeight $ heightBagMax myHeightBag
1959− currentHeight <- getCurrentHeight
1960− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1961− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1962− else (Nothing, dm)
1963− unless (DMap.null accum) $ do
1964− scheduleMergeSelf m myHeight
1965− liftIO $ writeIORef accumRef $! accum
1966− liftIO $ writeIORef heightRef $! myHeight
1967− liftIO $ writeIORef heightBagRef $! myHeightBag
1968− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1969− liftIO $ writeIORef parentsRef $! initialParentState
1970− defer $ SomeMergeInit $ do
1971− let s = Subscriber
1972− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1973− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1974− defer $ updateMerge m updateFunc a
1975− , subscriberInvalidateHeight = \_ -> return ()
1976− , subscriberRecalculateHeight = \_ -> return ()
1977− }
1978− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1979− forM_ change $ \c -> defer $ updateMerge m updateFunc c
1980− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1981− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1982− -- its subscription.
1983− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1984− let unsubscribeAll = destroy =<< readIORef parentsRef
1985− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1986− , occ
1987− )
1988−
1989−mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1990−mergeInt = cacheEvent . mergeIntCheap
1991−
1992−{-# INLINABLE mergeIntCheap #-}
1993−mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1994−mergeIntCheap d = Event $ \sub -> do
1995− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1996− accum <- liftIO $ FastMutableIntMap.newEmpty
1997− heightRef <- liftIO $ newIORef zeroHeight
1998− heightBagRef <- liftIO $ newIORef heightBagEmpty
1999− parents <- liftIO $ FastMutableIntMap.newEmpty
2000− let scheduleSelf = do
2001− height <- liftIO $ readIORef $ heightRef
2002− scheduleMerge' height heightRef $ do
2003− vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
2004− subscriberPropagate sub vals
2005− invalidateMyHeight = do
2006− invalidateMergeHeight' heightRef sub
2007− recalculateMyHeight = do
2008− currentHeight <- readIORef heightRef
2009− when (currentHeight == invalidHeight) $ do --TODO: This will almost always be true; can we get rid of this check and just proceed to the next one always?
2010− heights <- readIORef heightBagRef
2011− numParents <- FastMutableIntMap.size parents
2012− case heightBagSize heights `compare` numParents of
2013− LT -> return ()
2014− EQ -> do
2015− let height = succHeight $ heightBagMax heights
2016− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
2017− writeIORef heightRef $! height
2018− subscriberRecalculateHeight sub height
2019− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
2020− mySubscriber k = Subscriber
2021− { subscriberPropagate = \a -> do
2022− wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2023− liftIO $ FastMutableIntMap.insert accum k a
2024− when wasEmpty scheduleSelf
2025− , subscriberInvalidateHeight = \old -> do
2026− modifyIORef' heightBagRef $ heightBagRemove old
2027− invalidateMyHeight
2028− , subscriberRecalculateHeight = \new -> do
2029− modifyIORef' heightBagRef $ heightBagAdd new
2030− recalculateMyHeight
2031− }
2032− forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2033− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2034− liftIO $ do
2035− forM_ parentOcc $ FastMutableIntMap.insert accum k
2036− FastMutableIntMap.insert parents k subscription
2037− height <- getEventSubscribedHeight parentSubd
2038− if height == invalidHeight
2039− then writeIORef heightRef invalidHeight
2040− else do
2041− modifyIORef' heightBagRef $ heightBagAdd height
2042− modifyIORef' heightRef $ \oldHeight ->
2043− if oldHeight == invalidHeight
2044− then invalidHeight
2045− else max (succHeight height) oldHeight
2046− myHeight <- liftIO $ readIORef heightRef
2047− currentHeight <- getCurrentHeight
2048− isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2049− occ <- if currentHeight >= myHeight -- If we should have fired by now
2050− then if isEmpty
2051− then return Nothing
2052− else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2053− else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2054− return Nothing
2055− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2056− defer $ SomeMergeInit $ do
2057− let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2058− where
2059− u = do
2060− let f k newParent = do
2061− subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2062− newParentHeight <- liftIO $ getEventSubscribedHeight subd
2063− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2064− return subscription
2065− newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2066− oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2067− liftIO $ for_ oldParents $ \oldParent -> do
2068− oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2069− modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2070− return $ IntMap.elems oldParents
2071− let s = Subscriber
2072− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2073− tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2074− defer $ updateMe a
2075− , subscriberInvalidateHeight = \_ -> return ()
2076− , subscriberRecalculateHeight = \_ -> return ()
2077− }
2078− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2079− forM_ change $ \c -> defer $ updateMe c
2080− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2081− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2082− -- its subscription.
2083− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2084− let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2085− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2086− , occ
2087− )
2088−
2089−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2090−newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2091−
2092−fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2093−fanG e = unsafePerformIO $ do
2094− ref <- newIORef Nothing
2095− let f = Fan
2096− { fanParent = e
2097− , fanSubscribed = ref
2098− }
2099− pure $ EventSelectorG $ \k -> eventFan k f
2100−
2101−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2102−runHoldInits holdInitRef dynInitRef mergeInitRef = do
2103− holdInits <- liftIO $ readIORef holdInitRef
2104− dynInits <- liftIO $ readIORef dynInitRef
2105− mergeInits <- liftIO $ readIORef mergeInitRef
2106− unless (null holdInits && null dynInits && null mergeInits) $ do
2107− liftIO $ writeIORef holdInitRef []
2108− liftIO $ writeIORef dynInitRef []
2109− liftIO $ writeIORef mergeInitRef []
2110− mapM_ initHold holdInits
2111− mapM_ initDyn dynInits
2112− mapM_ unSomeMergeInit mergeInits
2113− runHoldInits holdInitRef dynInitRef mergeInitRef
2114−
2115−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2116−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2117−
2118−initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2119−initDyn (SomeDynInit d) = void $ getDynHold d
2120−
2121−newEventEnv :: IO (EventEnv x)
2122−newEventEnv = do
2123− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2124− holdInitRef <- newIORef []
2125− dynInitRef <- newIORef []
2126− mergeUpdateRef <- newIORef []
2127− mergeInitRef <- newIORef []
2128− heightRef <- newIORef zeroHeight
2129− toClearRef <- newIORef []
2130− toClearIntRef <- newIORef []
2131− toClearRootRef <- newIORef []
2132− coincidenceInfosRef <- newIORef []
2133− delayedRef <- newIORef IntMap.empty
2134− return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2135−
2136−clearEventEnv :: EventEnv x -> IO ()
2137−clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2138− writeIORef toAssignRef []
2139− writeIORef holdInitRef []
2140− writeIORef dynInitRef []
2141− writeIORef mergeUpdateRef []
2142− writeIORef mergeInitRef []
2143− writeIORef heightRef zeroHeight
2144− writeIORef toClearRef []
2145− writeIORef toClearIntRef []
2146− writeIORef toClearRootRef []
2147− writeIORef coincidenceInfosRef []
2148− writeIORef delayedRef IntMap.empty
2149−
2150−-- | Run an event action outside of a frame
2151−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2152−runFrame a = SpiderHost $ do
2153− let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
2154− let go = do
2155− result <- a
2156− runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
2157− return result
2158− result <- runEventM go
2159− toClear <- readIORef $ eventEnvClears env
2160− forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2161− toClearInt <- readIORef $ eventEnvIntClears env
2162− forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2163− toClearRoot <- readIORef $ eventEnvRootClears env
2164− forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2165− toAssign <- readIORef $ eventEnvAssignments env
2166− toReconnectRef <- newIORef []
2167− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2168− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2169− writeIORef vRef v
2170− when debugInvalidate $ putStrLn $ "Invalidating Hold"
2171− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2172− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2173− writeIORef (eventEnvMergeUpdates env) []
2174− when debugPropagate $ putStrLn "Updating merges"
2175− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2176− when debugPropagate $ putStrLn "Updating merges done"
2177− toReconnect <- readIORef toReconnectRef
2178− clearEventEnv env
2179− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2180− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2181− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2182− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2183− finalize wi
2184− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2185− wi' <- mkWeakPtrWithDebug i "wi'"
2186− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2187− writeIORef (switchSubscribedBehaviorParents subscribed) []
2188− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2189− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2190− runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) --TODO: Is this actually OK? It seems like it should be, since we know that no events are firing at this point, but it still seems inelegant
2191− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2192− sub <- newSubscriberSwitch subscribed
2193− subscription <- unSpiderHost $ runFrame $ {-# SCC "subscribeSwitch" #-} subscribe e sub --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient
2194− {-
2195− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2196− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2197− EventRoot _ -> "EventRoot"
2198− EventNever -> "EventNever"
2199− _ -> "something else"
2200− -}
2201− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2202− return oldSubscription
2203− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2204− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2205− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2206− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2207− parentHeight <- getEventSubscribedHeight subd'
2208− myHeight <- readIORef $ switchSubscribedHeight subscribed
2209− when (parentHeight /= myHeight) $ do
2210− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2211− WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2212− mapM_ _someMergeUpdate_invalidateHeight mergeUpdates --TODO: In addition to when the patch is completely empty, we should also not run this if it has some Nothing values, but none of them have actually had any effect; potentially, we could even check for Just values with no effect (e.g. by comparing their IORefs and ignoring them if they are unchanged); actually, we could just check if the new height is different
2213− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2214− unsubscribe subscription
2215− mapM_ invalidateCoincidenceHeight mcs
2216− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2217− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2218− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2219− height <- calculateSwitchHeight subscribed
2220− updateSwitchHeight height subscribed
2221− return result
2222−
2223−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2224−
2225−{-# INLINE zeroHeight #-}
2226−zeroHeight :: Height
2227−zeroHeight = Height 0
2228−
2229−{-# INLINE invalidHeight #-}
2230−invalidHeight :: Height
2231−invalidHeight = Height (-1000)
2232−
2233−#ifdef DEBUG_CYCLES
2234−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2235−{-# INLINE invalidHeightBeingTraversed #-}
2236−invalidHeightBeingTraversed :: Height
2237−invalidHeightBeingTraversed = Height (-1001)
2238−#endif
2239−
2240−{-# INLINE succHeight #-}
2241−succHeight :: Height -> Height
2242−succHeight h@(Height a) =
2243− if h == invalidHeight
2244− then invalidHeight
2245− else Height $ succ a
2246−
2247−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2248−invalidateCoincidenceHeight subscribed = do
2249− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2250− when (oldHeight /= invalidHeight) $ do
2251− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2252− WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2253−
2254−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2255−updateSwitchHeight new subscribed = do
2256− oldHeight <- readIORef $ switchSubscribedHeight subscribed
2257− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2258− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2259− writeIORef (switchSubscribedHeight subscribed) $! new
2260− WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2261−
2262−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2263−recalculateCoincidenceHeight subscribed = do
2264− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2265− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2266− height <- calculateCoincidenceHeight subscribed
2267− when (height /= invalidHeight) $ do
2268− writeIORef (coincidenceSubscribedHeight subscribed) $! height
2269− WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2270−
2271−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2272−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2273−
2274−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2275−calculateCoincidenceHeight subscribed = do
2276− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2277− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2278− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2279−
2280−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2281−
2282−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2283−invalidate toReconnectRef wis = do
2284− forM_ wis $ \wi -> do
2285− mi <- deRefWeak wi
2286− case mi of
2287− Nothing -> do
2288− traceInvalidate "invalidate Dead"
2289− return () --TODO: Should we clean this up here?
2290− Just i -> do
2291− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2292− case i of
2293− InvalidatorPull p -> do
2294− traceInvalidate $ "invalidate: Pull" <> showNodeId p
2295− mVal <- readIORef $ pullValue p
2296− forM_ mVal $ \val -> do
2297− writeIORef (pullValue p) Nothing
2298− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2299− InvalidatorSwitch subscribed -> do
2300− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2301− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2302− 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
2303−
2304−--------------------------------------------------------------------------------
2305−-- Reflex integration
2306−--------------------------------------------------------------------------------
2307−
2308−-- | Designates the default, global Spider timeline
2309−data SpiderTimeline x
2310−type role SpiderTimeline nominal
2311−
2312−-- | The default, global Spider environment
2313−type Spider = SpiderTimeline Global
2314−
2315−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2316− {-# INLINABLE sample #-}
2317− sample (SpiderBehavior b) = readBehaviorUntracked b
2318−
2319−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2320− {-# INLINABLE hold #-}
2321− hold = holdSpiderEventM
2322− {-# INLINABLE holdDyn #-}
2323− holdDyn = holdDynSpiderEventM
2324− {-# INLINABLE holdIncremental #-}
2325− holdIncremental = holdIncrementalSpiderEventM
2326− {-# INLINABLE buildDynamic #-}
2327− buildDynamic = buildDynamicSpiderEventM
2328− {-# INLINABLE headE #-}
2329− headE = R.slowHeadE
2330−-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2331−
2332−instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2333− {-# INLINABLE sample #-}
2334− sample = coerce . readBehaviorTracked . unSpiderBehavior
2335−
2336−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2337− {-# INLINABLE sample #-}
2338− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2339−
2340−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2341− {-# INLINABLE hold #-}
2342− hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2343− {-# INLINABLE holdDyn #-}
2344− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2345− {-# INLINABLE holdIncremental #-}
2346− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2347− {-# INLINABLE buildDynamic #-}
2348− buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2349− {-# INLINABLE headE #-}
2350− headE = R.slowHeadE
2351−-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2352−
2353−instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2354− {-# INLINE return #-}
2355− return = pure
2356− {-# INLINE (>>=) #-}
2357− x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2358− {-# INLINE (>>) #-}
2359− (>>) = (*>)
2360− {-# INLINE fail #-}
2361− fail _ = error "Dynamic does not support 'fail'"
2362−
2363−{-# INLINABLE newJoinDyn #-}
2364−newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2365−newJoinDyn d =
2366− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2367− eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2368− eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2369− eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2370− v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2371− in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2372−
2373−instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2374− fmap = mapDynamicSpider
2375− x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2376−
2377−mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2378−mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2379−{-# INLINE [1] mapDynamicSpider #-}
2380−
2381−instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2382− pure = SpiderDynamic . dynamicConst
2383−#if MIN_VERSION_base(4,10,0)
2384− liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2385−#endif
2386− SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2387− a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2388− (<*) = flip (*>) -- There are no effects, so order doesn't matter
2389−
2390−holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2391−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2392−
2393−holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2394−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2395−
2396−holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2397−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2398−
2399−buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2400−buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2401−
2402−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2403− {-# INLINABLE hold #-}
2404− hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2405− {-# INLINABLE holdDyn #-}
2406− holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2407− {-# INLINABLE holdIncremental #-}
2408− holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2409− {-# INLINABLE buildDynamic #-}
2410− buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2411− {-# INLINABLE headE #-}
2412− headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2413−
2414−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2415− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2416−
2417−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2418− {-# INLINABLE hold #-}
2419− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2420− {-# INLINABLE holdDyn #-}
2421− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2422− {-# INLINABLE holdIncremental #-}
2423− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2424− {-# INLINABLE buildDynamic #-}
2425− buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2426− {-# INLINABLE headE #-}
2427− headE = R.slowHeadE
2428−-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2429−
2430−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2431− {-# INLINABLE sample #-}
2432− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2433−
2434−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2435− {-# INLINABLE sample #-}
2436− sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2437−
2438−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2439− {-# INLINABLE hold #-}
2440− hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2441− {-# INLINABLE holdDyn #-}
2442− holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2443− {-# INLINABLE holdIncremental #-}
2444− holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2445− {-# INLINABLE buildDynamic #-}
2446− buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2447− {-# INLINABLE headE #-}
2448− headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2449−
2450−--------------------------------------------------------------------------------
2451−-- Deprecated items
2452−--------------------------------------------------------------------------------
2453−
2454−-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2455−{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2456−type SpiderEnv = SpiderTimeline
2457−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2458− {-# INLINABLE subscribeEvent #-}
2459− subscribeEvent e = SpiderHostFrame $ do
2460− --TODO: Unsubscribe eventually (manually and/or with weak ref)
2461− val <- liftIO $ newIORef Nothing
2462− subscription <- subscribe (unSpiderEvent e) $ Subscriber
2463− { subscriberPropagate = \a -> do
2464− liftIO $ writeIORef val $ Just a
2465− scheduleClear val
2466− , subscriberInvalidateHeight = \_ -> return ()
2467− , subscriberRecalculateHeight = \_ -> return ()
2468− }
2469− return $ SpiderEventHandle
2470− { spiderEventHandleSubscription = subscription
2471− , spiderEventHandleValue = val
2472− }
2473−
2474−instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2475− type EventTrigger (SpiderTimeline x) = RootTrigger x
2476− type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2477− type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2478−
2479−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2480− {-# NOINLINE readEvent #-}
2481− readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2482− result <- readIORef $ spiderEventHandleValue h
2483− touch h
2484− return result
2485−
2486−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2487− newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2488− newFanEventWithTrigger f = SpiderHost $ do
2489− es <- newFanEventWithTriggerIO f
2490− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2491−
2492−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2493− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2494− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2495− es <- newFanEventWithTriggerIO f
2496− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2497−
2498−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2499− {-# INLINABLE subscribeEvent #-}
2500− subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2501−
2502−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2503− type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2504− fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2505− runHostFrame = runFrame . runSpiderHostFrame
2506−
2507−unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2508−unsafeNewSpiderTimelineEnv = do
2509− lock <- newMVar ()
2510− env <- newEventEnv
2511−#ifdef DEBUG
2512− depthRef <- newIORef 0
2513−#endif
2514− return $ STE $ SpiderTimelineEnv
2515− { _spiderTimeline_lock = lock
2516− , _spiderTimeline_eventEnv = env
2517−#ifdef DEBUG
2518− , _spiderTimeline_depth = depthRef
2519−#endif
2520− }
2521−
2522−-- | Create a new SpiderTimelineEnv
2523−newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2524−newSpiderTimeline = withSpiderTimeline (pure . Some)
2525−
2526−data LocalSpiderTimeline (x :: Type) s
2527−
2528−instance Reifies s (SpiderTimelineEnv x) =>
2529− HasSpiderTimeline (LocalSpiderTimeline x s) where
2530− spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
2531−
2532−localSpiderTimeline
2533− :: proxy s
2534− -> SpiderTimelineEnv x
2535− -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2536−localSpiderTimeline _ = coerce
2537−
2538−-- | Pass a new timeline to the given function.
2539−withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2540−withSpiderTimeline k = do
2541− env <- unsafeNewSpiderTimelineEnv
2542− reify env $ \s -> k $ localSpiderTimeline s env
2543−
2544−newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2545−
2546−type ComputeM = EventM
2547−
2548−newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2549−
2550−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2551− {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2552− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2553− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2554− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2555− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
2556− type PullM (SpiderTimeline x) = SpiderPullM x
2557− type PushM (SpiderTimeline x) = SpiderPushM x
2558− {-# INLINABLE never #-}
2559− never = SpiderEvent eventNever
2560− {-# INLINABLE constant #-}
2561− constant = SpiderBehavior . behaviorConst
2562− {-# INLINE push #-}
2563− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2564− {-# INLINE pushCheap #-}
2565− pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2566− {-# INLINABLE pull #-}
2567− pull = SpiderBehavior . pull . coerce
2568− {-# INLINABLE fanG #-}
2569− fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2570− {-# INLINABLE mergeG #-}
2571− mergeG
2572− :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2573− => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2574− -> DMap k q
2575− -> R.Event (SpiderTimeline x) (DMap k v)
2576− mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2577− {-# INLINABLE switch #-}
2578− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2579− {-# INLINABLE coincidence #-}
2580− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2581− {-# INLINABLE current #-}
2582− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2583− {-# INLINABLE updated #-}
2584− updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
2585− {-# INLINABLE unsafeBuildDynamic #-}
2586− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2587− {-# INLINABLE unsafeBuildIncremental #-}
2588− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2589− {-# INLINABLE mergeIncrementalG #-}
2590− mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2591− {-# INLINABLE mergeIncrementalWithMoveG #-}
2592− mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2593− {-# INLINABLE currentIncremental #-}
2594− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2595− {-# INLINABLE updatedIncremental #-}
2596− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2597− {-# INLINABLE incrementalToDynamic #-}
2598− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2599− c <- readBehaviorUntracked $ dynamicCurrent i
2600− return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2601− eventCoercion Coercion = Coercion
2602− behaviorCoercion Coercion = Coercion
2603− dynamicCoercion Coercion = Coercion
2604− incrementalCoercion Coercion Coercion = Coercion
2605− {-# INLINABLE mergeIntIncremental #-}
2606− mergeIntIncremental = SpiderEvent . mergeInt . coerce
2607− {-# INLINABLE fanInt #-}
2608− fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2609−
2610−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2611−
2612−data SpiderEventHandle x a = SpiderEventHandle
2613− { spiderEventHandleSubscription :: EventSubscription x
2614− , spiderEventHandleValue :: IORef (Maybe a)
2615− }
2616−
2617−instance MonadRef (EventM x) where
2618− type Ref (EventM x) = Ref IO
2619− {-# INLINABLE newRef #-}
2620− {-# INLINABLE readRef #-}
2621− {-# INLINABLE writeRef #-}
2622− newRef = liftIO . newRef
2623− readRef = liftIO . readRef
2624− writeRef r a = liftIO $ writeRef r a
2625−
2626−instance MonadAtomicRef (EventM x) where
2627− {-# INLINABLE atomicModifyRef #-}
2628− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2629−
2630−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2631−newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2632−
2633−instance Monad (SpiderHost x) where
2634− {-# INLINABLE (>>=) #-}
2635− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2636− {-# INLINABLE (>>) #-}
2637− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2638− {-# INLINABLE return #-}
2639− return x = SpiderHost $ return x
2640− {-# INLINABLE fail #-}
2641− fail s = SpiderHost $ fail s
2642−
2643−-- | Run an action affecting the global Spider timeline; this will be guarded by
2644−-- a mutex for that timeline
2645−runSpiderHost :: SpiderHost Global a -> IO a
2646−runSpiderHost (SpiderHost a) = a
2647−
2648−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2649−-- mutex for that timeline
2650−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2651−runSpiderHostForTimeline (SpiderHost a) _ = a
2652−
2653−newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2654− deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2655−
2656−instance Monad (SpiderHostFrame x) where
2657− {-# INLINABLE (>>=) #-}
2658− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2659− {-# INLINABLE (>>) #-}
2660− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2661− {-# INLINABLE return #-}
2662− return x = SpiderHostFrame $ return x
2663− {-# INLINABLE fail #-}
2664− fail s = SpiderHostFrame $ fail s
2665−
2666−instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2667− notReadyUntil _ = pure ()
2668− notReady = pure ()
2669−
2670−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2671−newEventWithTriggerIO f = do
2672− es <- newFanEventWithTriggerIO $ \Refl -> f
2673− return $ select es Refl
2674−
2675−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2676−newFanEventWithTriggerIO f = do
2677− occRef <- newIORef DMap.empty
2678− subscribedRef <- newIORef DMap.empty
2679− let !r = Root
2680− { rootOccurrence = occRef
2681− , rootSubscribed = subscribedRef
2682− , rootInit = f
2683− }
2684− return $ EventSelector $ \k -> eventRoot k r
2685−
2686−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2687−
2688−instance MonadRef (SpiderHost x) where
2689− type Ref (SpiderHost x) = Ref IO
2690− newRef = SpiderHost . newRef
2691− readRef = SpiderHost . readRef
2692− writeRef r = SpiderHost . writeRef r
2693−
2694−instance MonadAtomicRef (SpiderHost x) where
2695− atomicModifyRef r = SpiderHost . atomicModifyRef r
2696−
2697−instance MonadRef (SpiderHostFrame x) where
2698− type Ref (SpiderHostFrame x) = Ref IO
2699− newRef = SpiderHostFrame . newRef
2700− readRef = SpiderHostFrame . readRef
2701− writeRef r = SpiderHostFrame . writeRef r
2702−
2703−instance MonadAtomicRef (SpiderHostFrame x) where
2704− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2705−
2706−instance PrimMonad (SpiderHostFrame x) where
2707− type PrimState (SpiderHostFrame x) = PrimState IO
2708− primitive = SpiderHostFrame . EventM . primitive
2709−
2710−instance NotReady (SpiderTimeline x) (SpiderHost x) where
2711− notReadyUntil _ = return ()
2712− notReady = return ()
2713−
2714−instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x)) where
2715− notReadyUntil _ = return ()
2716− notReady = return ()
src/Reflex/Time.hsdeleted−384
@@ -1,384 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE DeriveTraversable #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RecursiveDo #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeFamilies #-}
11−#ifdef USE_TEMPLATE_HASKELL
12−{-# LANGUAGE TemplateHaskell #-}
13−#endif
14−-- |
15−-- Module:
16−-- Reflex.Time
17−-- Description:
18−-- Clocks, timers, and other time-related functions.
19−module Reflex.Time where
20−
21−import Reflex.Class
22−import Reflex.Dynamic
23−import Reflex.PerformEvent.Class
24−import Reflex.PostBuild.Class
25−import Reflex.TriggerEvent.Class
26−
27−import Control.Concurrent
28−import qualified Control.Concurrent.Thread.Delay as Concurrent
29−import Control.Lens hiding ((|>))
30−import Control.Monad
31−import Control.Monad.Fix
32−import Control.Monad.IO.Class
33−import Data.Align
34−import Data.Data (Data)
35−import Data.Fixed
36−import Data.Semigroup (Semigroup(..))
37−import Data.Sequence (Seq, (|>))
38−import qualified Data.Sequence as Seq
39−import Data.These
40−import Data.Time.Clock
41−import Data.Typeable
42−import GHC.Generics (Generic)
43−import System.Random
44−
45−-- | Metadata associated with a timer "tick"
46−data TickInfo
47− = TickInfo { _tickInfo_lastUTC :: UTCTime
48− -- ^ UTC time immediately after the last tick.
49− , _tickInfo_n :: Integer
50− -- ^ Number of time periods or ticks since the start of the timer
51− , _tickInfo_alreadyElapsed :: NominalDiffTime
52− -- ^ Amount of time that has elapsed in the current tick period.
53− }
54− deriving (Eq, Ord, Show, Typeable)
55−
56−-- | Fires an 'Event' once every time provided interval elapses, approximately.
57−-- The provided 'UTCTime' is used bootstrap the determination of how much time has elapsed with each tick.
58−-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread.
59−tickLossy :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> UTCTime -> m (Event t TickInfo)
60−tickLossy dt t0 = tickLossyFrom dt t0 =<< getPostBuild
61−
62−-- | Fires an 'Event' once every time provided interval elapses, approximately.
63−-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread and the time of the post-build as the tick basis time.
64−tickLossyFromPostBuildTime :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> m (Event t TickInfo)
65−tickLossyFromPostBuildTime dt = do
66− postBuild <- getPostBuild
67− postBuildTime <- performEvent $ liftIO getCurrentTime <$ postBuild
68− tickLossyFrom' $ (dt,) <$> postBuildTime
69−
70−-- | Fires an 'Event' approximately each time the provided interval elapses. If the system starts running behind, occurrences will be dropped rather than buffered.
71−-- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the provided initial time.
72−tickLossyFrom
73− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
74− => NominalDiffTime
75− -- ^ The length of a tick interval
76− -> UTCTime
77− -- ^ The basis time from which intervals count and with which the initial calculation of elapsed time will be made.
78− -> Event t a
79− -- ^ Event that starts a tick generation thread. Usually you want this to
80− -- be something like the result of getPostBuild that only fires once. But
81− -- there could be uses for starting multiple timer threads.
82− -> m (Event t TickInfo)
83−tickLossyFrom dt t0 e = tickLossyFrom' $ (dt, t0) <$ e
84−
85−-- | Generalization of tickLossyFrom that takes the delay and initial time as an 'Event'.
86−tickLossyFrom'
87− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
88− => Event t (NominalDiffTime, UTCTime)
89− -- ^ Event that starts a tick generation thread. Usually you want this to
90− -- be something like the result of 'getPostBuild' that only fires once. But
91− -- there could be uses for starting multiple timer threads.
92− -> m (Event t TickInfo)
93−tickLossyFrom' e = do
94− rec result <- performEventAsync $ callAtNextInterval <$> leftmost [e, snd <$> result]
95− return $ fst <$> result
96− where callAtNextInterval pair cb = void $ liftIO $ forkIO $ do
97− tick <- uncurry getCurrentTick pair
98− Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000
99− cb (tick, pair)
100−
101−-- | Like 'tickLossy', but immediately calculates the first tick and provides a 'Dynamic' that is updated as ticks fire.
102−clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)
103−clockLossy dt t0 = do
104− initial <- liftIO $ getCurrentTick dt t0
105− e <- tickLossy dt t0
106− holdDyn initial e
107−
108−-- | Generates a 'TickInfo', given the specified interval and timestamp. The 'TickInfo' will include the
109−-- current time, the number of ticks that have elapsed since the timestamp, and the amount of time that
110−-- has elapsed since the start time of this tick.
111−getCurrentTick :: NominalDiffTime -> UTCTime -> IO TickInfo
112−getCurrentTick dt t0 = do
113− t <- getCurrentTime
114− let offset = t `diffUTCTime` t0
115− (n, alreadyElapsed) = offset `divMod'` dt
116− return $ TickInfo t n alreadyElapsed
117−
118−-- | Delay an Event's occurrences by a given amount in seconds.
119−delay :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
120−delay dt e = performEventAsync $ ffor e $ \a cb -> liftIO $ void $ forkIO $ do
121− Concurrent.delay $ ceiling $ dt * 1000000
122− cb a
123−
124−-- | Send events with Poisson timing with the given basis and rate
125−-- Each occurrence of the resulting event will contain the index of
126−-- the current interval, with 0 representing the basis time
127−poissonLossyFrom
128− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
129− => g
130− -> Double
131− -- ^ Poisson event rate (Hz)
132− -> UTCTime
133− -- ^ Baseline time for events
134− -> Event t a
135− -- ^ Event that starts a tick generation thread. Usually you want this to
136− -- be something like the result of getPostBuild that only fires once. But
137− -- there could be uses for starting multiple timer threads.
138− -- Start sending events in response to the event parameter.
139− -> m (Event t TickInfo)
140−poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate
141−
142−
143−-- | Send events with Poisson timing with the given basis and rate
144−-- Each occurrence of the resulting event will contain the index of
145−-- the current interval, with 0 representing the basis time.
146−-- Automatically begin sending events when the DOM is built
147−poissonLossy
148− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
149− => g
150− -> Double
151− -- ^ Poisson event rate (Hz)
152− -> UTCTime
153− -- ^ Baseline time for events
154− -> m (Event t TickInfo)
155−poissonLossy rnd rate t0 = poissonLossyFrom rnd rate t0 =<< getPostBuild
156−
157−-- | Send events with inhomogeneous Poisson timing with the given basis
158−-- and variable rate. Provide a maxRate that you expect to support.
159−inhomogeneousPoissonFrom
160− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
161− => g
162− -> Behavior t Double
163− -> Double
164− -> UTCTime
165− -> Event t a
166− -> m (Event t TickInfo)
167−inhomogeneousPoissonFrom rnd rate maxRate t0 e = do
168−
169− -- Create a thread for producing homogeneous poisson events
170− -- along with random Doubles (usage of Double's explained below)
171− ticksWithRateRand <- performEventAsync $
172− fmap callAtNextInterval e
173−
174− -- Filter homogeneous events according to associated
175− -- random values and the current rate parameter
176− return $ attachWithMaybe filterFun rate ticksWithRateRand
177−
178− where
179−
180− -- Inhomogeneous poisson processes are built from faster
181− -- homogeneous ones by randomly dropping events from the
182− -- fast process. For each fast homogeneous event, choose
183− -- a uniform random sample from (0, rMax). If the
184− -- inhomogeneous rate at this moment is greater than the
185− -- random sample, then keep this event, otherwise drop it
186− filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo
187− filterFun r (tInfo, p)
188− | r >= p = Just tInfo
189− | otherwise = Nothing
190−
191− callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0
192−
193− go tTargetLast lastGen cb lastN = do
194− t <- getCurrentTime
195−
196− -- Generate random numbers for this poisson interval (u)
197− -- and sample-retention likelihood (p)
198− let (u, nextGen) = randomR (0,1) lastGen
199− (p :: Double, nextGen') = randomR (0,maxRate) nextGen
200−
201− -- Inter-event interval is drawn from exponential
202− -- distribution accourding to u
203− let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime
204− nEvents = lastN + 1
205− alreadyElapsed = diffUTCTime t tTargetLast
206− tTarget = addUTCTime dt tTargetLast
207− thisDelay = realToFrac $ diffUTCTime tTarget t :: Double
208− Concurrent.delay $ ceiling $ thisDelay * 1000000
209− _ <- cb (TickInfo t nEvents alreadyElapsed, p)
210− go tTarget nextGen' cb nEvents
211−
212−-- | Send events with inhomogeneous Poisson timing with the given basis
213−-- and variable rate. Provide a maxRate that you expect to support
214−inhomogeneousPoisson
215− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
216− => g
217− -> Behavior t Double
218− -> Double
219− -> UTCTime
220− -> m (Event t TickInfo)
221−inhomogeneousPoisson rnd rate maxRate t0 =
222− inhomogeneousPoissonFrom rnd rate maxRate t0 =<< getPostBuild
223−
224−-- | Block occurrences of an Event until the given number of seconds elapses without
225−-- the Event firing, at which point the last occurrence of the Event will fire.
226−debounce :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
227−debounce dt e = do
228− n :: Dynamic t Integer <- count e
229− let tagged = attachPromptlyDynWith (,) n e
230− delayed <- delay dt tagged
231− return $ attachWithMaybe (\n' (t, v) -> if n' == t then Just v else Nothing) (current n) delayed
232−
233−-- | When the given 'Event' occurs, wait the given amount of time and collect
234−-- all occurrences during that time. Then, fire the output 'Event' with the
235−-- collected output.
236−batchOccurrences :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t (Seq a))
237−batchOccurrences t newValues = do
238− let f s x = (Just newState, out)
239− where newState = case x of
240− This a -> s |> a
241− That _ -> mempty
242− These a _ -> Seq.singleton a
243− out = case x of
244− This _ -> if Seq.null s then Just () else Nothing
245− That _ -> Nothing
246− These _ _ -> Just ()
247− rec (buffer, toDelay) <- mapAccumMaybe f mempty $ align newValues delayed
248− delayed <- delay t toDelay
249− return $ tag buffer delayed
250−
251−-- | Throttle an input event, ensuring that at least a given amount of time passes between occurrences of the output event. If the input event occurs too
252−-- frequently, the output event occurs with the most recently seen input value after the given delay passes since the last occurrence of the output.
253−-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
254−throttle :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
255−throttle t e = do
256− let f (immediate, buffer) x = case x of -- (Just newState, out)
257− This a -- If only the input event fires
258− | immediate -> -- and we're in immediate mode
259− -- Immediate mode turns off, and the buffer is empty.
260− -- We fire the output event with the input event value immediately.
261− (Just (False, Nothing), Just a)
262− | otherwise -> -- and we're not in immediate mode
263− -- Immediate mode remains off, and we replace the contents of the buffer (if any) with the input value.
264− -- We don't fire the output event.
265− (Just (False, Just a), Nothing)
266− That _ -> -- If only the delayed output event fires,
267− case buffer of
268− Nothing -> -- and the buffer is empty:
269− -- Immediate mode turns back on, and the buffer remains empty.
270− -- We don't fire.
271− (Just (True, Nothing), Nothing)
272− Just b -> -- and the buffer is full:
273− -- Immediate mode remains off, and the buffer is cleared.
274− -- We fire with the buffered value.
275− (Just (False, Nothing), Just b)
276− These a _ -> -- If both the input and delayed output event fire simultaneously:
277− -- Immediate mode turns off, and the buffer is empty.
278− -- We fire with the input event's value, as it is the most recent we have seen at this moment.
279− (Just (False, Nothing), Just a)
280− rec (_, outE) <- mapAccumMaybeDyn f (True, Nothing) $ align e delayed -- We start in immediate mode with an empty buffer.
281− delayed <- delay t outE
282− return outE
283−
284−data ThrottleState b
285− = ThrottleState_Immediate
286− | ThrottleState_Buffered (ThrottleBuffer b)
287− deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
288−
289−data ThrottleBuffer b
290− = ThrottleBuffer_Empty -- Empty conflicts with lens, and hiding it would require turning
291− -- on PatternSynonyms
292− | ThrottleBuffer_Full b
293− deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
294−
295−instance Semigroup b => Semigroup (ThrottleBuffer b) where
296− x <> y = case x of
297− ThrottleBuffer_Empty -> y
298− ThrottleBuffer_Full b1 -> case y of
299− ThrottleBuffer_Empty -> x
300− ThrottleBuffer_Full b2 -> ThrottleBuffer_Full $ b1 <> b2
301− {-# INLINE (<>) #-}
302−
303−instance Semigroup b => Monoid (ThrottleBuffer b) where
304− mempty = ThrottleBuffer_Empty
305− {-# INLINE mempty #-}
306− mappend = (<>)
307− {-# INLINE mappend #-}
308−
309−-- | Throttle an input event, ensuring that the output event doesn't occur more often than you are ready for it. If the input event occurs too
310−-- frequently, the output event will contain semigroup-based summaries of the input firings that happened since the last output firing.
311−-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
312−-- The first parameter is a function that receives access to the output event, and should construct an event that fires when the receiver is
313−-- ready for more input. For example, using @delay 20@ would give a simple time-based throttle.
314−--
315−-- NB: The provided lag function must *actually* delay the event.
316−throttleBatchWithLag :: (MonadFix m, MonadHold t m, PerformEvent t m, Semigroup a) => (Event t () -> m (Event t ())) -> Event t a -> m (Event t a)
317−-- Invariants:
318−-- * Immediate mode must turn off whenever output is produced.
319−-- * Output must be produced whenever immediate mode turns from on to off.
320−-- * Immediate mode can only go from off to on when the delayed event fires.
321−-- * Every input firing must go into either an immediate output firing or the
322−-- buffer, but not both.
323−-- * An existing full buffer must either stay in the buffer or go to output,
324−-- but not both.
325−throttleBatchWithLag lag e = do
326− let f state x = case x of -- (Just $ newState, out)
327− This a -> -- If only the input event fires
328− case state of
329− ThrottleState_Immediate -> -- and we're in immediate mode
330− -- Immediate mode turns off, and the buffer is empty.
331− -- We fire the output event with the input event value immediately.
332− (Just $ ThrottleState_Buffered $ ThrottleBuffer_Empty, Just a)
333− ThrottleState_Buffered b -> -- and we're not in immediate mode
334− -- Immediate mode remains off, and we accumulate the input value.
335− -- We don't fire the output event.
336− (Just $ ThrottleState_Buffered $ b <> ThrottleBuffer_Full a, Nothing)
337− That _ -> -- If only the delayed output event fires,
338− case state of
339− ThrottleState_Immediate -> -- and we're in immediate mode
340− -- Nothing happens.
341− (Nothing, Nothing)
342− ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
343− -- Immediate mode turns back on, and the buffer remains empty.
344− -- We don't fire.
345− (Just ThrottleState_Immediate, Nothing)
346− ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
347− -- Immediate mode remains off, and the buffer is cleared.
348− -- We fire with the buffered value.
349− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just b)
350− These a _ -> -- If both the input and delayed output event fire simultaneously:
351− case state of
352− ThrottleState_Immediate -> -- and we're in immediate mode
353− -- Immediate mode turns off, and the buffer is empty.
354− -- We fire with the input event's value, as it is the most recent we have seen at this moment.
355− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
356− ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
357− -- Immediate mode stays off, and the buffer remains empty.
358− -- We fire with the input event's value.
359− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
360− ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
361− -- Immediate mode remains off, and the buffer is cleared.
362− -- We fire with everything including the buffered value.
363− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just (b <> a))
364− rec (_stateDyn, outE) <- mapAccumMaybeDyn f
365− ThrottleState_Immediate -- We start in immediate mode with an empty buffer.
366− (align e delayed)
367− delayed <- lag (void outE)
368− return outE
369−
370−#ifdef USE_TEMPLATE_HASKELL
371−makeLensesWith (lensRules & simpleLenses .~ True) ''TickInfo
372−#else
373−tickInfo_lastUTC :: Lens' TickInfo UTCTime
374−tickInfo_lastUTC f (TickInfo x1 x2 x3) = (\y -> TickInfo y x2 x3) <$> f x1
375−{-# INLINE tickInfo_lastUTC #-}
376−
377−tickInfo_n :: Lens' TickInfo Integer
378−tickInfo_n f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 y x3) <$> f x2
379−{-# INLINE tickInfo_n #-}
380−
381−tickInfo_alreadyElapsed :: Lens' TickInfo NominalDiffTime
382−tickInfo_alreadyElapsed f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 x2 y) <$> f x3
383−{-# INLINE tickInfo_alreadyElapsed #-}
384−#endif
src/Reflex/TriggerEvent/Base.hsdeleted−148
@@ -1,148 +0,0 @@
1−-- | This module defines 'TriggerEventT', the standard implementation of
2−-- 'TriggerEvent'.
3−{-# LANGUAGE DeriveFunctor #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE TypeFamilies #-}
8−module Reflex.TriggerEvent.Base
9− ( TriggerEventT (..)
10− , runTriggerEventT
11− , askEvents
12− , TriggerInvocation (..)
13− , EventTriggerRef (..)
14− ) where
15−
16−import Control.Applicative (liftA2)
17−import Control.Concurrent
18−import Control.Monad.Exception
19−import Control.Monad.Primitive
20−import Control.Monad.Reader
21−import Control.Monad.Ref
22−import Data.Coerce
23−import Data.Dependent.Sum
24−import Data.IORef
25−import Data.Monoid ((<>))
26−import qualified Data.Semigroup as S
27−import Reflex.Class
28−import Reflex.Adjustable.Class
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.PostBuild.Class
32−import Reflex.TriggerEvent.Class
33−
34−-- | A value with which to fire an 'Event', as well as a callback to invoke
35−-- after its propagation has completed.
36−data TriggerInvocation a = TriggerInvocation a (IO ())
37−
38−-- | A reference to an 'EventTrigger' suitable for firing with 'TriggerEventT'.
39−newtype EventTriggerRef t a = EventTriggerRef { unEventTriggerRef :: IORef (Maybe (EventTrigger t a)) }
40−
41−-- | A basic implementation of 'TriggerEvent'.
42−newtype TriggerEventT t m a = TriggerEventT { unTriggerEventT :: ReaderT (Chan [DSum (EventTriggerRef t) TriggerInvocation]) m a }
43− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
44−
45−-- | Run a 'TriggerEventT' action. The argument should be a 'Chan' into which
46−-- 'TriggerInvocation's can be passed; it is expected that some other thread
47−-- will be responsible for popping values out of the 'Chan' and firing their
48−-- 'EventTrigger's.
49−runTriggerEventT :: TriggerEventT t m a -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a
50−runTriggerEventT = runReaderT . unTriggerEventT
51−
52−instance MonadTrans (TriggerEventT t) where
53− {-# INLINABLE lift #-}
54− lift = TriggerEventT . lift
55−
56−instance PrimMonad m => PrimMonad (TriggerEventT t m) where
57− type PrimState (TriggerEventT t m) = PrimState m
58− {-# INLINABLE primitive #-}
59− primitive = lift . primitive
60−
61−instance PerformEvent t m => PerformEvent t (TriggerEventT t m) where
62− type Performable (TriggerEventT t m) = Performable m
63− {-# INLINABLE performEvent_ #-}
64− performEvent_ e = lift $ performEvent_ e
65− {-# INLINABLE performEvent #-}
66− performEvent e = lift $ performEvent e
67−
68−instance PostBuild t m => PostBuild t (TriggerEventT t m) where
69− {-# INLINABLE getPostBuild #-}
70− getPostBuild = lift getPostBuild
71−
72−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (TriggerEventT t m) where
73− {-# INLINABLE newEventWithTrigger #-}
74− newEventWithTrigger = lift . newEventWithTrigger
75− {-# INLINABLE newFanEventWithTrigger #-}
76− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
77−
78−instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (TriggerEventT t m) where
79− {-# INLINABLE newTriggerEvent #-}
80− newTriggerEvent = do
81− (e, t) <- newTriggerEventWithOnComplete
82− return (e, \a -> t a $ return ())
83− {-# INLINABLE newTriggerEventWithOnComplete #-}
84− newTriggerEventWithOnComplete = do
85− events <- askEvents
86− (eResult, reResultTrigger) <- lift newEventWithTriggerRef
87− return . (,) eResult $ \a cb ->
88− writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
89− {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
90− newEventWithLazyTriggerWithOnComplete f = do
91− events <- askEvents
92− lift . newEventWithTrigger $ \t ->
93− f $ \a cb -> do
94− reResultTrigger <- newRef $ Just t
95− writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
96−
97−instance MonadRef m => MonadRef (TriggerEventT t m) where
98− type Ref (TriggerEventT t m) = Ref m
99− {-# INLINABLE newRef #-}
100− newRef = lift . newRef
101− {-# INLINABLE readRef #-}
102− readRef = lift . readRef
103− {-# INLINABLE writeRef #-}
104− writeRef r = lift . writeRef r
105−
106−instance MonadAtomicRef m => MonadAtomicRef (TriggerEventT t m) where
107− {-# INLINABLE atomicModifyRef #-}
108− atomicModifyRef r = lift . atomicModifyRef r
109−
110−instance MonadSample t m => MonadSample t (TriggerEventT t m) where
111− {-# INLINABLE sample #-}
112− sample = lift . sample
113−
114−instance MonadHold t m => MonadHold t (TriggerEventT t m) where
115− {-# INLINABLE hold #-}
116− hold v0 v' = lift $ hold v0 v'
117− {-# INLINABLE holdDyn #-}
118− holdDyn v0 v' = lift $ holdDyn v0 v'
119− {-# INLINABLE holdIncremental #-}
120− holdIncremental v0 v' = lift $ holdIncremental v0 v'
121− {-# INLINABLE buildDynamic #-}
122− buildDynamic a0 = lift . buildDynamic a0
123− {-# INLINABLE headE #-}
124− headE = lift . headE
125−
126−instance Adjustable t m => Adjustable t (TriggerEventT t m) where
127− {-# INLINABLE runWithReplace #-}
128− runWithReplace (TriggerEventT a0) a' = TriggerEventT $ runWithReplace a0 (coerceEvent a')
129− {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
130− traverseIntMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseIntMapWithKeyWithAdjust (coerce . f) dm0 dm'
131− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
132− traverseDMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
133− {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}
134− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
135−
136−-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
137−instance (Monoid a, Applicative m) => Monoid (TriggerEventT t m a) where
138− mempty = pure mempty
139− mappend = (<>)
140−
141−instance (S.Semigroup a, Applicative m) => S.Semigroup (TriggerEventT t m a) where
142− (<>) = liftA2 (S.<>)
143−
144−
145−-- | Retrieve the current 'Chan'; event trigger invocations pushed into it will
146−-- be fired.
147−askEvents :: Monad m => TriggerEventT t m (Chan [DSum (EventTriggerRef t) TriggerInvocation])
148−askEvents = TriggerEventT ask
src/Reflex/TriggerEvent/Class.hsdeleted−49
@@ -1,49 +0,0 @@
1−-- | This module defines 'TriggerEvent', which describes actions that may create
2−-- new 'Event's that can be triggered from 'IO'.
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE UndecidableInstances #-}
6−module Reflex.TriggerEvent.Class
7− ( TriggerEvent (..)
8− ) where
9−
10−import Reflex.Class
11−
12−import Control.Monad.Reader
13−import Control.Monad.State
14−import qualified Control.Monad.State.Strict as Strict
15−
16−--TODO: Shouldn't have IO hard-coded
17−-- | 'TriggerEvent' represents actions that can create 'Event's that can be
18−-- triggered by 'IO' actions.
19−class Monad m => TriggerEvent t m | m -> t where
20− -- | Create a triggerable 'Event'. Whenever the resulting function is called,
21− -- the resulting 'Event' will fire at some point in the future. Note that
22− -- this may not be synchronous.
23− newTriggerEvent :: m (Event t a, a -> IO ())
24− -- | Like 'newTriggerEvent', but the callback itself takes another callback,
25− -- to be invoked once the requested 'Event' occurrence has finished firing.
26− -- This allows synchronous operation.
27− newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow
28− -- | Like 'newTriggerEventWithOnComplete', but with setup and teardown. This
29− -- relatively complex type signature allows any external listeners to be
30− -- subscribed lazily and then removed whenever the returned 'Event' is no
31− -- longer being listened to. Note that the setup/teardown may happen multiple
32− -- times, and there is no guarantee that the teardown will be executed
33− -- promptly, or even at all, in the case of program termination.
34− newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)
35−
36−instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
37− newTriggerEvent = lift newTriggerEvent
38− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
39− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
40−
41−instance TriggerEvent t m => TriggerEvent t (StateT s m) where
42− newTriggerEvent = lift newTriggerEvent
43− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
44− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
45−
46−instance TriggerEvent t m => TriggerEvent t (Strict.StateT s m) where
47− newTriggerEvent = lift newTriggerEvent
48− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
49− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
src/Reflex/Widget/Basic.hsdeleted−44
@@ -1,44 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExplicitForAll #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−{-# LANGUAGE RecursiveDo #-}
5−#ifdef USE_REFLEX_OPTIMIZER
6−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
7−#endif
8−
9−module Reflex.Widget.Basic where
10−
11−import Control.Monad.Fix (MonadFix)
12−import Data.Map (Map)
13−
14−import Reflex.Class
15−import Reflex.Adjustable.Class
16−import Reflex.Patch.MapWithMove
17−
18−
19−-- | Build sortable content in such a way that re-sorting it can cause minimal
20−-- disruption to an existing context.
21−--
22−-- Naively re-sorting a list of images would destroy every image and add them back
23−-- in the new order. This framework is able to avoid that by preserving the
24−-- identity of each image and simply moving it to the new location.
25−--
26−-- Example:
27−--
28−-- > let sortByFst = buttonA $> comparing fst
29−-- > sortBySnd = buttonB $> comparing snd
30−-- > sortEvent = leftmost [sortByFst, sortBySnd]
31−-- > sortableList
32−-- > (\k v -> text $ "\n" ++ show k ++ " " ++ v) -- show each element on a new line
33−-- > (Map.fromList $ zip [0..] [(3, "a"), (2, "b"), (1, "c")])
34−-- > sortEvent
35−sortableList :: forall t m k v a. (MonadHold t m, MonadFix m, Adjustable t m, Ord k)
36− => (k -> v -> m a) -- ^ Function to render the content for each key/value pair
37− -> Map k v -- ^ The sortable list with an initial ordering determined by the @Map@ keys in ascending order
38− -> Event t (v -> v -> Ordering) -- ^ An event carrying a sort function for the list
39− -> m (Map k a)
40−sortableList f m0 reSortFunc = do
41− rec let reSortPatch = attachWith (flip patchThatSortsMapWith) (currentIncremental m) reSortFunc
42− m <- holdIncremental m0 reSortPatch
43− (results, _) <- mapMapWithAdjustWithMove f m0 reSortPatch
44− pure results
src/Reflex/Workflow.hsdeleted−50
@@ -1,50 +0,0 @@
1−{-# LANGUAGE RecursiveDo #-}
2−{-# LANGUAGE ScopedTypeVariables #-}
3−-- |
4−-- Module:
5−-- Reflex.Workflow
6−-- Description:
7−-- Provides a convenient way to describe a series of interrelated widgets that
8−-- can send data to, invoke, and replace one another. Useful for modeling user interface
9−-- "workflows."
10−module Reflex.Workflow (
11− Workflow (..)
12− , workflow
13− , workflowView
14− , mapWorkflow
15− , mapWorkflowCheap
16− ) where
17−
18−import Control.Arrow ((***))
19−import Control.Monad.Fix (MonadFix)
20−
21−import Reflex.Class
22−import Reflex.Adjustable.Class
23−import Reflex.Network
24−import Reflex.NotReady.Class
25−import Reflex.PostBuild.Class
26−
27−-- | A widget in a workflow
28−-- When the 'Event' returned by a 'Workflow' fires, the current 'Workflow' is replaced by the one inside the firing 'Event'. A series of 'Workflow's must share the same return type.
29−newtype Workflow t m a = Workflow { unWorkflow :: m (a, Event t (Workflow t m a)) }
30−
31−-- | Runs a 'Workflow' and returns the 'Dynamic' result of the 'Workflow' (i.e., a 'Dynamic' of the value produced by the current 'Workflow' node, and whose update 'Event' fires whenever one 'Workflow' is replaced by another).
32−workflow :: forall t m a. (Reflex t, Adjustable t m, MonadFix m, MonadHold t m) => Workflow t m a -> m (Dynamic t a)
33−workflow w0 = do
34− rec eResult <- networkHold (unWorkflow w0) $ fmap unWorkflow $ switch $ snd <$> current eResult
35− return $ fmap fst eResult
36−
37−-- | Similar to 'workflow', but outputs an 'Event' that fires at post-build time and whenever the current 'Workflow' is replaced by the next 'Workflow'.
38−workflowView :: forall t m a. (Reflex t, NotReady t m, Adjustable t m, MonadFix m, MonadHold t m, PostBuild t m) => Workflow t m a -> m (Event t a)
39−workflowView w0 = do
40− rec eResult <- networkView . fmap unWorkflow =<< holdDyn w0 eReplace
41− eReplace <- fmap switch $ hold never $ fmap snd eResult
42− return $ fmap fst eResult
43−
44−-- | Map a function over a 'Workflow', possibly changing the return type.
45−mapWorkflow :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
46−mapWorkflow f (Workflow x) = Workflow (fmap (f *** fmap (mapWorkflow f)) x)
47−
48−-- | Map a "cheap" function over a 'Workflow'. Refer to the documentation for 'pushCheap' for more information and performance considerations.
49−mapWorkflowCheap :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
50−mapWorkflowCheap f (Workflow x) = Workflow (fmap (f *** fmapCheap (mapWorkflowCheap f)) x)
test/EventWriterT.hsdeleted−134
@@ -1,134 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE BangPatterns #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE RecursiveDo #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−module Main where
8−
9−import Control.Lens
10−import Control.Monad
11−import Control.Monad.Fix
12−import qualified Data.Dependent.Map as DMap
13−import Data.Functor.Misc
14−import qualified Data.Map as M
15−import Data.These
16−
17−#if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))
18−import Data.These.Lens
19−#endif
20−
21−import Reflex
22−import Reflex.EventWriter.Base
23−import Test.Run
24−
25−main :: IO ()
26−main = do
27− os1@[[Just [10,9,8,7,6,5,4,3,2,1]]] <- runApp' (unwrapApp testOrdering) $
28− [ Just ()
29− ]
30− print os1
31− os2@[[Just [1,3,5,7,9]],[Nothing,Nothing],[Just [2,4,6,8,10]],[Just [2,4,6,8,10],Nothing]]
32− <- runApp' (unwrapApp testSimultaneous) $ map Just $
33− [ This ()
34− , That ()
35− , This ()
36− , These () ()
37− ]
38− print os2
39− os3@[[Nothing, Just [2]]] <- runApp' (unwrapApp testMoribundTellEvent) [Just ()]
40− print os3
41− os4@[[Nothing, Just [2]]] <- runApp' (unwrapApp testMoribundTellEventDMap) [Just ()]
42− print os4
43− os5@[[Nothing, Just [1, 2]]] <- runApp' (unwrapApp testLiveTellEventDMap) [Just ()]
44− print os5
45− os6 <- runApp' (unwrapApp delayedPulse) [Just ()]
46− print os6
47− let ![[Nothing, Nothing]] = os6
48− return ()
49−
50−unwrapApp :: (Reflex t, Monad m) => (a -> EventWriterT t [Int] m ()) -> a -> m (Event t [Int])
51−unwrapApp x appIn = do
52− ((), e) <- runEventWriterT $ x appIn
53− return e
54−
55−testOrdering :: (Reflex t, Monad m) => Event t () -> EventWriterT t [Int] m ()
56−testOrdering pulse = forM_ [10,9..1] $ \i -> tellEvent ([i] <$ pulse)
57−
58−testSimultaneous :: (Reflex t, Adjustable t m, MonadHold t m) => Event t (These () ()) -> EventWriterT t [Int] m ()
59−testSimultaneous pulse = do
60− let e0 = fmapMaybe (^? here) pulse
61− e1 = fmapMaybe (^? there) pulse
62− forM_ [1,3..9] $ \i -> runWithReplace (tellEvent ([i] <$ e0)) $ ffor e1 $ \_ -> tellEvent ([i+1] <$ e0)
63−
64−-- | Test that a widget telling and event which fires at the same time it has been replaced
65−-- doesn't count along with the new widget.
66−testMoribundTellEvent
67− :: forall t m
68− . ( Reflex t
69− , Adjustable t m
70− , MonadHold t m
71− , MonadFix m
72− )
73− => Event t ()
74− -> EventWriterT t [Int] m ()
75−testMoribundTellEvent pulse = do
76− rec let tellIntOnReplace :: Int -> EventWriterT t [Int] m ()
77− tellIntOnReplace x = tellEvent $ [x] <$ rwrFinished
78− (_, rwrFinished) <- runWithReplace (tellIntOnReplace 1) $ tellIntOnReplace 2 <$ pulse
79− return ()
80−
81−-- | The equivalent of 'testMoribundTellEvent' for 'traverseDMapWithKeyWithAdjust'.
82−testMoribundTellEventDMap
83− :: forall t m
84− . ( Reflex t
85− , Adjustable t m
86− , MonadHold t m
87− , MonadFix m
88− )
89− => Event t ()
90− -> EventWriterT t [Int] m ()
91−testMoribundTellEventDMap pulse = do
92− rec let tellIntOnReplace :: Int -> EventWriterT t [Int] m ()
93− tellIntOnReplace x = tellEvent $ [x] <$ rwrFinished
94− (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-
95− traverseDMapWithKeyWithAdjust
96− (\(Const2 ()) (Identity v) -> Identity . const v <$> tellIntOnReplace v)
97− (mapToDMap $ M.singleton () 1)
98− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)
99− return ()
100−
101−-- | Ensures that elements which are _not_ removed can still fire 'tellEvent's
102−-- during the same frame as other elements are updated.
103−testLiveTellEventDMap
104− :: forall t m
105− . ( Reflex t
106− , Adjustable t m
107− , MonadHold t m
108− , MonadFix m
109− )
110− => Event t ()
111− -> EventWriterT t [Int] m ()
112−testLiveTellEventDMap pulse = do
113− rec let tellIntOnReplace :: Int -> EventWriterT t [Int] m ()
114− tellIntOnReplace x = tellEvent $ [x] <$ rwrFinished
115− (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-
116− traverseDMapWithKeyWithAdjust
117− (\(Const2 k) (Identity ()) -> Identity <$> tellIntOnReplace k)
118− (mapToDMap $ M.singleton 1 ())
119− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)
120− return ()
121−
122−delayedPulse
123− :: forall t m
124− . ( Reflex t
125− , Adjustable t m
126− , MonadHold t m
127− , MonadFix m
128− )
129− => Event t ()
130− -> EventWriterT t [Int] m ()
131−delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do
132− -- This has the effect of delaying pulse' from pulse
133− (_, pulse') <- runWithReplace (pure ()) $ pure [1] <$ pulse
134− tellEvent pulse'
test/GC.hsdeleted−101
@@ -1,101 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE GADTs #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE RankNTypes #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE TypeFamilies #-}
7−module Main where
8−
9−import Control.Monad
10−import Control.Monad.IO.Class
11−import Control.Monad.Ref
12−import Data.Align
13−import Data.Dependent.Map (DMap)
14−import qualified Data.Dependent.Map as DMap
15−import Data.Dependent.Sum
16−import Data.Functor.Identity
17−import Data.GADT.Compare
18−import Data.IORef
19−import Data.Semigroup
20−import Data.These
21−
22−import Data.Functor.Misc
23−import Reflex.Patch
24−
25−import qualified Reflex.Host.Class as Host
26−import qualified Reflex.Spider.Internal as S
27−
28−import System.Exit
29−import System.Mem
30−import Data.Coerce
31−
32−main :: IO ()
33−main = do
34− ref <- newIORef Nothing
35− hostPerf ref
36− readIORef ref >>= maybe exitFailure (putStrLn . ("Result " <>) . show)
37−
38−hostPerf :: IORef (Maybe Int) -> IO ()
39−hostPerf ref = S.runSpiderHost $ do
40− ---- body
41− liftIO $ putStrLn "#creating triggers"
42− (response', responseTrigger) <- Host.newEventWithTriggerRef
43− (eadd', addTriggerRef) <- Host.newEventWithTriggerRef
44− let response = S.unSpiderEvent response'
45− eadd = S.unSpiderEvent eadd'
46− liftIO $ putStrLn "#creating event graph"
47− eventToPerform <- Host.runHostFrame $ do
48− (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity))
49− <- S.SpiderHostFrame
50− $ fmap ( S.mergeG coerce
51− . S.dynamicHold)
52− $ S.hold DMap.empty
53− -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained
54− $ (\e -> S.Event $ \sub -> do
55− (s, o) <- S.subscribeAndRead e $ sub
56− { S.subscriberPropagate = S.subscriberPropagate sub
57− }
58− return (s, o))
59− $ runIdentity . runIdentity <$> S.selectG
60− (S.fanG $ S.pushCheap (return . Just . mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e)) response)
61− (WrapArg Request)
62− return $ alignWith (mergeThese (<>))
63− (flip S.pushCheap eadd $ \_ -> return $ Just $ DMap.singleton Request $ do
64− liftIO $ putStrLn "#eadd fired"
65− return $ PatchDMap $ DMap.singleton (Const2 (1 :: Int)) $ ComposeMaybe $ Just
66− $ S.pushCheap (return . Just . DMap.singleton Action . (\_ -> liftIO (writeIORef ref (Just 1)))) $ eadd)
67− (flip S.pushCheap reqMap $ \m -> return $ Just $ mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m)
68− ---- epilogue
69− eventToPerformHandle <- Host.subscribeEvent (S.SpiderEvent eventToPerform)
70− liftIO $ putStrLn "#performing GC" >> performMajorGC
71− liftIO $ putStrLn "#attempting to fire eadd"
72− mAddTrigger <- readRef addTriggerRef
73− forM_ mAddTrigger $ \t -> replicateM_ 2 $ do
74− liftIO $ putStrLn "#firing eadd"
75− mToPerform <- Host.fireEventsAndRead [t :=> Identity ()] $ sequence =<< Host.readEvent eventToPerformHandle
76− case mToPerform of
77− Nothing -> return ()
78− Just toPerform -> do
79− responses <- Host.runHostFrame $ DMap.traverseWithKey (\_ v -> Identity <$> v) toPerform
80− mrt <- readRef responseTrigger
81− let followupEventTriggers = case mrt of
82− Just rt -> [rt :=> Identity responses]
83− Nothing -> []
84− Host.fireEventsAndRead followupEventTriggers $ return ()
85− return ()
86− return ()
87−
88−data Tell a where
89− Action :: Tell ()
90− Request :: Tell (PatchDMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) (S.Event S.Global))
91−
92−instance GEq Tell where
93− geq Action Action = Just Refl
94− geq Request Request = Just Refl
95− geq _ _ = Nothing
96−
97−instance GCompare Tell where
98− gcompare Action Action = GEQ
99− gcompare Request Request = GEQ
100− gcompare Action Request = GLT
101− gcompare Request Action = GGT
test/QueryT.hsdeleted−142
@@ -1,142 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE StandaloneDeriving #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−
11−import Control.Lens
12−import Control.Monad.Fix
13−import Data.Align
14−import qualified Data.AppendMap as AMap
15−import Data.Functor.Misc
16−import Data.Map (Map)
17−import qualified Data.Map as Map
18−import Data.Map.Monoidal (MonoidalMap)
19−import Data.Semigroup
20−import Data.These
21−
22−#if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))
23−import Data.These.Lens
24−#endif
25−
26−import Reflex
27−import Reflex.Patch.MapWithMove
28−import Test.Run
29−
30−newtype MyQuery = MyQuery SelectedCount
31− deriving (Show, Read, Eq, Ord, Monoid, Semigroup, Additive, Group)
32−
33−instance Query MyQuery where
34− type QueryResult MyQuery = ()
35− crop _ _ = ()
36−
37−instance (Ord k, Query a, Eq (QueryResult a), Align (MonoidalMap k)) => Query (Selector k a) where
38− type QueryResult (Selector k a) = Selector k (QueryResult a)
39− crop q r = undefined
40−
41−newtype Selector k a = Selector { unSelector :: MonoidalMap k a }
42− deriving (Show, Read, Eq, Ord, Functor)
43−
44−#if !(MIN_VERSION_monoidal_containers(0,4,1))
45−deriving instance Ord k => Align (MonoidalMap k)
46−#endif
47−
48−instance (Ord k, Eq a, Monoid a, Align (MonoidalMap k)) => Semigroup (Selector k a) where
49− (Selector a) <> (Selector b) = Selector $ fmapMaybe id $ f a b
50− where
51− f = alignWith $ \case
52− This x -> Just x
53− That y -> Just y
54− These x y ->
55− let z = x `mappend` y
56− in if z == mempty then Nothing else Just z
57−
58−instance (Ord k, Eq a, Monoid a, Align (MonoidalMap k)) => Monoid (Selector k a) where
59− mempty = Selector AMap.empty
60− mappend = (<>)
61−
62−instance (Eq a, Ord k, Group a, Align (MonoidalMap k)) => Group (Selector k a) where
63− negateG = fmap negateG
64−
65−instance (Eq a, Ord k, Group a, Align (MonoidalMap k)) => Additive (Selector k a)
66−
67−main :: IO ()
68−main = do
69− [0, 1, 1, 0] <- fmap (map fst . concat) $
70− runApp (testQueryT testRunWithReplace) () $ map (Just . That) $
71− [ That (), This (), That () ]
72− [0, 1, 1, 0] <- fmap (map fst . concat) $
73− runApp (testQueryT testSequenceDMapWithAdjust) () $ map (Just . That) $
74− [ That (), This (), That () ]
75− [0, 1, 1, 0] <- fmap (map fst . concat) $
76− runApp (testQueryT testSequenceDMapWithAdjustWithMove) () $ map (Just . That) $
77− [ That (), This (), That () ]
78− return ()
79−
80−testQueryT :: (Reflex t, MonadFix m)
81− => (Event t () -> Event t () -> QueryT t (Selector Int MyQuery) m ())
82− -> AppIn t () (These () ())
83− -> m (AppOut t Int Int)
84−testQueryT w (AppIn _ pulse) = do
85− let replace = fmapMaybe (^? here) pulse
86− increment = fmapMaybe (^? there) pulse
87− (_, q) <- runQueryT (w replace increment) $ pure mempty
88− let qDyn = head . AMap.keys . unSelector <$> incrementalToDynamic q
89− return $ AppOut
90− { _appOut_behavior = current qDyn
91− , _appOut_event = updated qDyn
92− }
93−
94−testRunWithReplace :: ( Reflex t
95− , Adjustable t m
96− , MonadHold t m
97− , MonadFix m
98− , MonadQuery t (Selector Int MyQuery) m)
99− => Event t ()
100− -> Event t ()
101− -> m ()
102−testRunWithReplace replace increment = do
103− let w = do
104− n <- count increment
105− queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
106− _ <- runWithReplace w $ w <$ replace
107− return ()
108−
109−testSequenceDMapWithAdjust :: ( Reflex t
110− , Adjustable t m
111− , MonadHold t m
112− , MonadFix m
113− , MonadQuery t (Selector Int MyQuery) m)
114− => Event t ()
115− -> Event t ()
116− -> m ()
117−testSequenceDMapWithAdjust replace increment = do
118− _ <- listHoldWithKey (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do
119− n <- count increment
120− queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
121− return ()
122−
123−testSequenceDMapWithAdjustWithMove :: ( Reflex t
124− , Adjustable t m
125− , MonadHold t m
126− , MonadFix m
127− , MonadQuery t (Selector Int MyQuery) m)
128− => Event t ()
129− -> Event t ()
130− -> m ()
131−testSequenceDMapWithAdjustWithMove replace increment = do
132− _ <- listHoldWithKeyWithMove (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do
133− n <- count increment
134− queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
135− return ()
136−
137−-- scam it out to test traverseDMapWithAdjustWithMove
138−listHoldWithKeyWithMove :: forall t m k v a. (Ord k, MonadHold t m, Adjustable t m) => Map k v -> Event t (Map k (Maybe v)) -> (k -> v -> m a) -> m (Dynamic t (Map k a))
139−listHoldWithKeyWithMove m0 m' f = do
140− (n0, n') <- mapMapWithAdjustWithMove f m0 $ ffor m' $ PatchMapWithMove . Map.map (\v -> NodeInfo (maybe From_Delete From_Insert v) Nothing)
141− incrementalToDynamic <$> holdIncremental n0 n'
142−-- -}
test/Reflex/Bench/Focused.hsdeleted−381
@@ -1,381 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE RecursiveDo #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeSynonymInstances #-}
11−
12−module Reflex.Bench.Focused where
13−
14−import Reflex
15−import Reflex.TestPlan
16−
17−import Control.Applicative
18−import Control.Monad
19−import Control.Monad.Fix
20−import Control.Monad.Identity
21−import Data.Traversable (for, traverse)
22−
23−import qualified Data.Dependent.Map as DMap
24−import Data.Map (Map)
25−import qualified Data.Map as Map
26−import Data.Maybe
27−
28−import Data.Functor.Misc
29−
30−import Data.List
31−import Data.List.Split
32−import Data.Tuple
33−
34−import Data.Monoid
35−import Data.Word
36−
37−import Control.DeepSeq
38−
39−import Prelude hiding (concat, sum)
40−
41−
42−mergeTree :: Num a => (Monoid (f [a]), Functor f) => Int -> [f a] -> f a
43−mergeTree n es | length es <= n = sum' es
44− | otherwise = mergeTree n subTrees
45− where
46− merges = chunksOf n es
47− subTrees = map sum' merges
48− sum' = fmap sum . mconcat . fmap (fmap (:[]) )
49−
50−mergeListDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
51−mergeListDyn = mconcat . fmap (fmap pure)
52−
53−mergeTreeDyn :: (Num a, Reflex t) => Int -> [Dynamic t a] -> Dynamic t a
54−mergeTreeDyn n dyns | length dyns <= n = sumDyns dyns
55− | otherwise = mergeTreeDyn n $ fmap sumDyns merges
56− where
57− merges = chunksOf n dyns
58− sumDyns = fmap sum . mergeListDyn
59−
60−
61−
62−-- N events all firing for N frames
63−continuous :: TestPlan t m => Word -> Word -> m [Event t Word]
64−continuous n frames = for [1..n] $ \i -> plan $ (, i) <$> [1..frames]
65−
66−-- Fire N events once every P frames for total N frames (interspersed evenly)
67−occasional :: TestPlan t m => Word -> Word -> Word -> m [Event t Word]
68−occasional n period frames = traverse plan $ zipWith occs [1..] phases
69− where
70− phases = take (fromIntegral n) $ concat (repeat [1..period])
71− occs i phase = (, i) <$> [1, phase+1..frames]
72−
73−
74−
75−-- Event which never fires (but isn't 'never')
76−never' :: TestPlan t m => m (Event t Word)
77−never' = plan []
78−
79−
80−-- Event which fires once on first frame
81−event :: TestPlan t m => m (Event t Word)
82−event = plan [(1, 0)]
83−
84−-- Event which fires constantly over N frames
85−events :: TestPlan t m => Word -> m (Event t Word)
86−events n = plan $ (\i -> (i, i)) <$> [1..n]
87−
88−
89−-- N events all originating from one event
90−fmapFan :: Reflex t => Word -> Event t Word -> [Event t Word]
91−fmapFan n e = (\i -> (+i) <$> e) <$> [1..n]
92−
93−
94−-- Make a fan using the value in the event converting it to a singleton Map
95−-- use a fan of size n (key is the value mod n)
96−fanMerge :: Reflex t => Word -> Event t Word -> Event t Word
97−fanMerge n e = leftmost $ s <$> [0..n - 1] where
98− s k = select f (Const2 k)
99− f = fan (toMap <$> e)
100− toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k)
101−
102−-- Dumb version of the above using simple fmapMaybe to filter
103−fmapFanMerge :: Reflex t => Word -> Event t Word -> Event t Word
104−fmapFanMerge n e = leftmost $ s <$> [0..n - 1] where
105− s k = flip fmapMaybe e $ \j -> if k == j `mod` n
106− then Just k
107− else Nothing
108−
109−
110−
111−-- Create an Event with a Map which is dense to size N
112−denseMap :: TestPlan t m => Word -> m (Event t (Map Word Word))
113−denseMap n = plan [(1, m)] where
114− m = Map.fromList $ zip [1..n] [1..n]
115−
116−iter :: (a -> a) -> Word -> a -> a
117−iter _ 0 a = a
118−iter f n a = iter f (n - 1) (f a)
119−
120−iterM :: Monad m => (a -> m a) -> Word -> a -> m a
121−iterM _ 0 a = return a
122−iterM f n a = iterM f (n - 1) =<< f a
123−
124−fmapChain :: (Functor f) => Word -> f Word -> f Word
125−fmapChain = iter (fmap (+1))
126−
127−mapDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
128−mapDynChain = iterM (return . fmap (+1))
129−
130−joinDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
131−joinDynChain = iterM (\d -> return $ join $ fmap (const d) d)
132−
133−holdDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
134−holdDynChain = iterM (\d -> sample (current d) >>= flip holdDyn (updated d))
135−
136−buildDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
137−buildDynChain = iterM (\d -> do
138− let b = fmap (+1) (current d)
139− e = fmap (*2) (updated d)
140− buildDynamic (sample b) e)
141−
142−
143−combineDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
144−combineDynChain = iterM (\d -> return $ zipDynWith (+) d d)
145−
146−pingPong :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> Event t a -> m (Event t a)
147−pingPong e1 e2 = do
148− rec
149− d <- foldDyn (const swap) (e1, e2) e
150− let e = switch (fst <$> current d)
151− return e
152−
153−switchFactors :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
154−switchFactors 0 e = return e
155−switchFactors i e = do
156− b <- hold ((+1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)
157− switchFactors (i - 1) (switch b)
158−
159−
160−switchChain :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
161−switchChain = iterM (\e -> pingPong e ((+1) <$> e))
162−
163−
164−switchChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
165−switchChain2 = iterM (\e -> pingPong e ((+1) <$> leftmost [e, e]))
166−
167−switchPromptlyChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
168−switchPromptlyChain = iterM $ \e ->
169− switchPromptlyDyn <$> holdDyn e (e <$ e)
170−
171−
172−coinChain :: Reflex t => Word -> Event t Word -> Event t Word
173−coinChain = iter $ \e -> coincidence (e <$ e)
174−
175−fanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
176−fanMergeChain width = iter $ fanMerge width
177−
178−fmapFanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
179−fmapFanMergeChain width = iter $ fmapFanMerge width
180−
181−-- | Data type for a collection (a map) which is updated by providing differences
182−data UpdatedMap t k a = UpdatedMap (Map k a) (Event t (Map k (Maybe a)))
183−
184−-- This will hopefully become a primitive (faster!)
185−switchMergeEvents :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
186−switchMergeEvents mapChanges = switch . fmap mergeMap <$> holdMap mapChanges
187−
188−-- switchMergeMaybe :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
189−-- switchMergeMaybe (UpdatedMap initial changes) = switchMergeMap initial (fmap (fromMaybe never) <$> changes)
190−
191−switchMergeBehaviors :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Behavior t a) -> m (Behavior t (Map k a))
192−switchMergeBehaviors mapChanges = pull . joinMap <$> holdMap mapChanges
193− where joinMap m = traverse sample =<< sample m
194−
195−-- | Turn an UpdatedMap into a Dynamic by applying the differences to the initial value
196−holdMapDyn :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Dynamic t (Map k a))
197−holdMapDyn (UpdatedMap initial changes) = foldDyn (flip (Map.foldrWithKey modify)) initial changes
198−
199− where
200− modify k Nothing items = Map.delete k items
201− modify k (Just item) items = Map.insert k item items
202−
203−
204−-- | Hold an UpdatedMap as a behavior by applying differences to the initial value
205−holdMap :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Behavior t (Map k a))
206−holdMap = (current <$>) . holdMapDyn
207−
208−
209−increasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a)
210−increasingMerge xs = do
211− e <- planList (zipWith Map.singleton [1..] (Just <$> xs) ++ [reset])
212− return (UpdatedMap Map.empty e)
213− where
214− reset = Map.fromList $ zip [1..] (const Nothing <$> xs)
215−
216−decreasingMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
217−decreasingMerge xs = do
218− e <- planList (zipWith Map.singleton [1..] (const Nothing <$> xs) ++ [reset])
219− return (UpdatedMap initial e)
220− where
221− initial = Map.fromList $ zip [1..] xs
222− reset = Just <$> initial
223−
224−modifyMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
225−modifyMerge xs = do
226− e <- planList $ zipWith Map.singleton [1..] (Just <$> xs)
227− return (UpdatedMap initial e)
228− where
229− initial = Map.fromList $ zip [1..] xs
230−
231−
232−countMany :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Behavior t Int]
233−countMany = traverse (fmap current . count)
234−
235−countManyDyn :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Dynamic t Int]
236−countManyDyn = traverse count
237−
238−
239−-- Given a function which creates a sub-network (from a single event)
240−-- Create a plan which uses a switch to substitute it
241−switches :: TestPlan t m => Word -> (forall n. (MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> m (Event t a)
242−switches numFrames f = do
243− es <- events numFrames
244− switch <$> hold never (makeEvents es)
245−
246− where
247− makeEvents es = pushAlways (\n -> f (fmap (+n) es)) es
248−
249−
250−
251−-- Two sets of benchmarks, one which we're interested in testing subscribe time (as well as time to fire frames)
252−-- the other, which we're only interested in time for running frames
253−subscribing :: Word -> Word -> [(String, TestCase)]
254−subscribing n frames =
255− [ testSub "fmapFanMerge" $ return . mergeList . fmapFan n
256− , testSub "fanMerge" $ return . fanMerge n
257− , testSub "fmapFan/mergeTree" $ return . mergeTree 8 . fmapFan n
258− , testSub "fmapChain" $ return . fmapChain n
259− , testSub "switchChain" $ switchChain n
260− , testSub "switchPromptlyChain" $ switchPromptlyChain n
261− , testSub "switchFactors" $ switchFactors n
262− , testSub "coincidenceChain" $ return . coinChain n
263− ]
264−
265− where
266− testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)
267− testSub name test = testE name (switches frames test)
268−
269−-- Set of benchmark to test specifically merging dynamic collections
270−-- a pattern which occurs frequently in reflex-dom collections
271−merging :: Word -> [(String, TestCase)]
272−merging n =
273− [ testE "static events" $ mergeList <$> sparse
274− , testE "increasing events" $ switchMergeEvents =<< increasingMerge =<< sparse
275− , testE "decreasing events" $ switchMergeEvents =<< decreasingMerge =<< sparse
276− , testE "modify events" $ switchMergeEvents =<< modifyMerge =<< sparse
277−
278− , testB "static behaviors" $ pull . traverse sample <$> counters
279− , testB "increasing behaviors" $ switchMergeBehaviors =<< increasingMerge =<< counters
280− , testB "decreasing behaviors" $ switchMergeBehaviors =<< decreasingMerge =<< counters
281− , testB "modify behaviors" $ switchMergeBehaviors =<< modifyMerge =<< counters
282−
283−
284− -- , testE "increasing events/switchMerge" $ switchMergeMaybe =<< increasingMerge =<< sparse
285− -- , testE "decreasing events/switchMerge" $ switchMergeMaybe =<< decreasingMerge =<< sparse
286− -- , testE "modify events/switchMerge" $ switchMergeMaybe =<< modifyMerge =<< sparse
287− ]
288−
289− where
290− sparse :: TestPlan t m => m [Event t Word]
291− sparse = fmap (fmap (+1)) <$> occasional n 8 n
292−
293− counters :: TestPlan t m => m [Behavior t Int]
294− counters = countMany =<< sparse
295−
296−
297−
298−fans :: Word -> [(String, TestCase)]
299−fans n =
300− [ testE "fanMapChain" $ fanMergeChain n 10 <$> e
301− , testE "fmapFanMapChain" $ fmapFanMergeChain n 10 <$> e
302−
303− , testE "fanMerge " $ fanMerge n <$> events n
304−
305− , testE "fmapFanMerge " $ fmapFanMerge n <$> events n
306− , testE "triggerMerge" $ leftmost <$> for [1..n] (\i -> plan [(i, i)])
307−
308− ]
309− where
310−
311− e :: TestPlan t m => m (Event t Word)
312− e = events 100
313−
314−
315−
316−
317−dynamics :: Word -> [(String, TestCase)]
318−dynamics n =
319− [ testE "mapDynChain" $ fmap updated $ mapDynChain n =<< d
320− , testE "joinDynChain" $ fmap updated $ joinDynChain n =<< d
321− , testE "holdDynChain" $ fmap updated $ holdDynChain n =<< d
322− , testE "buildDynChain" $ fmap updated $ buildDynChain n =<< d
323− , testE "combineDynChain" $ fmap updated $ combineDynChain n =<< d
324− , testE "dense mergeTree" $ fmap (updated . mergeTreeDyn 8) dense
325− , testE "sparse mergeTree" $ fmap (updated . mergeTreeDyn 8) sparse
326− , testE "mergeDyn" $ fmap (updated . fmap sum . mergeListDyn) sparse
327− ] where
328−
329− d :: TestPlan t m => m (Dynamic t Word)
330− d = count =<< events 10
331−
332− sparse, dense :: TestPlan t m => m [Dynamic t Int]
333− sparse = countManyDyn =<< occasional n 8 16
334− dense = countManyDyn =<< continuous n 2
335−
336−
337−firing :: Word -> [(String, TestCase)]
338−firing n =
339− [ testE "fmapChain" $ fmapChain n <$> e
340− , testE "switchChain2" $ switchChain2 n =<< e
341− , testE "switchPromptlyChain" $ switchPromptlyChain n =<< e
342− , testE "switchFactors" $ switchFactors n =<< e
343− , testE "coincidenceChain" $ coinChain n <$> e
344−
345− , testE "dense mergeTree" $ mergeTree 8 <$> dense
346− , testE "sparse mergeTree" $ mergeTree 8 <$> sparse
347−
348− -- Triggers test failure in Spider
349− --, testE "runFrame" $ events n
350−
351− , testB "sum counters" $ do
352− counts <- counters
353− return $ pull $ sum <$> traverse sample counts
354−
355− , testB "pullChain" $ fmapChain n . current <$> (count =<< events 4)
356− , testB "pullChain2" $ do
357− es <- events 4
358− e' <- plan [(0, ())]
359−
360− b <- hold (constant 0) $
361− pushAlways (const $ fmapChain n <$> hold 0 es) e'
362−
363− return (join b)
364− , testB "counters/pullTree" $ mergeTree 8 <$> counters
365−
366− ]
367− where
368− e :: TestPlan t m => m (Event t Word)
369− e = events 10
370−
371− dense, sparse :: TestPlan t m => m [Event t Word]
372− dense = continuous n 2
373− sparse = occasional n 8 16
374−
375− counters :: TestPlan t m => m [Behavior t Int]
376− counters = countMany =<< sparse
377−
378−
379−
380−
381−
test/Reflex/Plan/Pure.hsdeleted−72
@@ -1,72 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GADTs #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−
9−module Reflex.Plan.Pure where
10−
11−import Reflex
12−import Reflex.Pure
13−import Reflex.TestPlan
14−
15−import Control.Applicative
16−import Control.Monad.Fix
17−import Control.Monad.State
18−import Data.IntMap (IntMap)
19−import qualified Data.IntMap as IntMap
20−import Data.IntSet (IntSet)
21−import qualified Data.IntSet as IntSet
22−
23−import Data.Bifunctor
24−import Data.Maybe
25−import Data.Monoid
26−import Prelude
27−
28−
29−mapToPureEvent :: IntMap a -> Event (Pure Int) a
30−mapToPureEvent m = Event $ flip IntMap.lookup m
31−
32−type TimeM = (->) Int
33−newtype PurePlan a = PurePlan { unPlan :: StateT IntSet TimeM a } deriving (Functor, Applicative, Monad, MonadFix)
34−
35−liftPlan :: TimeM a -> PurePlan a
36−liftPlan = PurePlan . lift
37−
38−instance MonadHold (Pure Int) PurePlan where
39− hold initial = liftPlan . hold initial
40− holdDyn initial = liftPlan . holdDyn initial
41− holdIncremental initial = liftPlan . holdIncremental initial
42− buildDynamic getInitial = liftPlan . buildDynamic getInitial
43− headE = liftPlan . headE
44−
45−instance MonadSample (Pure Int) PurePlan where
46− sample = liftPlan . sample
47−
48−
49−instance TestPlan (Pure Int) PurePlan where
50− plan occs = do
51− PurePlan . modify $ IntSet.union (IntMap.keysSet m)
52− return $ mapToPureEvent m
53− where m = IntMap.fromList (first fromIntegral <$> occs)
54−
55−runPure :: PurePlan a -> (a, IntSet)
56−runPure (PurePlan p) = runStateT p mempty $ 0
57−
58−relevantTimes :: IntSet -> IntSet
59−relevantTimes occs = IntSet.fromList [0..l + 1]
60− where l = fromMaybe 0 (fst <$> IntSet.maxView occs)
61−
62−testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a
63−testBehavior (b, occs) = IntMap.fromSet (sample b) (relevantTimes occs)
64−
65−testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a)
66−testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relevantTimes occs)
67−
68−
69−
70−
71−
72−
test/Reflex/Plan/Reflex.hsdeleted−135
@@ -1,135 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE StandaloneDeriving #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−module Reflex.Plan.Reflex
12− ( TestPlan(..)
13− , runPlan
14− , Plan (..)
15− , Schedule
16− , Firing (..)
17− , MonadIORef
18−
19−
20− , readSchedule
21− , readSchedule_
22− , testSchedule
23− , readEvent'
24− , makeDense
25−
26− , runTestE
27− , runTestB
28−
29− ) where
30−
31−import Reflex.Class
32−import Reflex.Host.Class
33−import Reflex.TestPlan
34−
35−import Control.Applicative
36−import Control.Monad
37−import Control.Monad.Identity
38−import Control.Monad.State.Strict
39−
40−import Control.Monad.Ref
41−import Data.Dependent.Sum (DSum (..))
42−import qualified Data.IntMap.Strict as IntMap
43−import Data.Maybe
44−import Data.Monoid
45−import Data.Traversable (sequenceA, traverse)
46−
47−import Control.DeepSeq
48−import Control.Exception
49−import Data.IntMap.Strict (IntMap)
50−import Data.IORef
51−import System.Mem
52−
53−-- Note: this import must come last to silence warnings from AMP
54−import Prelude
55−
56−type MonadIORef m = (MonadIO m, MonadRef m, Ref m ~ Ref IO)
57−
58−data Firing t where
59− Firing :: IORef (Maybe (EventTrigger t a)) -> a -> Firing t
60−
61−
62−type Schedule t = IntMap [Firing t]
63−
64−-- Implementation of a TestPlan in terms of ReflexHost
65−newtype Plan t a = Plan (StateT (Schedule t) (HostFrame t) a)
66−
67−deriving instance ReflexHost t => Functor (Plan t)
68−deriving instance ReflexHost t => Applicative (Plan t)
69−deriving instance ReflexHost t => Monad (Plan t)
70−
71−deriving instance ReflexHost t => MonadSample t (Plan t)
72−deriving instance ReflexHost t => MonadHold t (Plan t)
73−deriving instance ReflexHost t => MonadFix (Plan t)
74−
75−
76−instance (ReflexHost t, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => TestPlan t (Plan t) where
77− plan occurrences = Plan $ do
78− (e, ref) <- newEventWithTriggerRef
79− modify (IntMap.unionWith mappend (firings ref))
80− return e
81−
82− where
83− firings ref = IntMap.fromList (makeFiring ref <$> occurrences)
84− makeFiring ref (t, a) = (fromIntegral t, [Firing ref a])
85−
86−
87−firingTrigger :: (MonadReflexHost t m, MonadIORef m) => Firing t -> m (Maybe (DSum (EventTrigger t) Identity))
88−firingTrigger (Firing ref a) = fmap (:=> Identity a) <$> readRef ref
89−
90−runPlan :: (MonadReflexHost t m) => Plan t a -> m (a, Schedule t)
91−runPlan (Plan p) = runHostFrame $ runStateT p mempty
92−
93−
94−makeDense :: Schedule t -> Schedule t
95−makeDense s = fromMaybe (emptyRange 0) $ do
96− (end, _) <- fst <$> IntMap.maxViewWithKey s
97− return $ IntMap.union s (emptyRange end)
98− where
99− emptyRange end = IntMap.fromList (zip [0..end + 1] (repeat []))
100−
101−
102−-- For the purposes of testing, we add in a zero frame and extend one frame (to observe changes to behaviors
103−-- after the last event)
104−-- performGC is called at each frame to test for GC issues
105−testSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
106−testSchedule schedule readResult = IntMap.traverseWithKey (\t occs -> liftIO performGC *> triggerFrame readResult t occs) (makeDense schedule)
107−
108−readSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
109−readSchedule schedule readResult = IntMap.traverseWithKey (triggerFrame readResult) schedule
110−
111−readSchedule_ :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m ()
112−readSchedule_ schedule readResult = mapM_ (uncurry $ triggerFrame readResult) $ IntMap.toList schedule
113−
114−triggerFrame :: (MonadReflexHost t m, MonadIORef m, NFData a) => ReadPhase m a -> Int -> [Firing t] -> m a
115−triggerFrame readResult _ occs = do
116− triggers <- catMaybes <$> traverse firingTrigger occs
117− liftIO . evaluate . force =<< fireEventsAndRead triggers readResult
118−
119−readEvent' :: MonadReadEvent t m => EventHandle t a -> m (Maybe a)
120−readEvent' = readEvent >=> sequenceA
121−
122−
123−-- Convenience functions for running tests producing Events/Behaviors
124−runTestB :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Behavior t a) -> m (IntMap a)
125−runTestB p = do
126− (b, s) <- runPlan p
127− testSchedule s $ sample b
128−
129−runTestE :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Event t a) -> m (IntMap (Maybe a))
130−runTestE p = do
131− (e, s) <- runPlan p
132− h <- subscribeEvent e
133− testSchedule s (readEvent' h)
134−
135−
test/Reflex/Test.hsdeleted−66
@@ -1,66 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−
8−module Reflex.Test
9− ( testAgreement
10− , compareResult
11− , runTests
12−
13− , module Reflex.TestPlan
14−
15− ) where
16−
17−import Reflex.Spider
18−
19−import Reflex.TestPlan
20−
21−import Reflex.Plan.Pure
22−import Reflex.Plan.Reflex
23−
24−import Control.Monad
25−import Data.Monoid
26−
27−import Data.IntMap (IntMap)
28−
29−--import Data.Foldable
30−import System.Exit
31−
32−import Prelude
33−
34−
35−testAgreement :: TestCase -> IO Bool
36−testAgreement (TestE p) = do
37− spider <- runSpiderHost $ runTestE p
38− let results = [("spider", spider)]
39−
40− compareResult results (testEvent $ runPure p)
41−
42−testAgreement (TestB p) = do
43− spider <- runSpiderHost $ runTestB p
44− let results = [("spider", spider)]
45−
46− compareResult results (testBehavior $ runPure p)
47−
48−
49−compareResult :: (Show a, Eq a) => [(String, IntMap a)] -> IntMap a -> IO Bool
50−compareResult results expected = fmap and $ forM results $ \(name, r) -> do
51−
52− when (r /= expected) $ do
53− putStrLn ("Got: " ++ show (name, r))
54− putStrLn ("Expected: " ++ show expected)
55− return (r == expected)
56−
57−
58−runTests :: [(String, TestCase)] -> IO ()
59−runTests testCases = do
60− results <- forM testCases $ \(name, test) -> do
61− putStrLn $ "Test: " <> name
62− testAgreement test
63− exitWith $ if and results
64− then ExitSuccess
65− else ExitFailure 1
66−
test/Reflex/Test/CrossImpl.hsdeleted−262
@@ -1,262 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoMonomorphismRestriction #-}
9−{-# LANGUAGE RankNTypes #-}
10−{-# LANGUAGE RecursiveDo #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−
16−import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_)
17−
18−import Control.Monad.Ref
19−import Reflex.Class
20−import Reflex.Dynamic
21−import Reflex.Host.Class
22−import qualified Reflex.Pure as P
23−import qualified Reflex.Spider.Internal as S
24−
25−import Control.Arrow (second, (&&&))
26−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
27−import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
28−import Data.Dependent.Map (DSum (..))
29−import Data.Foldable
30−import Data.Map.Strict (Map)
31−import qualified Data.Map.Strict as Map
32−import qualified Data.Set as Set
33−import Data.Monoid
34−import Data.Traversable
35−import System.Exit
36−import System.Mem
37−
38−import System.IO.Unsafe
39−
40−mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a
41−mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of
42− Nothing -> error $ "mapToPureBehavior: no value for time " <> show t
43− Just (_, v) -> v
44−
45−mapToPureEvent :: Map Int a -> Event PureReflexDomain a
46−mapToPureEvent m = P.Event $ flip Map.lookup m
47−
48−relevantTestingTimes :: (Map Int a, Map Int b) -> [Int]
49−relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of
50− (Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event
51− _ -> [] -- Doesn't actually make much sense
52−
53−type PureReflexDomain = P.Pure Int
54−type TimeM = (->) Int
55−
56−testPure :: (t ~ PureReflexDomain, m ~ TimeM) => ((Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
57−testPure builder (b, e) =
58− let (P.Behavior b', P.Event e') = ($ 0) $ builder (mapToPureBehavior b, mapToPureEvent e)
59− relevantTimes = relevantTestingTimes (b, e)
60− e'' = Map.mapMaybe id $ Map.fromList $ map (id &&& e') relevantTimes
61− b'' = Map.fromList $ map (id &&& b') relevantTimes
62− in (b'', e'')
63−
64−class MapMSignals a a' t t' | a -> t, a' -> t', a t' -> a', a' t -> a where
65− mapMSignals :: Monad m => (forall b. Behavior t b -> m (Behavior t' b)) -> (forall b. Event t b -> m (Event t' b)) -> a -> m a'
66−
67−instance MapMSignals (Behavior t a) (Behavior t' a) t t' where
68− mapMSignals fb _ = fb
69−
70−instance MapMSignals (Event t a) (Event t' a) t t' where
71− mapMSignals _ fe = fe
72−
73−instance (MapMSignals a a' t t', MapMSignals b b' t t') => MapMSignals (a, b) (a', b') t t' where
74− mapMSignals fb fe (a, b) = liftM2 (,) (mapMSignals fb fe a) (mapMSignals fb fe b)
75−
76−testSpider :: (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
77−testSpider builder (bMap, eMap) = unsafePerformIO $ S.runSpiderHost $ do
78− (re, reTrigger) <- newEventWithTriggerRef
79− (rb, rbTrigger) <- newEventWithTriggerRef
80− b <- runHostFrame $ hold (error "testSpider: No value for input behavior yet") rb
81− (b', e') <- runHostFrame $ builder (b, re)
82− e'Handle <- subscribeEvent e' --TODO: This should be unnecessary
83− let times = relevantTestingTimes (bMap, eMap)
84− liftIO performGC
85− outputs <- forM times $ \t -> do
86− forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger
87− bOutput <- sample b'
88− eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do
89− mret <- readRef reTrigger
90− let firing = case mret of
91− Just ret -> [ret :=> Identity val]
92− Nothing -> []
93− fireEventsAndRead firing $ sequence =<< readEvent e'Handle
94− liftIO performGC
95− return (t, (bOutput, eOutput))
96− return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)
97−
98−tracePerf :: Show a => a -> b -> b
99−tracePerf = flip const
100−
101−testAgreement :: (Eq c, Eq d, Show c, Show d) => (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> IO Bool
102−testAgreement builder inputs = do
103− let identityResult = testPure builder inputs
104− tracePerf "---------" $ return ()
105− let spiderResult = testSpider builder inputs
106− tracePerf "---------" $ return ()
107− let resultsAgree = identityResult == spiderResult
108− if resultsAgree
109− then do --putStrLn "Success:"
110− --print identityResult
111− return ()
112− else do putStrLn "Failure:"
113− putStrLn $ "Pure result: " <> show identityResult
114− putStrLn $ "Spider result: " <> show spiderResult
115− return resultsAgree
116−
117−type TestCaseConstraint t m = (Reflex t, MonadSample t m, MonadHold t m, MonadFix m, MonadFix (PushM t))
118−
119−data TestCase = forall a b c d. (Eq c, Eq d, Show c, Show d) => TestCase (Map Int a, Map Int b) (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d))
120−
121−testCases :: [(String, TestCase)]
122−testCases =
123− [ (,) "hold" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
124− b' <- hold "123" e
125− return (b', e)
126− , (,) "count" $ TestCase (Map.singleton 0 (), Map.fromList [(1, ()), (2, ()), (3, ())]) $ \(_, e) -> do
127− e' <- updated <$> count e
128− b' <- hold (0 :: Int) e'
129− return (b', e')
130− , (,) "headE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
131− e' <- headE $ leftmost [e, e]
132− return (b, e')
133− , (,) "switch-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
134− let e' = fmap (const e) e
135− b' <- hold never e'
136− let e'' = switch b'
137− return (b, e'')
138− , (,) "switch-2" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
139− let e' = flip pushAlways e $ const $ do
140− let eab = splitRecombineEvent e
141− switch <$> hold eab never
142− e'' = coincidence e'
143− return (b, e'')
144− , (,) "switch-3" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
145− let e' = flip pushAlways e $ const $ do
146− let eab = splitRecombineEvent e
147− switch <$> hold eab (fmap (const e) e)
148− e'' = coincidence e'
149− return (b, e'')
150− , (,) "switch-4" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
151− let e' = leftmost [e, e]
152− e'' <- switch <$> hold e' (fmap (const e) e)
153− return (b, e'')
154− , (,) "switchHoldPromptly-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
155− let e' = fmap (const e) e
156− e'' <- switchHoldPromptly never e'
157− return (b, e'')
158− , (,) "switchHoldPromptly-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
159− let e' = fmap (const e) e
160− e'' <- switchHoldPromptly never $ leftmost [e', e']
161− return (b, e'')
162− , (,) "switchHoldPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
163− let e' = leftmost [e, e]
164− e'' <- switchHoldPromptly never (fmap (const e) e')
165− return (b, e'')
166− , (,) "switchHoldPromptly-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
167− let e' = leftmost [e, e]
168− e'' <- switchHoldPromptly never (fmap (const e') e)
169− return (b, e'')
170− , (,) "switch-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
171− let e' = leftmost [e, e]
172− e'' <- switch <$> hold never (fmap (const e') e)
173− return (b, e'')
174− , (,) "switchHoldPromptly-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
175− let e' = flip push e $ \_ -> do
176− Just <$> headE e
177− e'' <- switchHoldPromptly never e'
178− return (b, e'')
179− , (,) "switchHoldPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
180− let e' = flip pushAlways e $ \_ -> do
181− switchHoldPromptly e never
182− e'' <- switchHoldPromptly never e'
183− return (b, e'')
184− , (,) "coincidence-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
185− let e' = flip pushAlways e $ \_ -> return e
186− e'' = coincidence e'
187− return (b, e'')
188− , (,) "coincidence-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
189− let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]
190− e'' = coincidence e'
191− return (b, e'')
192− , (,) "coincidence-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
193− let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e
194− e'' = coincidence e'
195− return (b, e'')
196− , (,) "coincidence-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
197− let e' = flip pushAlways e $ \_ -> headE e
198− e'' = coincidence e'
199− return (b, e'')
200− , (,) "coincidence-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
201− let eChild = flip pushAlways e $ const $ do
202− let eNewValues = leftmost [e, e]
203− return $ coincidence $ fmap (const eNewValues) eNewValues
204− e' = coincidence eChild
205− return (b, e')
206− , (,) "coincidence-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
207− let eChild = flip pushAlways e $ const $ do
208− let e' = coincidence $ fmap (const e) e
209− return $ leftmost [e', e']
210− e'' = coincidence eChild
211− return (b, e'')
212− , (,) "coincidence-7" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
213− let e' = leftmost [e, e]
214− eCoincidences = coincidence $ fmap (const e') e
215− return (b, eCoincidences)
216− , (,) "holdWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
217− eo <- headE e
218− bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo
219− let b' = pull $ sample =<< sample bb
220− return (b', e)
221− , (,) "foldDynWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
222− d <- foldDyn (:) [] $
223− pushAlways (\a -> foldDyn (:) [a] e) e
224− let b = current (join (fmap distributeListOverDynPure d))
225− return (b, e)
226− , (,) "joinDyn" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
227− bb <- hold "b" e
228− bd <- hold never . fmap (const e) =<< headE e
229− eOuter <- pushAlways sample . fmap (const bb) <$> headE e
230− let eInner = switch bd
231− e' = leftmost [eOuter, eInner]
232− return (b, e')
233− , (,) "holdUniqDyn-laziness" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList (zip [1 :: Int ..] [1 :: Int, 2, 2, 3, 3, 3, 4, 4, 4, 4])) $ \(_, e :: Event t Int) -> do
234− rec result <- holdUniqDyn d
235− d <- holdDyn (0 :: Int) e
236− return (current result, updated result)
237−
238−
239−
240− {-
241− , (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do
242− x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e
243− let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)
244− return (b, e')
245− -}
246− ]
247−
248−splitRecombineEvent :: Reflex t => Event t a -> Event t String
249−splitRecombineEvent e =
250− let ea = "a" <$ e
251− eb = "b" <$ e
252− in leftmost [ea, eb]
253−
254−
255−main :: IO ()
256−main = do
257− results <- forM testCases $ \(name, TestCase inputs builder) -> do
258− putStrLn $ "Test: " <> name
259− testAgreement builder inputs
260− exitWith $ if and results
261− then ExitSuccess
262− else ExitFailure 1
test/Reflex/Test/Micro.hsdeleted−346
@@ -1,346 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RecursiveDo #-}
10−
11−module Reflex.Test.Micro (testCases) where
12−
13−import Reflex
14−import Reflex.TestPlan
15−
16−import Control.Applicative
17−import Control.Monad
18−import Control.Monad.Fix
19−import Data.Char
20−import Data.Foldable
21−import Data.Functor.Misc
22−import qualified Data.Map as Map
23−import Data.Monoid
24−
25−import Prelude
26−
27−pushDyn :: (Reflex t, MonadHold t m) => (a -> PushM t b) -> Dynamic t a -> m (Dynamic t b)
28−pushDyn f d = buildDynamic (sample (current d) >>= f) (pushAlways f (updated d))
29−
30−foldedDyn :: (Reflex t, MonadHold t m) => (a -> a -> a) -> Dynamic t a -> m (Dynamic t a)
31−foldedDyn f d = fmap join $ flip buildDynamic never $ do
32− a <- sample (current d)
33− foldDyn f a (updated d)
34−
35−scannedDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> m (Dynamic t [a])
36−scannedDyn = fmap (fmap reverse) . foldedDyn (<>) . fmap pure
37−
38−scanInnerDyns :: (Reflex t, MonadHold t m) => Dynamic t (Dynamic t a) -> m (Dynamic t [a])
39−scanInnerDyns d = do
40− scans <- scannedDyn d
41− return (join (fmap distributeListOverDynPure scans))
42−
43−
44−
45−{-# ANN testCases "HLint: ignore Functor law" #-}
46−testCases :: [(String, TestCase)]
47−testCases =
48− [ testB "hold" $ hold "0" =<< events1
49−
50− , testB "count" $ do
51− b <- current <$> (count =<< events2)
52− return $ (+ (0::Int)) <$> b
53−
54− , testB "pull-1" $ do
55− b <- hold "0" =<< events1
56− return (pull $ sample $ pull $ sample b)
57−
58− , testB "pull-2" $ do
59− b1 <- behavior1
60− return (pull $ liftA2 (<>) (sample b1) (sample b1))
61−
62− , testB "pull-3" $ do
63− b1 <- behavior1
64− b2 <- behavior2
65− return (pull $ liftA2 (<>) (sample b1) (sample b2))
66−
67− , testB "pull-4" $ do
68− es <- planList ["a", "b", "c"]
69− e <- plan [(0, ())]
70− b <- hold (constant "") $
71− pushAlways (const $ hold "z" es) e
72− return (join b)
73−
74− , testE "id" $ do
75− events2
76−
77− , testE "fmap-id" $ do
78− e <- events2
79− return $ fmap id e
80−
81− , testE "tag-1" $ do
82− b1 <- behavior1
83− e <- events2
84− return (tag b1 e)
85−
86− , testE "tag-2" $ do
87− b1 <- behavior1
88− e <- events2
89− return (tag (map toUpper <$> b1) e)
90−
91− , testE "attach-1" $ do
92− b1 <- behavior1
93− e <- events2
94− return (attachWith (++) (map toUpper <$> b1) e)
95−
96− , testE "leftmost" $ liftA2 leftmost2 events1 events2
97−
98− , testE "appendEvents-1" $ liftA2 mappend events1 events2
99−
100− , testE "appendEvents-2" $ liftA2 mappend events3 events2
101−
102− , testE "merge-1" $ do
103− e <- events1
104− return $ leftmost ["x" <$ e, "y" <$ e]
105−
106− , testE "merge-2" $ do
107− e <- events1
108− let m = mergeMap $ Map.fromList [(1::Int, "y" <$ e), (2, "z" <$ e)]
109− let ee = flip pushAlways e $ const $ return m
110− return $ coincidence ee
111−
112− , testE "headE-1" $ do
113− e <- events1
114− headE $ leftmost [e, e]
115−
116− , testE "headE-2" $ do
117− e <- events1
118− b <- hold never (e <$ e)
119− headE $ switch b
120−
121− , testE "switch-1" $ do
122− e <- events1
123− b <- hold never (e <$ e)
124− return $ switch b
125−
126− , testE "switch-2" $ do
127− e <- events1
128− return $ coincidence $ flip pushAlways e $ const $ do
129− switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) (e <$ e)
130−
131− , testE "switch-3" $ do
132− e <- events1
133− return $ coincidence $ flip pushAlways e $ const $ do
134− switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) never
135−
136− , testE "switch-4" $ do
137− e <- events1
138− switch <$> hold (deep e) (e <$ e)
139−
140− , testE "switch-5" $ do
141− e <- events1
142− return $ coincidence $ flip pushAlways e $ const $
143− return $ leftmost ["x" <$ e, "y" <$ e, "z" <$ e]
144−
145− , testE "switch-6" $ do
146− e <- events1
147− return $ coincidence $ flip pushAlways e $ const $ do
148− switch <$> hold ("x" <$ e) (e <$ e)
149−
150− , testE "switchHoldPromptly-1" $ do
151− e <- events1
152− let e' = e <$ e
153− switchHoldPromptly never $ e <$ e'
154−
155− , testE "switchHoldPromptly-2" $ do
156− e <- events1
157− switchHoldPromptly never $ deep (e <$ e)
158−
159− , testE "switchHoldPromptly-3" $ do
160− e <- events1
161− switchHoldPromptly never $ (e <$ deep e)
162−
163− , testE "switchHoldPromptly-4" $ do
164− e <- events1
165− switchHoldPromptly never $ (deep e <$ e)
166−
167− , testE "switch-5" $ do
168− e <- events1
169− switch <$> hold never (deep e <$ e)
170−
171− , testE "switchHoldPromptly-5" $ do
172− e <- events1
173− switchHoldPromptly never $ flip push e $
174− const (Just <$> headE e)
175−
176− , testE "switchHoldPromptly-6" $ do
177− e <- events1
178− switchHoldPromptly never $ flip pushAlways e $
179− const (switchHoldPromptly e never)
180−
181− , testE "coincidence-1" $ do
182− e <- events1
183− return $ coincidence $ flip pushAlways e $
184− const $ return e
185−
186− , testE "coincidence-2" $ do
187− e <- events1
188− return $ coincidence $ flip pushAlways e $
189− const $ return (deep e)
190−
191− , testE "coincidence-3" $ do
192− e <- events1
193− return $ coincidence $ flip pushAlways e $
194− const $ return (coincidence (e <$ e))
195−
196− , testE "coincidence-4" $ do
197− e <- events1
198− return $ coincidence $ flip pushAlways e $
199− const (headE e)
200−
201− , testE "coincidence-5" $ do
202− e <- events1
203− return $ coincidence $ flip pushAlways e $ const $ do
204− let e' = deep e
205− return (coincidence (e' <$ e'))
206−
207− , testE "coincidence-6" $ do
208− e <- events1
209− return $ coincidence $ flip pushAlways e $ const $ do
210− let e' = coincidence (e <$ e)
211− return $ deep e'
212−
213− , testE "coincidence-7" $ do
214− e <- events1
215− return $ coincidence (deep e <$ e)
216−
217− , testB "holdWhileFiring" $ do
218− e <- events1
219− eo <- headE e
220− bb <- hold (constant "x") $ pushAlways (const $ hold "a" eo) eo
221− return $ pull $ sample =<< sample bb
222−
223−
224− , testB "foldDynWhileFiring" $ do
225− e <- events1
226− d <- foldDyn (:) [] $
227− pushAlways (\a -> foldDyn (:) [a] e) e
228−
229− return $ current (join (fmap distributeListOverDynPure d))
230−
231− , testE "joinDyn" $ do
232− e <- events1
233− bb <- hold "b" e
234− bd <- hold never . fmap (const e) =<< headE e
235−
236− eOuter <- pushAlways sample . fmap (const bb) <$> headE e
237− let eInner = switch bd
238− return $ leftmost [eOuter, eInner]
239−
240− , testB "foldDyn" $ do
241− d <- foldDyn (++) "0" =<< events1
242− return (current d)
243−
244− , testB "mapDyn" $ do
245− d <- foldDyn (++) "0" =<< events1
246− return $ current $ fmap (map toUpper) d
247−
248− , testB "combineDyn" $ do
249− d1 <- foldDyn (++) "0" =<< events1
250− d2 <- fmap (fmap (map toUpper)) $ foldDyn (++) "0" =<< events2
251−
252− return $ current $ zipDynWith (<>) d1 d2
253−
254− , testB "buildDynamicStrictness" $ do
255− rec
256− d'' <- pushDyn return d'
257− d' <- pushDyn return d
258− d <- holdDyn "0" =<< events1
259−
260− _ <- sample (current d'')
261− return (current d'')
262−
263− , testB "factorDyn" $ do
264− d <- holdDyn (Left "a") =<< eithers
265−
266− eithers' <- eitherDyn d
267− let unFactor = either id id
268− return $ current (join (fmap unFactor eithers'))
269−
270− , testB "pushDynDeep" $ do
271− _ <- events1
272− _ <- events2
273−
274− d1 <- holdDyn "d1" =<< events1
275− d2 <- holdDyn "d2" =<< events2
276−
277− d <- flip pushDyn d1 $ \a ->
278− flip pushDyn d2 $ \b ->
279− flip pushDyn d1 $ \c ->
280− return (a <> b <> c)
281−
282− d' <- pushDyn scanInnerDyns d >>= scanInnerDyns
283− return $ current d'
284−
285− , testE "fan-1" $ do
286− e <- fmap toMap <$> events1
287− let es = select (fanMap e) . Const2 <$> values
288−
289− return (mergeList es)
290−
291− , testE "fan-2" $ do
292− e <- fmap toMap <$> events3
293− let es = select (fanMap e) . Const2 <$> values
294−
295− return (mergeList es)
296−
297− , testE "fan-3" $ do
298− f <- fanMap . fmap toMap <$> events3
299− return $ select f (Const2 'c')
300−
301− , testE "fan-4" $ do
302− e <- fmap toMap <$> events1
303− return $ toUpper <$> select (fanMap e) (Const2 'a')
304−
305− , testE "fan-5" $ do
306− e <- fmap toMap <$> events2
307− return $ toUpper <$> select (fanMap e) (Const2 'c')
308−
309− , testE "fan-6" $ do
310− f <- fanMap . fmap toMap <$> events1
311− return $ toList <$> mergeList [ select f (Const2 'b'), select f (Const2 'b'), select f (Const2 'e'), select f (Const2 'e') ]
312−
313− , testE "difference" $ do
314− e1 <- events1
315− e2 <- events2
316− return $ e1 `difference ` e2
317−
318− , testE "lazy-hold" $ do
319− let lazyHold :: forall t m. (Reflex t, MonadHold t m, MonadFix m) => m (Event t ())
320− lazyHold = do
321− rec !b <- hold never e
322− let e = never <$ switch b
323− return $ void e
324− lazyHold
325−
326−
327− ] where
328−
329− events1, events2, events3 :: TestPlan t m => m (Event t String)
330− events1 = plan [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")]
331− events2 = plan [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")]
332− events3 = liftA2 mappend events1 events2
333−
334− eithers :: TestPlan t m => m (Event t (Either String String))
335− eithers = plan [(1, Left "e"), (3, Left "d"), (4, Right "c"), (6, Right "b"), (7, Left "a")]
336−
337−
338− values = "abcde"
339− toMap str = Map.fromList $ map (\c -> (c, c)) str
340−
341− behavior1, behavior2 :: forall t m. TestPlan t m => m (Behavior t String)
342− behavior1 = hold "1" =<< events1
343− behavior2 = hold "2" =<< events2
344−
345− deep e = leftmost [e, e]
346− leftmost2 e1 e2 = leftmost [e1, e2]
test/Reflex/TestPlan.hsdeleted−52
@@ -1,52 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE UndecidableInstances #-}
9−module Reflex.TestPlan
10− ( TestPlan(..)
11−
12− , TestCase (..)
13− , testE, testB
14− , TestE, TestB
15−
16− , planList
17−
18− ) where
19−
20−import Control.DeepSeq
21−import Control.Monad.Fix
22−import Data.Word
23−import Reflex.Class
24−
25−
26−import Prelude
27−
28−class (Reflex t, MonadHold t m, MonadFix m) => TestPlan t m where
29− -- | Specify a plan of an input Event firing
30− -- Occurrences must be in the future (i.e. Time > 0)
31− -- Initial specification is
32−
33− plan :: [(Word, a)] -> m (Event t a)
34−
35−
36−planList :: TestPlan t m => [a] -> m (Event t a)
37−planList xs = plan $ zip [1..] xs
38−
39−type TestE a = forall t m. TestPlan t m => m (Event t a)
40−type TestB a = forall t m. TestPlan t m => m (Behavior t a)
41−
42−data TestCase where
43− TestE :: (Show a, Eq a, NFData a) => TestE a -> TestCase
44− TestB :: (Show a, Eq a, NFData a) => TestB a -> TestCase
45−
46−-- Helpers to declare test cases
47−testE :: (Eq a, Show a, NFData a) => String -> TestE a -> (String, TestCase)
48−testE name test = (name, TestE test)
49−
50−testB :: (Eq a, Show a, NFData a) => String -> TestB a -> (String, TestCase)
51−testB name test = (name, TestB test)
52−
test/RequesterT.hsdeleted−174
@@ -1,174 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE BangPatterns #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE RankNTypes #-}
6−{-# LANGUAGE RecursiveDo #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−module Main where
9−
10−import Control.Lens
11−import Control.Monad
12−import Control.Monad.Fix
13−import qualified Data.Dependent.Map as DMap
14−import Data.Dependent.Sum
15−import Data.Functor.Misc
16−import qualified Data.Map as M
17−import Data.These
18−
19−#if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))
20−import Data.These.Lens
21−#endif
22−
23−import Reflex
24−import Reflex.Requester.Base
25−import Reflex.Requester.Class
26−import Test.Run
27−
28−data RequestInt a where
29− RequestInt :: Int -> RequestInt Int
30−
31−main :: IO ()
32−main = do
33− os1 <- runApp' (unwrapApp testOrdering) $
34− [ Just ()
35− ]
36− print os1
37− os2 <- runApp' (unwrapApp testSimultaneous) $ map Just $
38− [ This ()
39− , That ()
40− , This ()
41− , These () ()
42− ]
43− print os2
44− os3 <- runApp' (unwrapApp testMoribundRequest) [Just ()]
45− print os3
46− os4 <- runApp' (unwrapApp testMoribundRequestDMap) [Just ()]
47− print os4
48− os5 <- runApp' (unwrapApp testLiveRequestDMap) [Just ()]
49− print os5
50− os6 <- runApp' (unwrapApp delayedPulse) [Just ()]
51− print os6
52− let ![[Just [1,2,3,4,5,6,7,8,9,10]]] = os1 -- The order is reversed here: see the documentation for 'runRequesterT'
53− let ![[Just [9,7,5,3,1]],[Nothing,Nothing],[Just [10,8,6,4,2]],[Just [10,8,6,4,2],Nothing]] = os2
54− let ![[Nothing, Just [2]]] = os3
55− let ![[Nothing, Just [2]]] = os4
56− let ![[Nothing, Just [1, 2]]] = os5
57− -- let ![[Nothing, Nothing]] = os6 -- TODO re-enable this test after issue #233 has been resolved
58− return ()
59−
60−unwrapRequest :: DSum tag RequestInt -> Int
61−unwrapRequest (_ :=> RequestInt i) = i
62−
63−unwrapApp :: ( Reflex t, Monad m )
64− => (a -> RequesterT t RequestInt Identity m ())
65− -> a
66− -> m (Event t [Int])
67−unwrapApp x appIn = do
68− ((), e) <- runRequesterT (x appIn) never
69− return $ fmap (map unwrapRequest . requesterDataToList) e
70−
71−testOrdering :: ( Response m ~ Identity
72− , Request m ~ RequestInt
73− , Requester t m
74− , Adjustable t m)
75− => Event t ()
76− -> m ()
77−testOrdering pulse = forM_ [10,9..1] $ \i ->
78− requestingIdentity (RequestInt i <$ pulse)
79−
80−testSimultaneous :: ( Response m ~ Identity
81− , Request m ~ RequestInt
82− , Requester t m
83− , Adjustable t m)
84− => Event t (These () ())
85− -> m ()
86−testSimultaneous pulse = do
87− let tellE = fmapMaybe (^? here) pulse
88− switchE = fmapMaybe (^? there) pulse
89− forM_ [1,3..9] $ \i -> runWithReplace (requestingIdentity (RequestInt i <$ tellE)) $ ffor switchE $ \_ ->
90− requestingIdentity (RequestInt (i+1) <$ tellE)
91−
92−-- | Test that a widget requesting and event which fires at the same time it has been replaced
93−-- doesn't count along with the new widget.
94−testMoribundRequest
95− :: forall t m
96− . ( Reflex t
97− , Adjustable t m
98− , MonadHold t m
99− , MonadFix m
100− , Response m ~ Identity
101− , Request m ~ RequestInt
102− , Requester t m
103− )
104− => Event t ()
105− -> m ()
106−testMoribundRequest pulse = do
107− rec let requestIntOnReplace x = requestingIdentity $ RequestInt x <$ rwrFinished
108− (_, rwrFinished) <- runWithReplace (requestIntOnReplace 1) $ requestIntOnReplace 2 <$ pulse
109− return ()
110−
111−-- | The equivalent of 'testMoribundRequest' for 'traverseDMapWithKeyWithAdjust'.
112−testMoribundRequestDMap
113− :: forall t m
114− . ( Reflex t
115− , Adjustable t m
116− , MonadHold t m
117− , MonadFix m
118− , Response m ~ Identity
119− , Request m ~ RequestInt
120− , Requester t m
121− )
122− => Event t ()
123− -> m ()
124−testMoribundRequestDMap pulse = do
125− rec let requestIntOnReplace :: Int -> m ()
126− requestIntOnReplace x = void $ requestingIdentity $ RequestInt x <$ rwrFinished
127− (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-
128− traverseDMapWithKeyWithAdjust
129− (\(Const2 ()) (Identity v) -> Identity . const v <$> requestIntOnReplace v)
130− (mapToDMap $ M.singleton () 1)
131− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)
132− return ()
133−
134−-- | Ensures that elements which are _not_ removed can still fire requests
135−-- during the same frame as other elements are updated.
136−testLiveRequestDMap
137− :: forall t m
138− . ( Reflex t
139− , Adjustable t m
140− , MonadHold t m
141− , MonadFix m
142− , Response m ~ Identity
143− , Request m ~ RequestInt
144− , Requester t m
145− )
146− => Event t ()
147− -> m ()
148−testLiveRequestDMap pulse = do
149− rec let requestIntOnReplace :: Int -> m ()
150− requestIntOnReplace x = void $ requestingIdentity $ RequestInt x <$ rwrFinished
151− (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-
152− traverseDMapWithKeyWithAdjust
153− (\(Const2 k) (Identity ()) -> Identity <$> requestIntOnReplace k)
154− (mapToDMap $ M.singleton 1 ())
155− ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)
156− return ()
157−
158−delayedPulse
159− :: forall t m
160− . ( Reflex t
161− , Adjustable t m
162− , MonadHold t m
163− , MonadFix m
164− , Response m ~ Identity
165− , Request m ~ RequestInt
166− , PerformEvent t m
167− , Requester t m
168− )
169− => Event t ()
170− -> m ()
171−delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do
172− -- This has the effect of delaying pulse' from pulse
173− (_, pulse') <- runWithReplace (pure ()) $ pure (RequestInt 1) <$ pulse
174− requestingIdentity pulse'
test/Test/Run.hsdeleted−74
@@ -1,74 +0,0 @@
1−{-# LANGUAGE GADTs #-}
2−{-# LANGUAGE LambdaCase #-}
3−module Test.Run where
4−
5−import Control.Monad
6−import Control.Monad.Ref
7−import Data.Dependent.Sum
8−import Data.Functor.Identity
9−import Data.These
10−
11−import Reflex
12−import Reflex.Host.Class
13−
14−data AppIn t b e = AppIn
15− { _appIn_behavior :: Behavior t b
16− , _appIn_event :: Event t e
17− }
18−
19−data AppOut t b e = AppOut
20− { _appOut_behavior :: Behavior t b
21− , _appOut_event :: Event t e
22− }
23−
24−runApp :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
25− => (AppIn t bIn eIn -> PerformEventT t m (AppOut t bOut eOut))
26− -> bIn
27− -> [Maybe (These bIn eIn)]
28− -> IO [[(bOut, Maybe eOut)]]
29−runApp app b0 input = runSpiderHost $ do
30− (appInHoldE, pulseHoldTriggerRef) <- newEventWithTriggerRef
31− (appInE, pulseEventTriggerRef) <- newEventWithTriggerRef
32− appInB <- hold b0 appInHoldE
33− (out, FireCommand fire) <- hostPerformEventT $ app $ AppIn
34− { _appIn_event = appInE
35− , _appIn_behavior = appInB
36− }
37− hnd <- subscribeEvent (_appOut_event out)
38− mpulseB <- readRef pulseHoldTriggerRef
39− mpulseE <- readRef pulseEventTriggerRef
40− let readPhase = do
41− b <- sample (_appOut_behavior out)
42− frames <- sequence =<< readEvent hnd
43− return (b, frames)
44− forM input $ \case
45− Nothing ->
46− fire [] $ readPhase
47− Just i -> case i of
48− This b' -> case mpulseB of
49− Nothing -> error "tried to fire in-behavior but ref was empty"
50− Just pulseB -> fire [ pulseB :=> Identity b' ] $ readPhase
51− That e' -> case mpulseE of
52− Nothing -> error "tried to fire in-event but ref was empty"
53− Just pulseE -> fire [ pulseE :=> Identity e' ] $ readPhase
54− These b' e' -> case mpulseB of
55− Nothing -> error "tried to fire in-behavior but ref was empty"
56− Just pulseB -> case mpulseE of
57− Nothing -> error "tried to fire in-event but ref was empty"
58− Just pulseE -> fire [ pulseB :=> Identity b', pulseE :=> Identity e' ] $ readPhase
59−
60−runApp' :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
61− => (Event t eIn -> PerformEventT t m (Event t eOut))
62− -> [Maybe eIn]
63− -> IO [[Maybe eOut]]
64−runApp' app input = do
65− let app' = fmap (AppOut (pure ())) . app
66− map (map snd) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
67−
68−runAppB :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
69− => (Event t eIn -> PerformEventT t m (Behavior t bOut))
70− -> [Maybe eIn]
71− -> IO [[bOut]]
72−runAppB app input = do
73− let app' = fmap (flip AppOut never) . app
74− map (map fst) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
test/hlint.hs+2−1
@@ -1,7 +1,7 @@
11module Main where
22
33import Control.Monad
4−import Language.Haskell.HLint3 (hlint)
4+import Language.Haskell.HLint (hlint)
55import System.Directory
66import System.Exit (exitFailure, exitSuccess)
77import System.FilePath
@@ -23,6 +23,7 @@ main = do
2323 , "--ignore=Reduce duplication"
2424 , "--cpp-define=USE_TEMPLATE_HASKELL"
2525 , "--ignore=Use tuple-section"
26+ , "--ignore=Unused LANGUAGE pragma" -- hlint3 falsely believes that TypeOperators is not needed
2627 ]
2728 recurseInto = and <$> sequence
2829 [ fileType ==? Directory
test/rootCleanup.hsdeleted−25
@@ -1,25 +0,0 @@
1−import Control.Concurrent
2−import Control.Monad
3−import Data.IORef
4−import Reflex
5−import Reflex.Host.Class
6−import System.Exit
7−import System.Mem
8−
9−main :: IO ()
10−main = do
11− numSubscriptions <- newIORef 0
12− replicateM_ 1000 $ do
13− runSpiderHost $ do
14− e <- newEventWithTrigger $ \_ -> do
15− modifyIORef' numSubscriptions succ
16− return $ modifyIORef' numSubscriptions pred
17− _ <- hold () e
18− return ()
19− replicateM_ 100 $ do
20− performMajorGC
21− threadDelay 1
22− n <- readIORef numSubscriptions
23− if n == 0
24− then putStrLn "Succeeded"
25− else putStrLn "Failed" >> exitFailure
test/semantics.hsdeleted−47
@@ -1,47 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RankNTypes #-}
7−
8−module Main (main) where
9−
10−import Reflex.Test
11−
12−import Data.Bifunctor
13−import Data.Functor
14−import Data.List
15−import qualified Reflex.Bench.Focused as Focused
16−import qualified Reflex.Test.Micro as Micro
17−
18−import System.Environment
19−import System.Exit
20−
21−import Prelude
22−
23−matchPrefixes :: [String] -> (String -> Bool)
24−matchPrefixes [] = const True
25−matchPrefixes args = \name -> any (`isPrefixOf` name) args
26−
27−
28−main :: IO ()
29−main = do
30− args <- getArgs
31−
32− case args of
33− ["--list"] -> mapM_ putStrLn (fst <$> allTests) >> exitWith (ExitFailure 1)
34− _ -> case filter (matchPrefixes args . fst) allTests of
35− [] -> putStrLn "filter did not match any tests" >> exitWith (ExitFailure 1)
36− tests -> runTests tests
37−
38− where
39− allTests = concat
40− [ makeGroup "micro" Micro.testCases
41− , makeGroup "subscribing (100,40)" (Focused.subscribing 100 40)
42− , makeGroup "firing 1000" (Focused.firing 1000)
43− , makeGroup "merge 100" (Focused.merging 100)
44− , makeGroup "fan 50" (Focused.fans 50)
45− ]
46−
47− makeGroup name tests = first (\test -> intercalate "/" [name, test]) <$> tests
test/tests.hsnew file+43
@@ -0,0 +1,43 @@
1+{-# LANGUAGE TemplateHaskell #-}
2+module Main where
3+
4+import Test.HUnit (runTestTT, (~:), assertEqual, errors, failures, test)
5+import Data.Patch ( Patch(apply) )
6+import Data.Patch.MapWithMove ( patchThatChangesMap )
7+import Data.Map as Map ( Map, fromList, singleton )
8+import Hedgehog (checkParallel, discover, Property, property, forAll, PropertyT, (===))
9+import Hedgehog.Gen as Gen ( int )
10+import Hedgehog.Range as Range ( linear )
11+import Control.Monad (replicateM)
12+import System.Exit (exitFailure, exitSuccess)
13+import Data.Sequence as Seq ( foldMapWithIndex, replicateM )
14+
15+main :: IO ()
16+main = do
17+ counts <- runTestTT $ test [
18+ "Simple Move" ~: (do
19+ let mapBefore = Map.fromList [(0,1)]
20+ mapAfter = Map.fromList [(0,0),(1,1)]
21+ patch = patchThatChangesMap mapBefore mapAfter
22+ afterPatch = apply patch mapBefore
23+ assertEqual "Patch creates the same Map" (Just mapAfter) afterPatch),
24+ "Property Checks" ~: propertyChecks
25+ ]
26+ if errors counts + failures counts == 0 then exitSuccess else exitFailure
27+
28+propertyChecks :: IO Bool
29+propertyChecks = checkParallel $$(discover)
30+
31+prop_patchThatChangesMap :: Property
32+prop_patchThatChangesMap = property $ do
33+ mapBefore <- makeRandomIntMap
34+ mapAfter <- makeRandomIntMap
35+ let patch = patchThatChangesMap mapBefore mapAfter
36+ Just mapAfter === apply patch mapBefore
37+
38+makeRandomIntMap :: Monad m => PropertyT m (Map Int Int)
39+makeRandomIntMap = do
40+ let genNum = Gen.int (Range.linear 0 100)
41+ length <- forAll genNum
42+ listOfNumbers <- forAll $ Seq.replicateM length genNum
43+ pure $ Seq.foldMapWithIndex Map.singleton listOfNumbers