on develop help sign in
89 files changed+1446−14021
since splitsnapshots
unifiedsplit
.github/workflows/haskell.yml+47 .travis.yml−171 CONTRIBUTING.md+3−3 ChangeLog.md+44−40 Quickref.md−311 README.md+41−14 bench/Main.hs−110 bench/RunAll.hs−157 cabal.haskell-ci−16 cabal.project.freeze−1 default.nix−44 dep/reflex-platform/default.nix+7−6 dep/reflex-platform/github.json+4−3 patch.cabal+100 reflex.cabal−400 release.nix+24−13 src/Control/Monad/ReaderIO.hs−60 src/Data/AppendMap.hs−84 src/Data/FastMutableIntMap.hs−93 src/Data/FastWeakBag.hs−156 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−121 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−1675 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−29 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−2707 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−8 test/rootCleanup.hs−25 test/semantics.hs−47 test/tests.hs+43
.github/workflows/haskell.ymlnew file+47
@@ -0,0 +1,47 @@
1+name: github-action
2+
3+on: [push, pull_request]
4+
5+jobs:
6+ build:
7+ strategy:
8+ matrix:
9+ ghc: ['8.0.2', '8.2.2', '8.4.4', '8.6.5', '8.8.4', '8.10.2']
10+ os: ['ubuntu-latest', 'macos-latest']
11+ exclude:
12+ # There are some linker warnings in 802 on darwin that
13+ # cause compilation to fail
14+ # See https://github.com/NixOS/nixpkgs/issues/25139
15+ - ghc: '8.0.2'
16+ os: 'macos-latest'
17+ runs-on: ${{ matrix.os }}
18+
19+ name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20+ steps:
21+ - uses: actions/checkout@v2
22+ - uses: actions/setup-haskell@v1
23+ with:
24+ ghc-version: ${{ matrix.ghc }}
25+ - name: Cache
26+ uses: actions/cache@v1
27+ env:
28+ cache-name: cache-cabal
29+ with:
30+ path: ~/.cabal
31+ key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32+ restore-keys: |
33+ ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34+ ${{ runner.os }}-${{ matrix.ghc }}-build-
35+ ${{ runner.os }}-${{ matrix.ghc }}-
36+ ${{ runner.os }}
37+
38+ - name: Install dependencies
39+ run: |
40+ cabal update
41+ cabal build --only-dependencies --enable-tests --enable-benchmarks
42+ - name: Build
43+ run: cabal build --enable-tests --enable-benchmarks all
44+ - name: Run tests
45+ run: cabal test --enable-tests all
46+ - name: Build Docs
47+ run: cabal haddock
.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+44−40
@@ -1,57 +1,61 @@
1−# Revision history for reflex
1+# Revision history for patch
22
3−## 0.6.2.4
3+## Unreleased
44
5−* Update to monoidal-containers 0.6
5+* New dep of `data-orphans` for old GHC to get instances honestly instead of
6+ via `monoidal-containers`.
67
7−## 0.6.2.3
8+## 0.0.5.0 - 2021-12-17
89
9−* Add an upper-bound to witherable
10+* `Additive` now lives in `Data.Semigroup.Additive`, but is still reexported
11+ from `Data.Patch` for compatability.
1012
11−## 0.6.2.2
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.
1218
13−* Support these >= 1. Add `split-these` flag to control whether to use new these/semialign combination or not.
14−* Update version bounds to fix some CI failures
15−* Add travis CI configuration
19+## 0.0.4.0 - 2021-04-20
1620
17−## 0.6.2.1
21+* Enable PolyKinds
1822
19−* Generalize `fan` to `fanG` to take a `DMap` with non-`Identity`
20− functor:
21− * `fan` to `fanG`
22− * `EventSelectorG` for `fanG` result selector.
23+## 0.0.3.2 - 2020-11-06
2324
24−* Reduce the amount of unsafeCoerce in coercing newtypes under Event/Dynamic/Behavior.
25− * Add fused ReaderIO for the purpose of coercion (ReaderT's third argument has nominal role preventing automated coerce)
26− * Add incrementalCoercion/coerceIncremental to go with dynamicCoercion/coerceDynamic
25+* Update version bounds
2726
28−* Generalize merging functions:
29− `merge` to `mergeG`,
30− `mergeIncremental` to `mergeIncrementalG`,
31− `mergeIncrementalWithMove` to `mergeIncrementalWithMoveG`.
27+## 0.0.3.1 - 2020-02-05
3228
33−* Generalize distribute function:
34− `distributeDMapOverDynPure` to `distributeDMapOverDynPureG`,
29+* Replace `fromJust` with something easier to debug.
3530
36−## 0.6.2.0
31+## 0.0.3.0 - 2020-02-05
3732
38−* Fix `holdDyn` so that it is lazy in its event argument
39− These produce `DMap`s whose values needn't be `Identity`.
40−* Stop using the now-deprecated `*Tag` classes (e.g., `ShowTag`).
41−* Fix `holdDyn` so that it is lazy in its event argument.
33+* Create `PatchMapWithPatchingMove` variant which supports moves with a patch.
4234
43−## 0.6.1.0
35+* Create `DecidablyEmpty` subclass of `Monoid`.
4436
45−* Re-export all of `Data.Map.Monoidal`
46−* Fix `QueryT` and `RequesterT` tests
37+## 0.0.2.0 - 2020-01-17
4738
48−## 0.6.0.0 -- 2019-03-20
39+* Consistently provide:
4940
50−* Deprecate `FunctorMaybe` in favor of `Data.Witherable.Filterable`. We still export `fmapMaybe`, `ffilter`, etc., but they all rely on `Filterable` now.
51−* Rename `MonadDynamicWriter` to `DynamicWriter` and add a deprecation for the old name.
52−* Remove many deprecated functions.
53−* Add a `Num` instance for `Dynamic`.
54−* Add `matchRequestsWithResponses` to make it easier to use `Requester` with protocols that don't do this matching for you.
55−* Add `withRequesterT` to map functions over the request and response of a `RequesterT`.
56−* Suppress nil patches in `QueryT` as an optimization. The `Query` type must now have an `Eq` instance.
57−* Add `throttleBatchWithLag` to `Reflex.Time`. See that module for details.
41+ - `Wrapped` instances
42+
43+ - `*WithIndex` instances
44+
45+ - `un*` newtype unwrappers
46+
47+ for `PatchMap`, `PatchIntMap`, and `PatchMapWithMove`.
48+
49+## 0.0.1.0 - 2020-01-09
50+
51+* Support older GHCs with `split-these` flag.
52+
53+* Additional instances for the `Group` class for basic types.
54+
55+## 0.0.0.1 - 2020-01-08
56+
57+* Remove unneeded dependencies
58+
59+## 0.0.0.0 - 2020-01-08
60+
61+* Extract patching functionality from Reflex.
Quickref.mddeleted−311
@@ -1,311 +0,0 @@
1−# Reflex Quick(ish) Reference
2−
3−## Typeclasses
4−
5−Many Reflex functions operate in monadic context `m a`, where the monad 'm' supports various additional typeclasses such as MonadWidget, MonadHold, or MonadSample in addition to Monad itself. The actual 'm' in use will be determined by the top-level entry point of the FRP host (such as Reflex-Dom -- see the bottom of the Reflex-Dom quick reference for details).
6−
7−The function signatures here have been simplified by removing many typeclass constraints and adding simple annotations to each function. Also the ubiquitous 't' type parameter has been removed.
8−
9−Some of these functions are *pure*: They operate on Events, Behaviors, or Dynamics uniformly without regard to the "current time". Other functions must operate in some monadic context, because they produce a result "as of now" (e.g., any function that takes an "initial" value, or returns a "current" value). Annotations are used to distinguish these cases:
10−
11−```haskell
12−[ ] -- Pure function
13−[S] -- Function runs in any monad supporting MonadSample
14−[H] -- Function runs in any monad supporting MonadHold
15−```
16−Since MonadHold depends on MonadSample, any [S] function also runs in [H] context.
17−
18−## Functions producing Event
19−
20−```haskell
21−-- Trivial Event
22−[ ] never :: Event a
23−
24−-- Extract Event from Dynamic
25−[ ] updated :: Dynamic a -> Event a
26−
27−-- Transform Event to Event using function
28−[ ] fmap :: (a -> b) -> Event a -> Event b
29−[ ] fmapMaybe :: (a -> Maybe b) -> Event a -> Event b
30−[ ] ffilter :: (a -> Bool) -> Event a -> Event a
31−[ ] ffor :: Event a -> (a -> b) -> Event b
32−[ ] fforMaybe :: Event a -> (a -> Maybe b) -> Event b
33−[ ] <$ :: a -> Event b -> Event a
34−
35−-- Event to identical Event with debug trace. (Only prints if Event is ultimately used.)
36−[ ] traceEvent :: Show a => String -> Event a -> Event a
37−[ ] traceEventWith :: (a -> String) -> Event a -> Event a
38−
39−-- Transform Event to Event by sampling Behavior or Dynamic
40−[ ] gate :: Behavior Bool -> Event a -> Event a
41−[ ] tag :: Behavior a -> Event b -> Event a
42−[ ] tagPromptlyDyn :: Dynamic a -> Event b -> Event a
43−[ ] attach :: Behavior a -> Event b -> Event (a, b)
44−[ ] attachPromptlyDyn :: Dynamic a -> Event b -> Event (a, b)
45−[ ] attachWith :: (a -> b -> c) -> Behavior a -> Event b -> Event c
46−[ ] attachPromptlyDynWith :: (a -> b -> c) -> Dynamic a -> Event b -> Event c
47−[ ] attachWithMaybe :: (a -> b -> Maybe c) -> Behavior a -> Event b -> Event c
48−[ ] attachPromptlyDynWithMaybe :: (a -> b -> Maybe c) -> Dynamic a -> Event b -> Event c
49−[ ] <@> :: Behavior (a -> b) -> Event a -> Event b
50−[ ] <@ :: Behavior a -> Event b -> Event a
51−
52−-- Combine multiple Events
53−[ ] <> :: Semigroup a => Event a -> Event a -> Event a
54−[ ] difference :: Event a -> Event b -> Event a
55−[ ] align :: Event a -> Event b -> Event (These a b)
56−[ ] alignWith :: (These a b -> c) -> Event a -> Event b -> Event c
57−[ ] mergeWith :: (a -> a -> a) -> [Event a] -> Event a
58−[ ] leftmost :: [Event a] -> Event a
59−[ ] mergeList :: [Event a] -> Event (NonEmpty a)
60−[ ] merge :: GCompare k => DMap k Event -> Event (DMap k Identity)
61−[ ] mergeMap :: Ord k => Map k (Event a) -> Event (Map k a)
62−
63−-- Efficient one-to-many fanout
64−[ ] fanMap :: Ord k => Event (Map k a) -> EventSelector (Const2 k a)
65−[ ] fan :: GCompare k => Event (DMap k Identity) -> EventSelector k
66−[ ] select :: EventSelector k -> k a -> Event a
67−[ ] fanEither :: Event (Either a b) -> (Event a, Event b)
68−[ ] fanThese :: Event (These a b) -> (Event a, Event b)
69−
70−-- Event to Event via function that can sample current values
71−[ ] push :: (a -> m (Maybe b)) -> Event a -> Event b
72−[ ] pushAlways :: (a -> m b ) -> Event a -> Event b
73− -- Note supplied function operates in [H] context
74−
75−-- Split Event into next occurrence and all other future occurrences, as of now.
76−[H] headE :: Event a -> m (Event a)
77−[H] tailE :: Event a -> m (Event a)
78−[H] headTailE :: Event a -> m (Event a, Event a)
79−```
80−
81−## Functions producing Behavior
82−
83−```haskell
84−-- Trivial Behavior
85−[ ] constant :: a -> Behavior a
86−
87−-- Extract Behavior from Dynamic
88−[ ] current :: Dynamic a -> Behavior a
89−
90−-- Create Behavior with given initial value, updated when the Event fires.
91−[H] hold :: a -> Event a -> m (Behavior a)
92−
93−-- Transform Behavior to Behavior using function
94−[ ] fmap :: (a -> b) -> Behavior a -> Behavior b
95−[ ] ffor :: Behavior a -> (a -> b) -> Behavior b
96−[ ] <*> :: Behavior (a -> b) -> Behavior a -> Behavior b
97−[ ] >>= :: Behavior a -> (a -> Behavior b) -> Behavior b
98−[ ] <> :: Monoid a => Behavior a -> Behavior a -> Behavior a
99−-- ... plus many more due to typeclass membership
100−
101−-- Combine multiple behaviors via applicative instance
102−[ ] ffor2 :: Behavior a -> Behavior b -> (a -> b -> c) -> Behavior c
103−[ ] ffor3 :: Behavior a -> Behavior b -> Behavior c -> (a -> b -> c -> d) -> Behavior d
104−
105−-- Behavior to Behavior by sampling current values
106−[S] sample :: Behavior a -> m a
107−[ ] pull :: m a -> Behavior a
108− -- Note supplied value is in [S] context
109−```
110−
111−## Functions producing Dynamic
112−
113−```haskell
114−-- Trivial Dynamic
115−[ ] constDyn :: a -> Dynamic a
116−
117−-- Create Dynamic with given initial value, updated (various ways) when the Event fires.
118−[H] holdDyn :: a -> Event a -> m (Dynamic a)
119−[H] foldDyn :: (a -> b -> b ) -> b -> Event a -> m (Dynamic b)
120−[H] foldDynMaybe :: (a -> b -> Maybe b ) -> b -> Event a -> m (Dynamic b)
121−[H] foldDynM :: (a -> b -> m' b ) -> b -> Event a -> m (Dynamic b)
122−[H] foldDynMaybeM :: (a -> b -> m' (Maybe b)) -> b -> Event a -> m (Dynamic b)
123− -- Note m' supplies [H] context
124−
125−-- Initial value is 0; counts Event firings from now.
126−[H] count :: Num b => Event a -> m (Dynamic b)
127−-- Initial Bool value is supplied; toggles at each Event firing.
128−[H] toggle :: Bool -> Event a -> m (Dynamic Bool)
129−
130−-- Transform Dynamic to Dynamic using function
131−[ ] ffor :: Dynamic a -> (a -> b) -> Dynamic b
132−[ ] fmap :: (a -> b) -> Dynamic a -> Dynamic b
133−[ ] splitDynPure :: Dynamic (a, b) -> (Dynamic a, Dynamic b)
134−
135−-- Combine multiple Dynamics
136−[ ] mconcat :: Monoid a => [Dynamic a] -> Dynamic a
137−[ ] distributeDMapOverDynPure :: GCompare k => DMap (WrapArg Dynamic k) -> Dynamic (DMap k)
138−[ ] <*> :: Dynamic (a -> b) -> Dynamic a -> Dynamic b
139−[ ] >>= :: Dynamic a -> (a -> Dynamic b) -> Dynamic b
140−[ ] zipDynWith :: (a -> b -> c) -> Dynamic a -> Dynamic b -> Dynamic c
141−
142−-- Combine multiple dynamics via applicative instance
143−[ ] ffor2 :: Dynamic a -> Dynamic b -> (a -> b -> c) -> Dynamic c
144−[ ] ffor3 :: Dynamic a -> Dynamic b -> Dynamic c -> (a -> b -> c -> d) -> Dynamic d
145−
146−-- Efficient one-to-many fanout
147−[ ] demux :: Ord k => Dynamic k -> Demux k
148−[ ] demuxed :: Eq k => Demux k -> k -> Dynamic Bool
149−
150−-- Dynamic to Dynamic, removing updates w/o value change
151−[H] holdUniqDyn :: Eq a => Dynamic a -> m (Dynamic a)
152−[H] holdUniqDynBy :: (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
153−
154−-- Dynamic to identical Dynamic with debug trace. (Only prints if Dynamic is ultimately used.)
155−[ ] traceDyn :: Show a => String -> Dynamic a -> Dynamic a
156−[ ] traceDynWith :: (a -> String) -> Dynamic a -> Dynamic a
157−```
158−
159−## Flattening functions
160−
161−These functions flatten nested types such as Event-of-Event, Behavior-of-Event, Event-of-Behavior etc, removing the outer wrapper.
162−
163−For Events, the returned Event fires whenever the latest Event supplied by the wrapper fires. There are differences in how the functions handle *coincidences* -- situations where the old or new Event fires at the same instant that we switch from old to new. In some cases, the output Event tracks the old Event at the instant of switchover, while in other cases it tracks the new Event.
164−
165−```haskell
166−-- Flatten Behavior-of-Event to Event. Old Event is used during switchover.
167−[ ] switch :: Behavior (Event a) -> Event a
168−
169−-- Flatten Dynamic-of-Event to Event. New Event is used immediately.
170−[ ] switchDyn :: Dynamic (Event a) -> Event a
171−
172−-- Flatten Event-of-Event to Event that fires when both wrapper AND new Event fire.
173−[ ] coincidence :: Event (Event a) -> Event a
174−
175−-- Flatten Behavior-of-Behavior to Behavior. Behavior is an instance of Monad,
176−-- so the 'join' function from 'Control.Monad' suffices. The output of 'join' is
177−-- a Behavior whose value is equal to the current value of the current value of
178−-- the input.
179−[ ] join :: Behavior (Behavior a) -> Behavior a
180−
181−
182−-- Flatten Dynamic-of-Dynamic to Dynamic. New Dynamic is used immediately.
183−-- Output updated whenever inner OR outer Dynamic updates.
184−[ ] join :: Dynamic (Dynamic a) -> Dynamic a
185−[ ] joinDynThroughMap :: Ord k => Dynamic (Map k (Dynamic a)) -> Dynamic (Map k a)
186−
187−-- Analogous to 'hold': Create a Behavior that is initially identical to the
188−-- supplied Behavior. Updated to track a new Behavior whenever the Event fires.
189−[H] switcher :: Behavior a -> Event (Behavior a) -> m (Behavior a)
190−
191−-- Similar to above, for Events. Created Event initially tracks the first argument.
192−-- At switchover, the output Event immediately tracks the new Event.
193−[H] switchHold :: Event a -> Event (Event a) -> m (Event a)
194−```
195−
196−## Typeclasses to introspect and modify an FRP network.
197−
198−The functions mentioned above are used to create a static FRP network.
199−There are additional typeclasses that can be used to modify the FRP network, to have it interact with IO action, or to introspect the building of the network.
200−
201−Th typeclasses and their associated annotations include:
202−
203−- `PostBuild`
204− Fire an Event when an FRP network has been set up.
205− ```haskell
206− [B] -- Function runs in any monad supporting PostBuild
207− ```
208−
209−- `Adjustable`
210− Use Events to add or remove pieces of an FRP network.
211− ```haskell
212− [A] -- Function runs in any monad supporting Adjustable
213− ```
214−
215−- `TriggerEvent`
216− Create new externally-fired Events from within an FRP network.
217− ```haskell
218− [T] -- Function runs in any monad supporting TriggerEvent
219− ```
220−
221−- `PerformEvent`
222− Use Events to trigger IO actions and to collect their results.
223− ```haskell
224− [P] -- Function runs in any monad supporting PerformEvent
225− ```
226−
227−## Startup
228−
229−```haskell
230−-- One-shot Event that is triggered once the FRP network has been built
231−[B] getPostBuild :: m (Event ())
232−```
233−
234−## Collection management functions
235−
236−```haskell
237−-- Turn a Dynamic key/value map into a set of dynamically-changing widgets.
238−[H,A,B] listWithKey :: Ord k =>
239− Dynamic (Map k v) -> (k -> Dynamic v -> m a ) -> m (Dynamic (Map k a))
240−
241−-- Same as above where the widget constructor doesn't care about the key.
242−[H,A,B] list :: Ord k =>
243− Dynamic (Map k v) -> ( Dynamic v -> m a ) -> m (Dynamic (Map k a))
244−
245−-- Even simpler version where there are no keys and we just use a list.
246−[H,A,B] simpleList ::
247− Dynamic [v] -> ( Dynamic v -> m a ) -> m (Dynamic [a])
248−
249−-- Like listWithKey specialized for widgets returning (Event a).
250−[H,A,B] listViewWithKey :: Ord k =>
251− Dynamic (Map k v) -> (k -> Dynamic v -> m (Event a)) -> m (Event (Map k a))
252−
253−-- Create a dynamically-changing set of widgets, one of which is selected at any time.
254−[H,A,B] selectViewListWithKey_ :: Ord k => Dynamic k ->
255− Dynamic (Map k v) -> (k -> Dynamic v -> Dynamic Bool -> m (Event a)) -> m (Event k)
256−
257−-- Same as listWithKey, but takes initial values and an updates Event instead of a Dynamic.
258−[H,A] listWithKeyShallowDiff :: Ord k =>
259− Map k v -> Event (Map k (Maybe v)) -> (k -> v -> Event v -> m a) -> m (Dynamic (Map k a))
260−```
261−
262−## Creating new events from within an FRP network.
263−
264−```haskell
265−-- Create a new Event and a function that will cause the Event to fire, from within an FRP network
266−[T] newTriggerEvent :: m (Event a, a -> IO ())
267−```
268−
269−## Connecting to the real world (I/O)
270−
271−```haskell
272−-- Run side-effecting actions in Event when it occurs; returned Event contains
273−-- results. Side effects run in the (Performable m) monad which is associated with
274−-- the (PerformEvent t m) typeclass constraint.
275−-- This allows for working with IO when a ((MonadIO (Performable m)) constraint is available.
276−[P] performEvent :: Event (Performable m a ) -> m (Event a)
277−
278−-- Just run side-effects; no return Event
279−[P] performEvent_ :: Event (Performable m ()) -> m ()
280−
281−-- Actions run asynchronously; actions are given a callback to send return values
282−[P,T] performEventAsync :: Event ((a -> IO ()) -> Performable m ()) -> m (Event a)
283−```
284−
285−### Time
286−
287−```haskell
288−-- Create Event at given interval with given basis time.
289−[P,T] tickLossy :: NominalDiffTime -> UTCTime -> m (Event t TickInfo)
290−
291−-- Delay an Event's occurrences by a given amount in seconds.
292−[P,T] delay :: NominalDiffTime -> Event t a -> m (Event t a)
293−```
294−
295−## Networks
296−
297−```haskell
298−-- Functions from Reflex.Network used to deal with Dynamics/Events carrying (m a)
299−
300−-- Given a Dynamic of network-creating actions, create a network that is recreated whenever the Dynamic updates.
301−-- The returned Event of network results occurs when the Dynamic does. Note: Often, the type a is an Event,
302−-- in which case the return value is an Event-of-Events that would typically be flattened (via switchHold).
303−[P,A] networkView :: Dynamic (m a) -> m (Event a)
304−
305−-- Given an initial network and an Event of network-creating actions, create a network that is recreated whenever the
306−-- Event fires. The returned Dynamic of network results occurs when the Event does. Note: Often, the type a is an
307−-- Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
308−[H,A] networkHold :: m a -> Event (m a) -> m (Dynamic a)
309−
310−-- Render a placeholder network to be shown while another network is not yet done building
311−[P,A] untilReady :: m a -> m b -> m (a, Event b)
README.md+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
default.nixdeleted−44
@@ -1,44 +0,0 @@
1−{ mkDerivation, ghc, base, bifunctors, containers, deepseq
2−, dependent-map, dependent-sum, exception-transformers
3−, haskell-src-exts, haskell-src-meta, hlint, lens, MemoTrie
4−, monad-control, mtl, primitive, random, ref-tf
5−, semigroupoids , semigroups, split, stdenv, stm, syb
6−, template-haskell , these, time, transformers
7−, transformers-compat, unbounded-delays, prim-uniq
8−, data-default, filepath, directory, filemanip, ghcjs-base
9−, monoidal-containers, witherable, profunctors
10−, splitThese ? (semialign != null), semialign ? null, these-lens ? null
11−, useTemplateHaskell ? true
12−}:
13−mkDerivation {
14− pname = "reflex";
15− version = "0.6.2.4";
16− src = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [ ".git" "dist" ])) ./.;
17− libraryHaskellDepends = [
18− base bifunctors containers dependent-map dependent-sum
19− exception-transformers lens
20− MemoTrie monad-control mtl primitive ref-tf semigroupoids
21− semigroups stm syb template-haskell these transformers
22− transformers-compat prim-uniq
23− base bifunctors containers deepseq dependent-map dependent-sum
24− mtl ref-tf split transformers data-default
25− random time unbounded-delays monoidal-containers witherable
26− profunctors
27− ] ++ (if ghc.isGhcjs or false then [
28− ghcjs-base
29− ] else []) ++ (if !useTemplateHaskell then [] else [
30− haskell-src-exts haskell-src-meta
31− ]) ++ (if splitThese then [
32− semialign
33− these-lens
34− ] else []);
35− testHaskellDepends = if ghc.isGhcjs or false then [] else [
36− hlint filepath directory filemanip
37− ];
38− configureFlags =
39− stdenv.lib.optional (!useTemplateHaskell) [ "-f-use-template-haskell" ] ++
40− stdenv.lib.optional (!splitThese) [ "-f-split-these" ];
41− homepage = "https://github.com/reflex-frp/reflex";
42− description = "Higher-order Functional Reactive Programming";
43− license = stdenv.lib.licenses.bsd3;
44−}
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+4−3
@@ -1,7 +1,8 @@
11{
22 "owner": "reflex-frp",
33 "repo": "reflex-platform",
4− "branch": "jailbreakTheselens",
5− "rev": "4284ed527c96c373538dc7e31776d9a50ca6aa91",
6− "sha256": "1m1nkxq7ng9wnqbd77xn8d81f2iz8g61y5m0r3gp0gi0q59jm8ay"
4+ "branch": "master",
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−400
@@ -1,400 +0,0 @@
1−Name: reflex
2−Version: 0.6.2.4
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− profunctors >= 5.3 && < 5.5,
62− lens >= 4.7 && < 5,
63− monad-control >= 1.0.1 && < 1.1,
64− mtl >= 2.1 && < 2.3,
65− prim-uniq >= 0.1.0.1 && < 0.2,
66− primitive >= 0.5 && < 0.8,
67− profunctors,
68− random == 1.1.*,
69− ref-tf == 0.4.*,
70− reflection == 2.1.*,
71− semigroupoids >= 4.0 && < 6,
72− stm >= 2.4 && < 2.6,
73− syb >= 0.5 && < 0.8,
74− time >= 1.4 && < 1.9,
75− transformers >= 0.5.6.0 && < 0.6,
76− unbounded-delays >= 0.1.0.0 && < 0.2,
77− witherable >= 0.3 && < 0.3.2
78−
79− if flag(split-these)
80− build-depends: these >= 1 && <1.1,
81− semialign >=1 && <1.2,
82− monoidal-containers >= 0.6 && < 0.7
83− else
84− build-depends: these >= 0.4 && <0.9,
85− monoidal-containers == 0.4.0.0
86−
87− exposed-modules:
88− Control.Monad.ReaderIO
89− Data.AppendMap,
90− Data.FastMutableIntMap,
91− Data.FastWeakBag,
92− Data.Functor.Misc,
93− Data.Map.Misc,
94− Data.WeakBag,
95− Reflex,
96− Reflex.Class,
97− Reflex.Adjustable.Class,
98− Reflex.BehaviorWriter.Base,
99− Reflex.BehaviorWriter.Class,
100− Reflex.Collection,
101− Reflex.Dynamic,
102− Reflex.Dynamic.Uniq,
103− Reflex.DynamicWriter,
104− Reflex.DynamicWriter.Base,
105− Reflex.DynamicWriter.Class,
106− Reflex.EventWriter,
107− Reflex.EventWriter.Base,
108− Reflex.EventWriter.Class,
109− Reflex.FastWeak,
110− Reflex.FunctorMaybe,
111− Reflex.Host.Class,
112− Reflex.Network,
113− Reflex.NotReady.Class,
114− Reflex.Patch,
115− Reflex.Patch.Class,
116− Reflex.Patch.DMap,
117− Reflex.Patch.DMapWithMove,
118− Reflex.Patch.IntMap,
119− Reflex.Patch.Map,
120− Reflex.Patch.MapWithMove,
121− Reflex.PerformEvent.Base,
122− Reflex.PerformEvent.Class,
123− Reflex.PostBuild.Base,
124− Reflex.PostBuild.Class,
125− Reflex.Profiled,
126− Reflex.Pure,
127− Reflex.Query.Base,
128− Reflex.Query.Class,
129− Reflex.Requester.Base,
130− Reflex.Requester.Class,
131− Reflex.Spider,
132− Reflex.Spider.Internal,
133− Reflex.Time,
134− Reflex.TriggerEvent.Base,
135− Reflex.TriggerEvent.Class,
136− Reflex.Widget.Basic,
137− Reflex.Workflow
138−
139− ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs -funbox-strict-fields -O2 -fspecialise-aggressively
140−
141− if flag(debug-trace-events)
142− cpp-options: -DDEBUG_TRACE_EVENTS
143− build-depends: bytestring
144−
145− if flag(use-reflex-optimizer)
146− cpp-options: -DUSE_REFLEX_OPTIMIZER
147− build-depends: ghc
148− exposed-modules: Reflex.Optimizer
149−
150− if flag(use-template-haskell)
151− cpp-options: -DUSE_TEMPLATE_HASKELL
152− build-depends:
153− dependent-sum >= 0.6 && < 0.7,
154− haskell-src-exts >= 1.16 && < 1.22,
155− haskell-src-meta >= 0.6 && < 0.9,
156− template-haskell >= 2.9 && < 2.15
157− exposed-modules:
158− Reflex.Dynamic.TH
159− other-extensions: TemplateHaskell
160− else
161− build-depends:
162− dependent-sum >= 0.6 && < 0.7
163−
164− if flag(fast-weak) && impl(ghcjs)
165− cpp-options: -DGHCJS_FAST_WEAK
166−
167− if impl(ghcjs)
168− build-depends: ghcjs-base
169−
170−test-suite semantics
171− type: exitcode-stdio-1.0
172− main-is: semantics.hs
173− hs-source-dirs: test
174− ghc-options: -O2 -Wall -rtsopts
175− build-depends:
176− base,
177− bifunctors,
178− containers,
179− deepseq,
180− dependent-map,
181− dependent-sum,
182− mtl,
183− ref-tf,
184− reflex,
185− split,
186− transformers
187− other-modules:
188− Reflex.Bench.Focused
189− Reflex.Plan.Pure
190− Reflex.Plan.Reflex
191− Reflex.Test
192− Reflex.Test.Micro
193− Reflex.TestPlan
194−
195−test-suite CrossImpl
196− type: exitcode-stdio-1.0
197− main-is: Reflex/Test/CrossImpl.hs
198− hs-source-dirs: test
199− ghc-options: -O2 -Wall -rtsopts
200− build-depends:
201− base,
202− containers,
203− dependent-map,
204− dependent-sum,
205− deepseq,
206− mtl,
207− transformers,
208− ref-tf,
209− reflex
210− other-modules:
211− Reflex.Test
212− Reflex.TestPlan
213− Reflex.Plan.Reflex
214− Reflex.Plan.Pure
215−
216−test-suite hlint
217− type: exitcode-stdio-1.0
218− main-is: hlint.hs
219− hs-source-dirs: test
220− build-depends: base
221− , directory
222− , filepath
223− , filemanip
224− , hlint < 2.1 || >= 2.2.2
225− if impl(ghcjs)
226− buildable: False
227−
228−test-suite EventWriterT
229− type: exitcode-stdio-1.0
230− main-is: EventWriterT.hs
231− hs-source-dirs: test
232− build-depends: base
233− , containers
234− , deepseq
235− , dependent-map
236− , dependent-sum
237− , lens
238− , mtl
239− , these
240− , transformers
241− , reflex
242− , ref-tf
243−
244− if flag(split-these)
245− build-depends: these-lens
246−
247− other-modules:
248− Reflex.Test
249− Reflex.TestPlan
250− Reflex.Plan.Reflex
251− Reflex.Plan.Pure
252− Test.Run
253−
254−
255−test-suite RequesterT
256− type: exitcode-stdio-1.0
257− main-is: RequesterT.hs
258− hs-source-dirs: test
259− build-depends: base
260− , containers
261− , deepseq
262− , dependent-sum
263− , dependent-map
264− , lens
265− , mtl
266− , these
267− , transformers
268− , reflex
269− , ref-tf
270−
271− if flag(split-these)
272− build-depends: these-lens
273−
274− other-modules:
275− Reflex.TestPlan
276− Reflex.Plan.Pure
277− Test.Run
278−
279−test-suite QueryT
280− type: exitcode-stdio-1.0
281− main-is: QueryT.hs
282− hs-source-dirs: test
283− build-depends: base
284− , containers
285− , dependent-map
286− , dependent-sum
287− , deepseq
288− , lens
289− , monoidal-containers
290− , mtl
291− , ref-tf
292− , reflex
293− , these
294− , transformers
295−
296− if flag(split-these)
297− build-depends: semialign, these-lens
298−
299− other-modules:
300− Test.Run
301− Reflex.TestPlan
302− Reflex.Plan.Reflex
303− Reflex.Plan.Pure
304−
305−test-suite GC-Semantics
306− type: exitcode-stdio-1.0
307− main-is: GC.hs
308− hs-source-dirs: test
309− build-depends: base
310− , containers
311− , dependent-sum
312− , dependent-map
313− , deepseq
314− , mtl
315− , these
316− , transformers
317− , reflex
318− , ref-tf
319−
320− if flag(split-these)
321− build-depends: semialign
322−
323− other-modules:
324− Reflex.Plan.Pure
325− Reflex.Plan.Reflex
326− Reflex.TestPlan
327− Test.Run
328−
329−test-suite rootCleanup
330− type: exitcode-stdio-1.0
331− main-is: rootCleanup.hs
332− hs-source-dirs: test
333− build-depends: base
334− , containers
335− , deepseq
336− , dependent-sum
337− , mtl
338− , reflex
339− , ref-tf
340− , these
341− other-modules:
342− Reflex.Plan.Pure
343− Reflex.TestPlan
344− Test.Run
345−
346−benchmark spider-bench
347− type: exitcode-stdio-1.0
348− hs-source-dirs: bench test
349− main-is: Main.hs
350− ghc-options: -Wall -O2 -rtsopts
351− build-depends:
352− base,
353− containers,
354− criterion,
355− deepseq,
356− dependent-map,
357− dependent-sum,
358− ref-tf,
359− mtl,
360− primitive,
361− reflex,
362− split,
363− stm,
364− transformers
365− other-modules:
366− Reflex.TestPlan
367− Reflex.Plan.Reflex
368− Reflex.Bench.Focused
369−
370−benchmark saulzar-bench
371− type: exitcode-stdio-1.0
372− hs-source-dirs: bench test
373− c-sources: bench-cbits/checkCapability.c
374− main-is: RunAll.hs
375− ghc-options: -Wall -O2 -rtsopts -threaded
376− build-depends:
377− base,
378− containers,
379− criterion,
380− deepseq,
381− dependent-map,
382− dependent-sum,
383− loch-th,
384− mtl,
385− primitive,
386− process,
387− ref-tf,
388− reflex,
389− split,
390− stm,
391− time,
392− transformers
393− other-modules:
394− Reflex.TestPlan
395− Reflex.Plan.Reflex
396− Reflex.Bench.Focused
397−
398−source-repository head
399− type: git
400− location: https://github.com/reflex-frp/reflex
release.nix+24−13
@@ -17,22 +17,33 @@ let
1717 ] ++ lib.optionals (reflex-platform.iosSupport) [
1818 "ghcIosAarch64"
1919 ];
20− hsPkgs = lib.genAttrs compilers (ghc: let
21− ghc' = reflex-platform.${ghc}.override {
22− overrides = self: super: {
23− reflex-useTemplateHaskell = self.callPackage ./. { useTemplateHaskell = true; };
24− reflex = self.callPackage ./. { useTemplateHaskell = false; };
25− };
20+ compilerPkgs = lib.genAttrs compilers (ghc: let
21+ reflex-platform = reflex-platform-fun {
22+ inherit system;
23+ haskellOverlays = [
24+ # Use this package's source for reflex
25+ (self: super: {
26+ _dep = super._dep // {
27+ patch = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
28+ "release.nix"
29+ ".git"
30+ "dist"
31+ "dist-newstyle"
32+ "cabal.haskell-ci"
33+ "cabal.project"
34+ ".travis.yml"
35+ ])) ./.;
36+ };
37+ })
38+ ];
2639 };
27− in {
28− inherit (ghc') reflex reflex-useTemplateHaskell;
29− });
30− in hsPkgs // {
31− cache = reflex-platform.pinBuildInputs "reflex-${system}"
32− (lib.concatLists (map builtins.attrValues (builtins.attrValues hsPkgs)));
40+ in reflex-platform.${ghc}.patch);
41+ in compilerPkgs // {
42+ cache = reflex-platform.pinBuildInputs "patch-${system}"
43+ (builtins.attrValues compilerPkgs);
3344 });
3445
35− metaCache = native-reflex-platform.pinBuildInputs "reflex-everywhere"
46+ metaCache = native-reflex-platform.pinBuildInputs "patch-everywhere"
3647 (map (a: a.cache) (builtins.attrValues perPlatform));
3748
3849in 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 (map, null)
24−
25−import Data.Coerce
26−import Data.Default
27−import Data.Map (Map)
28−#if MIN_VERSION_containers(0,5,11)
29−import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith)
30−#else
31−import qualified Data.Map as Map (showTree, showTreeWith)
32−#endif
33−import qualified Data.Witherable as W
34−import Data.Map.Monoidal
35−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−156
@@ -1,156 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ExistentialQuantification #-}
3−#ifdef USE_REFLEX_OPTIMIZER
4−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5−#endif
6−#ifdef GHCJS_FAST_WEAK
7−{-# LANGUAGE ForeignFunctionInterface #-}
8−{-# LANGUAGE JavaScriptFFI #-}
9−#endif
10−-- | This module defines the 'FastWeakBag' type, which represents a mutable
11−-- collection of items that does not cause the items to be retained in memory.
12−-- This is useful for situations where a value needs to be inspected or modified
13−-- if it is still alive, but can be ignored if it is dead.
14−module Data.FastWeakBag
15− ( FastWeakBag
16− , FastWeakBagTicket
17− , empty
18− , isEmpty
19− , insert
20− , traverse
21− , remove
22− -- * Internal functions
23− -- These will not always be available.
24−#ifndef GHCJS_FAST_WEAK
25− , _weakBag_children --TODO: Don't export this
26−#endif
27− ) where
28−
29−import Prelude hiding (traverse)
30−
31−import Control.Monad
32−import Control.Monad.IO.Class
33−
34−#ifdef GHCJS_FAST_WEAK
35−import GHCJS.Types
36−import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)
37−#else
38−import Control.Exception
39−import Data.IntMap.Strict (IntMap)
40−import qualified Data.IntMap.Strict as IntMap
41−import Data.IORef
42−import System.Mem.Weak
43−#endif
44−
45−-- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them -
46−-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
47−-- alive, the 'FastWeakBag' will continue to refer to them.
48−#ifdef GHCJS_FAST_WEAK
49−newtype FastWeakBag a = FastWeakBag JSVal
50−#else
51−data FastWeakBag a = FastWeakBag
52− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
53− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'
54− }
55−#endif
56−
57−-- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned. If
58−-- the caller retains the ticket, the item is guranteed to stay in memory (and
59−-- thus in the 'FastWeakBag'). The ticket can also be used to remove the item from
60−-- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.
61−#ifdef GHCJS_FAST_WEAK
62−newtype FastWeakBagTicket a = FastWeakBagTicket JSVal
63−#else
64−data FastWeakBagTicket a = FastWeakBagTicket
65− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
66− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
67− }
68−#endif
69−
70−-- | Insert an item into a 'FastWeakBag'.
71−{-# INLINE insert #-}
72−insert :: a -- ^ The item
73− -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into
74− -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item
75− -- is retained and allows the item to be removed.
76−#ifdef GHCJS_FAST_WEAK
77−insert a wb = js_insert (unsafeToRawJSVal a) wb
78−foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)
79−#else
80−insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do
81− a' <- evaluate a
82− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
83− let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())
84− wa <- mkWeakPtr a' $ Just cleanup
85− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
86− return $ FastWeakBagTicket
87− { _weakBagTicket_weakItem = wa
88− , _weakBagTicket_item = a'
89− }
90−#endif
91−
92−-- | Create an empty 'FastWeakBag'.
93−{-# INLINE empty #-}
94−empty :: IO (FastWeakBag a)
95−#ifdef GHCJS_FAST_WEAK
96−empty = js_empty
97−foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)
98−#else
99−empty = {-# SCC "empty" #-} do
100− nextId <- newIORef 1
101− children <- newIORef IntMap.empty
102− let bag = FastWeakBag
103− { _weakBag_nextId = nextId
104− , _weakBag_children = children
105− }
106− return bag
107−#endif
108−
109−-- | Check whether a 'FastWeakBag' is empty.
110−{-# INLINE isEmpty #-}
111−isEmpty :: FastWeakBag a -> IO Bool
112−#ifdef GHCJS_FAST_WEAK
113−isEmpty = js_isEmpty
114−foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time
115−#else
116−isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)
117−#endif
118−
119−{-# INLINE traverse #-}
120−-- | Visit every node in the given list. If new nodes are appended during the
121−-- traversal, they will not be visited. Every live node that was in the list
122−-- when the traversal began will be visited exactly once; however, no guarantee
123−-- is made about the order of the traversal.
124−traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
125−#ifdef GHCJS_FAST_WEAK
126−traverse wb f = do
127− let go cursor = when (not $ js_isNull cursor) $ do
128− val <- liftIO $ js_getTicketValue cursor
129− f $ unsafeFromRawJSVal val
130− go =<< liftIO (js_getNext (FastWeakBagTicket cursor))
131− go =<< liftIO (js_getInitial wb)
132−foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
133−foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal
134−--TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag
135−foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
136−#else
137−traverse (FastWeakBag _ children) f = {-# SCC "traverse" #-} do
138− cs <- liftIO $ readIORef children
139− forM_ cs $ \c -> do
140− ma <- liftIO $ deRefWeak c
141− mapM_ f ma
142−#endif
143−
144−-- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times
145−-- on the same 'FastWeakBagTicket'.
146−{-# INLINE remove #-}
147−remove :: FastWeakBagTicket a -> IO ()
148−#ifdef GHCJS_FAST_WEAK
149−remove = js_remove
150−foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here
151−#else
152−remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w
153−#endif
154−--TODO: Should 'remove' also drop the reference to the item?
155−
156−--TODO: can/should we provide a null FastWeakBagTicket?
src/Data/Functor/Misc.hs+4−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−121
@@ -1,121 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ExistentialQuantification #-}
4−#ifdef USE_REFLEX_OPTIMIZER
5−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
6−#endif
7−-- | This module defines the 'WeakBag' type, which represents a mutable
8−-- collection of items that does not cause the items to be retained in memory.
9−-- This is useful for situations where a value needs to be inspected or modified
10−-- if it is still alive, but can be ignored if it is dead.
11−module Data.WeakBag
12− ( WeakBag
13− , WeakBagTicket
14− , empty
15− , singleton
16− , insert
17− , traverse
18− , remove
19− -- * Internal functions
20− -- These will not always be available.
21− , _weakBag_children --TODO: Don't export this
22− ) where
23−
24−import Prelude hiding (traverse)
25−
26−import Control.Exception
27−import Control.Monad
28−import Control.Monad.IO.Class
29−import Data.IntMap.Strict (IntMap)
30−import qualified Data.IntMap.Strict as IntMap
31−import Data.IORef
32−import System.Mem.Weak
33−
34−-- | A 'WeakBag' holds a set of values of type @/a/@, but does not retain them -
35−-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
36−-- alive, the 'WeakBag' will continue to refer to them.
37−data WeakBag a = WeakBag
38− { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
39− , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ The items referenced by the WeakBag
40− }
41−
42−-- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned. If
43−-- the caller retains the ticket, the item is guranteed to stay in memory (and
44−-- thus in the 'WeakBag'). The ticket can also be used to remove the item from
45−-- the 'WeakBag' prematurely (i.e. while it is still alive), using 'remove'.
46−data WeakBagTicket = forall a. WeakBagTicket
47− { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
48− , _weakBagTicket_item :: {-# NOUNPACK #-} !a
49− }
50−
51−-- | Insert an item into a 'WeakBag'.
52−{-# INLINE insert #-}
53−insert :: a -- ^ The item
54− -> WeakBag a -- ^ The 'WeakBag' to insert into
55− -> IORef (Weak b) -- ^ An arbitrary value to be used in the following
56− -- callback
57− -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed
58− -- (whether automatically by the item being garbage
59− -- collected or manually via 'remove')
60− -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item
61− -- is retained and allows the item to be removed.
62−insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do
63− a' <- evaluate a
64− wbRef' <- evaluate wbRef
65− myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
66− let cleanup = do
67− wb <- readIORef wbRef'
68− mb <- deRefWeak wb
69− forM_ mb $ \b -> do
70− csWithoutMe <- atomicModifyIORef children $ \cs ->
71− let !csWithoutMe = IntMap.delete myId cs
72− in (csWithoutMe, csWithoutMe)
73− when (IntMap.null csWithoutMe) $ finalizer b
74− wa <- mkWeakPtr a' $ Just cleanup
75− atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
76− return $ WeakBagTicket
77− { _weakBagTicket_weakItem = wa
78− , _weakBagTicket_item = a'
79− }
80−
81−-- | Create an empty 'WeakBag'.
82−{-# INLINE empty #-}
83−empty :: IO (WeakBag a)
84−empty = {-# SCC "empty" #-} do
85− nextId <- newIORef 1
86− children <- newIORef IntMap.empty
87− let bag = WeakBag
88− { _weakBag_nextId = nextId
89− , _weakBag_children = children
90− }
91− return bag
92−
93−-- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with
94−-- 'empty', then using 'insert'.
95−{-# INLINE singleton #-}
96−singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
97−singleton a wbRef finalizer = {-# SCC "singleton" #-} do
98− bag <- empty
99− ticket <- insert a bag wbRef finalizer
100− return (bag, ticket)
101−
102−{-# INLINE traverse #-}
103−-- | Visit every node in the given list. If new nodes are appended during the
104−-- traversal, they will not be visited. Every live node that was in the list
105−-- when the traversal began will be visited exactly once; however, no guarantee
106−-- is made about the order of the traversal.
107−traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
108−traverse (WeakBag _ children) f = {-# SCC "traverse" #-} do
109− cs <- liftIO $ readIORef children
110− forM_ cs $ \c -> do
111− ma <- liftIO $ deRefWeak c
112− mapM_ f ma
113−
114−-- | Remove an item from the 'WeakBag'; does nothing if invoked multiple times
115−-- on the same 'WeakBagTicket'.
116−{-# INLINE remove #-}
117−remove :: WeakBagTicket -> IO ()
118−remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w
119−--TODO: Should 'remove' also drop the reference to the item?
120−
121−--TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hsdeleted−35
@@ -1,35 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−-- | This module exports all of the commonly-used functionality of Reflex; if
3−-- you are just getting started with Reflex, this is probably what you want.
4−module Reflex
5− ( module X
6− ) where
7−
8−import Reflex.Class as X
9−import Reflex.Adjustable.Class as X
10−import Reflex.BehaviorWriter.Base as X
11−import Reflex.BehaviorWriter.Class as X
12−import Reflex.Collection as X
13−import Reflex.Dynamic as X
14−import Reflex.EventWriter.Base as X
15−import Reflex.EventWriter.Class as X
16−#ifdef USE_TEMPLATE_HASKELL
17−import Reflex.Dynamic.TH as X
18−#endif
19−import Reflex.Dynamic.Uniq as X
20−import Reflex.DynamicWriter.Base as X
21−import Reflex.DynamicWriter.Class as X
22−import Reflex.NotReady.Class as X
23−import Reflex.PerformEvent.Base as X
24−import Reflex.PerformEvent.Class as X
25−import Reflex.PostBuild.Base as X
26−import Reflex.PostBuild.Class as X
27−import Reflex.Profiled as X
28−import Reflex.Query.Base as X
29−import Reflex.Query.Class as X
30−import Reflex.Requester.Base as X
31−import Reflex.Requester.Class as X
32−import Reflex.Spider as X
33−import Reflex.Time as X
34−import Reflex.TriggerEvent.Base as X
35−import Reflex.TriggerEvent.Class as X
src/Reflex/Adjustable/Class.hsdeleted−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−1675
@@ -1,1675 +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− coincidence :: Event t (Event t a) -> Event t a
291− -- | Extract the 'Behavior' of a 'Dynamic'.
292− current :: Dynamic t a -> Behavior t a
293− -- | Extract the 'Event' of the 'Dynamic'.
294− updated :: Dynamic t a -> Event t a
295− -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
296− -- recent firing of the given 'Event', if any.
297− unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
298− -- | Create a new 'Incremental'. The given "PullM"'s value must always change
299− -- in the same way that the accumulated application of patches would change
300− -- that value.
301− unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
302− -- | Create a merge whose parents can change over time
303− mergeIncrementalG :: GCompare k
304− => (forall a. q a -> Event t (v a))
305− -> Incremental t (PatchDMap k q)
306− -> Event t (DMap k v)
307− -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
308− mergeIncrementalWithMoveG :: GCompare k
309− => (forall a. q a -> Event t (v a))
310− -> Incremental t (PatchDMapWithMove k q) -> Event t (DMap k v)
311− -- | Extract the 'Behavior' component of an 'Incremental'
312− currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
313− -- | Extract the 'Event' component of an 'Incremental'
314− updatedIncremental :: Patch p => Incremental t p -> Event t p
315− -- | Convert an 'Incremental' to a 'Dynamic'
316− incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
317− -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
318− -- occurrence type
319− behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
320− -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
321− -- occurrence type
322− eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
323− -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
324− -- occurrence type
325− dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
326− -- | Construct a 'Coercion' for an 'Incremental' given 'Coercion's for its
327− -- patch target and patch types.
328− incrementalCoercion
329− :: Coercion (PatchTarget a) (PatchTarget b) -> Coercion a b -> Coercion (Incremental t a) (Incremental t b)
330− mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
331− fanInt :: Event t (IntMap a) -> EventSelectorInt t a
332−
333−-- | Efficiently fan-out an event to many destinations. You should save the
334−-- result in a @let@-binding, and then repeatedly 'select' on the result to
335−-- create child events
336−fan :: forall t k. (Reflex t, GCompare k)
337− => Event t (DMap k Identity) -> EventSelector t k
338− --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
339−fan e = EventSelector (fixup (selectG (fanG e) :: k a -> Event t (Identity a)) :: forall a. k a -> Event t a)
340− where
341− fixup :: forall a. (k a -> Event t (Identity a)) -> k a -> Event t a
342− fixup = case eventCoercion Coercion :: Coercion (Event t (Identity a)) (Event t a) of
343− Coercion -> coerce
344−
345−--TODO: Specialize this so that we can take advantage of knowing that there's no changing going on
346−-- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple
347−-- keys simultaneously.
348−mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
349−mergeInt m = mergeIntIncremental $ unsafeBuildIncremental (return m) never
350−
351−-- | Coerce a 'Behavior' between representationally-equivalent value types
352−coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
353−coerceBehavior = coerceWith $ behaviorCoercion Coercion
354−
355−-- | Coerce an 'Event' between representationally-equivalent occurrence types
356−coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
357−coerceEvent = coerceWith $ eventCoercion Coercion
358−
359−-- | Coerce a 'Dynamic' between representationally-equivalent value types
360−coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
361−coerceDynamic = coerceWith $ dynamicCoercion Coercion
362−
363−-- | Coerce an 'Incremental' between representationally-equivalent value types
364−coerceIncremental
365− :: (Reflex t, Coercible a b, Coercible (PatchTarget a) (PatchTarget b))
366− => Incremental t a -> Incremental t b
367−coerceIncremental = coerceWith $ incrementalCoercion Coercion Coercion
368−
369−-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
370−-- __must__ change when and only when the 'Event' fires, such that the
371−-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
372−-- if this is not the case, the resulting 'Dynamic' will behave
373−-- nondeterministically.
374−unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
375−unsafeDynamic = unsafeBuildDynamic . sample
376−
377−-- | Construct a 'Dynamic' value that never changes
378−constDyn :: Reflex t => a -> Dynamic t a
379−constDyn = pure
380−
381−instance (Reflex t, Default a) => Default (Dynamic t a) where
382− def = pure def
383−
384−-- | 'MonadSample' designates monads that can read the current value of a
385−-- 'Behavior'. This includes both 'PullM' and 'PushM'.
386−class (Applicative m, Monad m) => MonadSample t m | m -> t where
387− -- | Get the current value in the 'Behavior'
388− sample :: Behavior t a -> m a
389−
390−-- | 'MonadHold' designates monads that can create new 'Behavior's based on
391−-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
392−-- is required to create any stateful computations with Reflex.
393−class MonadSample t m => MonadHold t m where
394− -- | Create a new 'Behavior' whose value will initially be equal to the given
395− -- value and will be updated whenever the given 'Event' occurs. The update
396− -- takes effect immediately after the 'Event' occurs; if the occurrence that
397− -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
398− -- the 'Behavior', it will see the __old__ value of the 'Behavior', not the new
399− -- one.
400− hold :: a -> Event t a -> m (Behavior t a)
401− default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)
402− hold v0 = lift . hold v0
403− -- | Create a 'Dynamic' value using the given initial value that changes every
404− -- time the 'Event' occurs.
405− holdDyn :: a -> Event t a -> m (Dynamic t a)
406− default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)
407− holdDyn v0 = lift . holdDyn v0
408− -- | Create an 'Incremental' value using the given initial value that changes
409− -- every time the 'Event' occurs.
410− holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
411− default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)
412− holdIncremental v0 = lift . holdIncremental v0
413− buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)
414− {-
415− default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)
416− buildDynamic getV0 = lift . buildDynamic getV0
417− -}
418− -- | Create a new 'Event' that only occurs only once, on the first occurrence of
419− -- the supplied 'Event'.
420− headE :: Event t a -> m (Event t a)
421−
422−-- | Accumulate an 'Incremental' with the supplied initial value and the firings of the provided 'Event',
423−-- using the combining function to produce a patch.
424−accumIncremental
425− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
426− => (PatchTarget p -> b -> p)
427− -> PatchTarget p
428− -> Event t b
429− -> m (Incremental t p)
430−accumIncremental f = accumMaybeIncremental $ \v o -> Just $ f v o
431−
432−-- | Similar to 'accumIncremental' but the combining function runs in 'PushM'
433−accumMIncremental
434− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
435− => (PatchTarget p -> b -> PushM t p)
436− -> PatchTarget p
437− -> Event t b
438− -> m (Incremental t p)
439−accumMIncremental f = accumMaybeMIncremental $ \v o -> Just <$> f v o
440−
441−-- | Similar to 'accumIncremental' but allows filtering of updates (by dropping updates when the
442−-- combining function produces @Nothing@)
443−accumMaybeIncremental
444− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
445− => (PatchTarget p -> b -> Maybe p)
446− -> PatchTarget p
447− -> Event t b
448− -> m (Incremental t p)
449−accumMaybeIncremental f = accumMaybeMIncremental $ \v o -> return $ f v o
450−
451−-- | Similar to 'accumMaybeMIncremental' but the combining function runs in 'PushM'
452−accumMaybeMIncremental
453− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
454− => (PatchTarget p -> b -> PushM t (Maybe p))
455− -> PatchTarget p
456− -> Event t b
457− -> m (Incremental t p)
458−accumMaybeMIncremental f z e = do
459− rec let e' = flip push e $ \o -> do
460− v <- sample $ currentIncremental d'
461− f v o
462− d' <- holdIncremental z e'
463− return d'
464−
465−-- | Accumulate an 'Incremental' by folding occurrences of an 'Event'
466−-- with a function that both accumulates and produces a value to fire
467−-- as an 'Event'. Returns both the accumulated value and the constructed
468−-- 'Event'.
469−mapAccumIncremental
470− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
471− => (PatchTarget p -> b -> (p, c))
472− -> PatchTarget p
473− -> Event t b
474− -> m (Incremental t p, Event t c)
475−mapAccumIncremental f = mapAccumMaybeIncremental $ \v o -> bimap Just Just $ f v o
476−
477−-- | Like 'mapAccumIncremental' but the combining function runs in 'PushM'
478−mapAccumMIncremental
479− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
480− => (PatchTarget p -> b -> PushM t (p, c))
481− -> PatchTarget p
482− -> Event t b
483− -> m (Incremental t p, Event t c)
484−mapAccumMIncremental f = mapAccumMaybeMIncremental $ \v o -> bimap Just Just <$> f v o
485−
486−-- | Accumulate an 'Incremental' by folding occurrences of an 'Event' with
487−-- a function that both optionally accumulates and optionally produces
488−-- a value to fire as a separate output 'Event'.
489−-- Note that because 'Nothing's are discarded in both cases, the output
490−-- 'Event' may fire even though the output 'Incremental' has not changed, and
491−-- the output 'Incremental' may update even when the output 'Event' is not firing.
492−mapAccumMaybeIncremental
493− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
494− => (PatchTarget p -> b -> (Maybe p, Maybe c))
495− -> PatchTarget p
496− -> Event t b
497− -> m (Incremental t p, Event t c)
498−mapAccumMaybeIncremental f = mapAccumMaybeMIncremental $ \v o -> return $ f v o
499−
500−-- | Like 'mapAccumMaybeIncremental' but the combining function is a 'PushM' action
501−mapAccumMaybeMIncremental
502− :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
503− => (PatchTarget p -> b -> PushM t (Maybe p, Maybe c))
504− -> PatchTarget p
505− -> Event t b
506− -> m (Incremental t p, Event t c)
507−mapAccumMaybeMIncremental f z e = do
508− rec let e' = flip push e $ \o -> do
509− v <- sample $ currentIncremental d'
510− result <- f v o
511− return $ case result of
512− (Nothing, Nothing) -> Nothing
513− _ -> Just result
514− d' <- holdIncremental z $ mapMaybe fst e'
515− return (d', mapMaybe snd e')
516−
517−-- | A somewhat slow implementation of 'headE'
518−slowHeadE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
519−slowHeadE e = do
520− rec be <- hold e $ fmapCheap (const never) e'
521− let e' = switch be
522− return e'
523−
524−-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
525−-- key. This is much more efficient than filtering for each key with
526−-- 'mapMaybe'.
527−newtype EventSelector t k = EventSelector
528− { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
529− -- determined by the type of the key, so this can be used to fan-out
530− -- 'Event's whose sub-'Event's have different types.
531− --
532− -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
533− -- (but equivalent to) using 'mapMaybe' to select only the relevant
534− -- occurrences of an 'Event'.
535− select :: forall a. k a -> Event t a
536− }
537−
538−newtype EventSelectorG t k v = EventSelectorG
539− { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
540− -- determined by the type of the key, so this can be used to fan-out
541− -- 'Event's whose sub-'Event's have different types.
542− --
543− -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
544− -- (but equivalent to) using 'mapMaybe' to select only the relevant
545− -- occurrences of an 'Event'.
546− selectG :: forall a. k a -> Event t (v a)
547− }
548−
549−-- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually
550−-- filtering by key.
551−newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }
552−
553−--------------------------------------------------------------------------------
554−-- Instances
555−--------------------------------------------------------------------------------
556−
557−instance MonadSample t m => MonadSample t (ReaderT r m) where
558− sample = lift . sample
559−
560−instance MonadHold t m => MonadHold t (ReaderT r m) where
561− hold a0 = lift . hold a0
562− holdDyn a0 = lift . holdDyn a0
563− holdIncremental a0 = lift . holdIncremental a0
564− buildDynamic a0 = lift . buildDynamic a0
565− headE = lift . headE
566−
567−instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
568− sample = lift . sample
569−
570−instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
571− hold a0 = lift . hold a0
572− holdDyn a0 = lift . holdDyn a0
573− holdIncremental a0 = lift . holdIncremental a0
574− buildDynamic a0 = lift . buildDynamic a0
575− headE = lift . headE
576−
577−instance MonadSample t m => MonadSample t (StateT s m) where
578− sample = lift . sample
579−
580−instance MonadHold t m => MonadHold t (StateT s m) where
581− hold a0 = lift . hold a0
582− holdDyn a0 = lift . holdDyn a0
583− holdIncremental a0 = lift . holdIncremental a0
584− buildDynamic a0 = lift . buildDynamic a0
585− headE = lift . headE
586−
587−instance MonadSample t m => MonadSample t (ExceptT e m) where
588− sample = lift . sample
589−
590−instance MonadHold t m => MonadHold t (ExceptT e m) where
591− hold a0 = lift . hold a0
592− holdDyn a0 = lift . holdDyn a0
593− holdIncremental a0 = lift . holdIncremental a0
594− buildDynamic a0 = lift . buildDynamic a0
595− headE = lift . headE
596−
597−instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
598− sample = lift . sample
599−
600−instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
601− hold a0 = lift . hold a0
602− holdDyn a0 = lift . holdDyn a0
603− holdIncremental a0 = lift . holdIncremental a0
604− buildDynamic a0 = lift . buildDynamic a0
605− headE = lift . headE
606−
607−instance MonadSample t m => MonadSample t (ContT r m) where
608− sample = lift . sample
609−
610−instance MonadHold t m => MonadHold t (ContT r m) where
611− hold a0 = lift . hold a0
612− holdDyn a0 = lift . holdDyn a0
613− holdIncremental a0 = lift . holdIncremental a0
614− buildDynamic a0 = lift . buildDynamic a0
615− headE = lift . headE
616−
617−--------------------------------------------------------------------------------
618−-- Convenience functions
619−--------------------------------------------------------------------------------
620−
621−-- | Create an 'Event' from another 'Event'. The provided function can sample
622−-- 'Behavior's and hold 'Event's.
623−pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
624−pushAlways f = push (fmap Just . f)
625−
626−-- | Flipped version of 'fmap'.
627−ffor :: Functor f => f a -> (a -> b) -> f b
628−ffor = flip fmap
629−
630−-- | Rotated version of 'liftA2'.
631−ffor2 :: Applicative f => f a -> f b -> (a -> b -> c) -> f c
632−ffor2 a b f = liftA2 f a b
633−
634−-- | Rotated version of 'liftA3'.
635−ffor3 :: Applicative f => f a -> f b -> f c -> (a -> b -> c -> d) -> f d
636−ffor3 a b c f = liftA3 f a b c
637−
638−instance Reflex t => Applicative (Behavior t) where
639− pure = constant
640− f <*> x = pull $ sample f `ap` sample x
641− _ *> b = b
642− a <* _ = a
643−
644−instance Reflex t => Apply (Behavior t) where
645− (<.>) = (<*>)
646−
647−instance Reflex t => Bind (Behavior t) where
648− (>>-) = (>>=)
649−
650−instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
651− (/) = liftA2 (/)
652− fromRational = pure . fromRational
653− recip = fmap recip
654−
655−instance Reflex t => Functor (Behavior t) where
656− fmap f = pull . fmap f . sample
657−
658−instance (Reflex t, IsString a) => IsString (Behavior t a) where
659− fromString = pure . fromString
660−
661−instance Reflex t => Monad (Behavior t) where
662− a >>= f = pull $ sample a >>= sample . f
663− -- 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.
664− return = constant
665− fail = error "Monad (Behavior t) does not support fail"
666−
667−instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
668− mempty = constant mempty
669− mappend a b = pull $ liftM2 mappend (sample a) (sample b)
670− mconcat = pull . fmap mconcat . mapM sample
671−
672−instance (Reflex t, Num a) => Num (Behavior t a) where
673− (+) = liftA2 (+)
674− (-) = liftA2 (-)
675− (*) = liftA2 (*)
676− abs = fmap abs
677− fromInteger = pure . fromInteger
678− negate = fmap negate
679− signum = fmap signum
680−
681−instance (Num a, Reflex t) => Num (Dynamic t a) where
682− (+) = liftA2 (+)
683− (*) = liftA2 (*)
684− abs = fmap abs
685− signum = fmap signum
686− fromInteger = pure . fromInteger
687− negate = fmap negate
688− (-) = liftA2 (-)
689−
690−instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
691− a <> b = pull $ liftM2 (<>) (sample a) (sample b)
692− sconcat = pull . fmap sconcat . mapM sample
693− stimes n = fmap $ stimes n
694−
695−-- | Alias for 'mapMaybe'
696−fmapMaybe :: Filterable f => (a -> Maybe b) -> f a -> f b
697−fmapMaybe = mapMaybe
698−
699−-- | Flipped version of 'mapMaybe'.
700−fforMaybe :: Filterable f => f a -> (a -> Maybe b) -> f b
701−fforMaybe = flip mapMaybe
702−
703−-- | Filter 'f a' using the provided predicate.
704−ffilter :: Filterable f => (a -> Bool) -> f a -> f a
705−ffilter = W.filter
706−
707−-- | Filter 'Left's from 'f (Either a b)' into 'a'.
708−filterLeft :: Filterable f => f (Either a b) -> f a
709−filterLeft = mapMaybe (either Just (const Nothing))
710−
711−-- | Filter 'Right's from 'f (Either a b)' into 'b'.
712−filterRight :: Filterable f => f (Either a b) -> f b
713−filterRight = mapMaybe (either (const Nothing) Just)
714−
715−-- | Left-biased event union (prefers left event on simultaneous
716−-- occurrence).
717−instance Reflex t => Alt (Event t) where
718− ev1 <!> ev2 = leftmost [ev1, ev2]
719−
720−-- | 'Event' intersection. Only occurs when both events are co-incident.
721−instance Reflex t => Apply (Event t) where
722− evf <.> evx = mapMaybe f (align evf evx) where
723− f (These g a) = Just (g a)
724− f _ = Nothing
725−
726−
727−-- | 'Event' intersection (convenient interface to 'coincidence').
728−instance Reflex t => Bind (Event t) where
729− evx >>- f = coincidence (f <$> evx)
730− join = coincidence
731−
732−instance Reflex t => Functor (Event t) where
733− {-# INLINE fmap #-}
734− fmap f = mapMaybe $ Just . f
735− {-# INLINE (<$) #-}
736− x <$ e = fmapCheap (const x) e
737−
738−-- TODO Remove this instance
739−instance Reflex t => FunctorMaybe (Event t) where
740− {-# INLINE fmapMaybe #-}
741− fmapMaybe = mapMaybe
742−
743−instance Reflex t => Filterable (Event t) where
744− {-# INLINE mapMaybe #-}
745− mapMaybe f = push $ return . f
746−
747−-- | Never: @'zero' = 'never'@.
748−instance Reflex t => Plus (Event t) where
749− zero = never
750−
751−-- | Replace each occurrence value of the 'Event' with the value of the
752−-- 'Behavior' at the time of that occurrence.
753−tag :: Reflex t => Behavior t b -> Event t a -> Event t b
754−tag b = pushAlways $ \_ -> sample b
755−
756−-- | Replace each occurrence value of the 'Event' with the value of the
757−-- 'Behavior' at that time; if it is 'Just', fire with the contained value; if
758−-- it is 'Nothing', drop the occurrence.
759−tagMaybe :: Reflex t => Behavior t (Maybe b) -> Event t a -> Event t b
760−tagMaybe b = push $ \_ -> sample b
761−
762−-- | Create a new 'Event' that combines occurrences of supplied 'Event' with the
763−-- current value of the 'Behavior'.
764−attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
765−attach = attachWith (,)
766−
767−-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
768−-- combining it with the current value of the 'Behavior'.
769−attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
770−attachWith f = attachWithMaybe $ \a b -> Just $ f a b
771−
772−-- | Create a new 'Event' by combining each occurrence with the current value of
773−-- the 'Behavior'. The occurrence is discarded if the combining function returns
774−-- Nothing
775−attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
776−attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
777−
778−-- | Create a new 'Event' that occurs on all but the first occurrence of the
779−-- supplied 'Event'.
780−tailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a)
781−tailE e = snd <$> headTailE e
782−
783−-- | Create a tuple of two 'Event's with the first one occurring only the first
784−-- time the supplied 'Event' occurs and the second occurring on all but the first
785−-- occurrence.
786−headTailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a, Event t a)
787−headTailE e = do
788− eHead <- headE e
789− be <- hold never $ fmap (const e) eHead
790− return (eHead, switch be)
791−
792−-- | Take the streak of occurrences starting at the current time for which the
793−-- event returns 'True'.
794−--
795−-- Starting at the current time, fire all the occurrences of the 'Event' for
796−-- which the given predicate returns 'True'. When first 'False' is returned,
797−-- do not fire, and permanently stop firing, even if 'True' values would have
798−-- been encountered later.
799−takeWhileE
800− :: forall t m a
801− . (Reflex t, MonadFix m, MonadHold t m)
802− => (a -> Bool)
803− -> Event t a
804− -> m (Event t a)
805−takeWhileE f = takeWhileJustE $ \v -> guard (f v) $> v
806−
807−-- | Take the streak of occurrences starting at the current time for which the
808−-- event returns 'Just b'.
809−--
810−-- Starting at the current time, fire all the occurrences of the 'Event' for
811−-- which the given predicate returns 'Just b'. When first 'Nothing' is returned,
812−-- do not fire, and permanently stop firing, even if 'Just b' values would have
813−-- been encountered later.
814−takeWhileJustE
815− :: forall t m a b
816− . (Reflex t, MonadFix m, MonadHold t m)
817− => (a -> Maybe b)
818− -> Event t a
819− -> m (Event t b)
820−takeWhileJustE f e = do
821− rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of
822− Nothing -> Left never
823− Just b -> Right b
824− eFirstBad <- headE eBad
825− e' <- switchHold e eFirstBad
826− return eTrue
827−
828−-- | Drop the streak of occurrences starting at the current time for which the
829−-- event returns 'True'.
830−--
831−-- Starting at the current time, do not fire all the occurrences of the 'Event'
832−-- for which the given predicate returns 'True'. When 'False' is first
833−-- returned, do fire, and permanently continue firing, even if 'True' values
834−-- would have been encountered later.
835−dropWhileE
836− :: forall t m a
837− . (Reflex t, MonadFix m, MonadHold t m)
838− => (a -> Bool)
839− -> Event t a
840− -> m (Event t a)
841−dropWhileE f e = snd <$> takeDropWhileJustE (\v -> guard (f v) $> v) e
842−
843−-- | Both take and drop the streak of occurrences starting at the current time
844−-- for which the event returns 'Just b'.
845−--
846−-- For the left event, starting at the current time, fire all the occurrences
847−-- of the 'Event' for which the given function returns 'Just b'. When
848−-- 'Nothing' is returned, do not fire, and permanently stop firing, even if
849−-- 'Just b' values would have been encountered later.
850−--
851−-- For the right event, do not fire until the first occurrence where the given
852−-- function returns 'Nothing', and fire that one and all subsequent
853−-- occurrences. Even if the function would have again returned 'Just b', keep
854−-- on firing.
855−takeDropWhileJustE
856− :: forall t m a b
857− . (Reflex t, MonadFix m, MonadHold t m)
858− => (a -> Maybe b)
859− -> Event t a
860− -> m (Event t b, Event t a)
861−takeDropWhileJustE f e = do
862− rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of
863− Nothing -> Left ()
864− Just b -> Right b
865− eFirstBad <- headE eBad
866− e' <- switchHold e (never <$ eFirstBad)
867− eRest <- switchHoldPromptOnly never (e <$ eFirstBad)
868− return (eGood, eRest)
869−
870−-- | Split the supplied 'Event' into two individual 'Event's occurring at the
871−-- same time with the respective values from the tuple.
872−splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
873−splitE e = (fmap fst e, fmap snd e)
874−
875−-- | Print the supplied 'String' and the value of the 'Event' on each
876−-- occurrence. This should /only/ be used for debugging.
877−--
878−-- Note: As with Debug.Trace.trace, the message will only be printed if the
879−-- 'Event' is actually used.
880−traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
881−traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
882−
883−-- | Print the output of the supplied function on each occurrence of the
884−-- 'Event'. This should /only/ be used for debugging.
885−--
886−-- Note: As with Debug.Trace.trace, the message will only be printed if the
887−-- 'Event' is actually used.
888−traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
889−traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
890−
891−instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
892− (<>) = alignWith (mergeThese (<>))
893− sconcat = fmap sconcat . mergeList . toList
894− stimes n = fmap $ stimes n
895−
896−instance (Semigroup a, Reflex t) => Monoid (Event t a) where
897− mempty = never
898− mappend = (<>)
899− mconcat = fmap sconcat . mergeList
900−
901−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
902−-- list occurs. If multiple occur at the same time they are folded from the left
903−-- with the given function.
904−{-# INLINE mergeWith #-}
905−mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
906−mergeWith = mergeWith' id
907−
908−{-# INLINE mergeWith' #-}
909−mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
910−mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)
911− . mergeInt
912− . IntMap.fromDistinctAscList
913− $ zip [0 :: Int ..] es
914−
915−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
916−-- list occurs. If multiple occur at the same time the value is the value of the
917−-- leftmost event.
918−{-# INLINE leftmost #-}
919−leftmost :: Reflex t => [Event t a] -> Event t a
920−leftmost = mergeWith const
921−
922−-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
923−-- list occurs and has a list of the values of all 'Event's occurring at that
924−-- time.
925−mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
926−mergeList [] = never
927−mergeList es = mergeWithFoldCheap' id es
928−
929−unsafeMapIncremental
930− :: (Reflex t, Patch p, Patch p')
931− => (PatchTarget p -> PatchTarget p')
932− -> (p -> p')
933− -> Incremental t p
934− -> Incremental t p'
935−unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
936−
937−-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
938−-- occurs if at least one of them occurs and has a map of values of all 'Event's
939−-- occurring at that time.
940−mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
941−mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
942−
943−-- | Like 'mergeMap' but for 'IntMap'.
944−mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
945−mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap
946−
947−-- | Create a merge whose parents can change over time
948−mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a)
949−mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id)
950−
951−-- | Create a merge whose parents can change over time
952−mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
953−mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)
954−
955−-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
956−mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a)
957−mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id)
958−
959−-- | Split the event into separate events for 'Left' and 'Right' values.
960−fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
961−fanEither e =
962− let justLeft = either Just (const Nothing)
963− justRight = either (const Nothing) Just
964− in (mapMaybe justLeft e, mapMaybe justRight e)
965−
966−-- | Split the event into separate events for 'This' and 'That' values,
967−-- allowing them to fire simultaneously when the input value is 'These'.
968−fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
969−fanThese e =
970− let this (This x) = Just x
971− this (These x _) = Just x
972− this _ = Nothing
973− that (That y) = Just y
974− that (These _ y) = Just y
975− that _ = Nothing
976− in (mapMaybe this e, mapMaybe that e)
977−
978−-- | Split the event into an 'EventSelector' that allows efficient selection of
979−-- the individual 'Event's.
980−fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
981−fanMap = fan . fmap mapToDMap
982−
983−-- | Switches to the new event whenever it receives one. Only the old event is
984−-- considered the moment a new one is switched in; the output event will fire at
985−-- that moment only if the old event does.
986−--
987−-- Because the simultaneous firing case is irrelevant, this function imposes
988−-- laxer "timing requirements" on the overall circuit, avoiding many potential
989−-- cyclic dependency / metastability failures. It's also more performant. Use
990−-- this rather than 'switchHoldPromptly' and 'switchHoldPromptOnly' unless you
991−-- are absolutely sure you need to act on the new event in the coincidental
992−-- case.
993−switchHold :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
994−switchHold ea0 eea = switch <$> hold ea0 eea
995−
996−-- | Switches to the new event whenever it receives one. Whenever a new event is
997−-- provided, if it is firing, its value will be the resulting event's value; if
998−-- it is not firing, but the old one is, the old one's value will be used.
999−--
1000−-- 'switchHold', by always forwarding the old event the moment it is switched
1001−-- out, avoids many potential cyclic dependency problems / metastability
1002−-- problems. It's also more performant. Use it instead unless you are sure you
1003−-- cannot.
1004−switchHoldPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1005−switchHoldPromptly ea0 eea = do
1006− bea <- hold ea0 eea
1007− let eLag = switch bea
1008− eCoincidences = coincidence eea
1009− return $ leftmost [eCoincidences, eLag]
1010−
1011−-- | switches to a new event whenever it receives one. At the moment of
1012−-- switching, the old event will be ignored if it fires, and the new one will be
1013−-- used if it fires; this is the opposite of 'switch', which will use only the
1014−-- old value.
1015−--
1016−-- 'switchHold', by always forwarding the old event the moment it is switched
1017−-- out, avoids many potential cyclic dependency problems / metastability
1018−-- problems. It's also more performant. Use it instead unless you are sure you
1019−-- cannot.
1020−switchHoldPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1021−switchHoldPromptOnly e0 e' = do
1022− eLag <- switch <$> hold e0 e'
1023− return $ coincidence $ leftmost [e', eLag <$ eLag]
1024−
1025−-- | When the given outer event fires, condense the inner events into the contained patch. Non-firing inner events will be replaced with deletions.
1026−coincidencePatchMap :: (Reflex t, Ord k) => Event t (PatchMap k (Event t v)) -> Event t (PatchMap k v)
1027−coincidencePatchMap e = fmapCheap PatchMap $ coincidence $ ffor e $ \(PatchMap m) -> mergeMap $ ffor m $ \case
1028− Nothing -> fmapCheap (const Nothing) e
1029− Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1030−
1031−-- | See 'coincidencePatchMap'
1032−coincidencePatchIntMap :: Reflex t => Event t (PatchIntMap (Event t v)) -> Event t (PatchIntMap v)
1033−coincidencePatchIntMap e = fmapCheap PatchIntMap $ coincidence $ ffor e $ \(PatchIntMap m) -> mergeIntMap $ ffor m $ \case
1034− Nothing -> fmapCheap (const Nothing) e
1035− Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1036−
1037−-- | See 'coincidencePatchMap'
1038−coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v)
1039−coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of
1040− PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->
1041− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1042− PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->
1043− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }
1044− PatchMapWithMove.From_Insert ev -> leftmost
1045− [ fforCheap ev $ \v ->
1046− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }
1047− , fforCheap e $ \_ ->
1048− ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1049− ]
1050−
1051−-- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es
1052−-- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that
1053−-- fires with the patched value.
1054−switchHoldPromptOnlyIncremental
1055− :: forall t m p pt w
1056− . ( Reflex t
1057− , MonadHold t m
1058− , Patch (p (Event t w))
1059− , PatchTarget (p (Event t w)) ~ pt (Event t w)
1060− , Patch (p w)
1061− , PatchTarget (p w) ~ pt w
1062− , Monoid (pt w)
1063− )
1064− => (Incremental t (p (Event t w)) -> Event t (pt w))
1065− -> (Event t (p (Event t w)) -> Event t (p w))
1066− -> pt (Event t w)
1067− -> Event t (p (Event t w))
1068− -> m (Event t (pt w))
1069−switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch e0 e' = do
1070− lag <- mergePatchIncremental <$> holdIncremental e0 e'
1071− pure $ ffor (align lag (coincidencePatch e')) $ \case
1072− This old -> old
1073− That new -> new `applyAlways` mempty
1074− These old new -> new `applyAlways` old
1075−
1076−instance Reflex t => Align (Event t) where
1077− nil = never
1078−#if MIN_VERSION_these(0, 8, 0)
1079−instance Reflex t => Semialign (Event t) where
1080−#endif
1081− align = alignEventWithMaybe Just
1082−
1083−#ifdef MIN_VERSION_semialign
1084−#if MIN_VERSION_semialign(1,1,0)
1085−instance Reflex t => Zip (Event t) where
1086−#endif
1087− zip x y = mapMaybe justThese $ align x y
1088−#endif
1089−
1090−
1091−-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
1092−-- the 'Behavior' is true at the time of occurrence.
1093−gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
1094−gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
1095−
1096−-- | Create a new behavior given a starting behavior and switch to the behavior
1097−-- carried by the event when it fires.
1098−switcher :: (Reflex t, MonadHold t m)
1099− => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
1100−switcher b eb = pull . (sample <=< sample) <$> hold b eb
1101−
1102−instance (Reflex t, IsString a) => IsString (Dynamic t a) where
1103− fromString = pure . fromString
1104−
1105−-- | Combine two 'Dynamic's. The result will change whenever either (or both)
1106−-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
1107−zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
1108−zipDyn = zipDynWith (,)
1109−
1110−-- | Combine two 'Dynamic's with a combining function. The result will change
1111−-- whenever either (or both) input 'Dynamic' changes.
1112−-- More efficient than 'liftA2'.
1113−zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
1114−zipDynWith f da db =
1115− let eab = align (updated da) (updated db)
1116− ec = flip push eab $ \o -> do
1117− (a, b) <- case o of
1118− This a -> do
1119− b <- sample $ current db
1120− return (a, b)
1121− That b -> do
1122− a <- sample $ current da
1123− return (a, b)
1124− These a b -> return (a, b)
1125− return $ Just $ f a b
1126− in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
1127−
1128−instance (Reflex t, Semigroup a) => Semigroup (Dynamic t a) where
1129− (<>) = zipDynWith (<>)
1130− stimes n = fmap $ stimes n
1131−
1132−instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
1133− mconcat = distributeListOverDynWith mconcat
1134− mempty = constDyn mempty
1135− mappend = zipDynWith mappend
1136−
1137−-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1138−-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1139−-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1140−distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
1141−distributeDMapOverDynPure = distributeDMapOverDynPureG coerceDynamic
1142−
1143−-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1144−-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1145−-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1146−distributeDMapOverDynPureG
1147− :: forall t k q v. (Reflex t, GCompare k)
1148− => (forall a. q a -> Dynamic t (v a))
1149− -> DMap k q -> Dynamic t (DMap k v)
1150−distributeDMapOverDynPureG nt dm = case DMap.toList dm of
1151− [] -> constDyn DMap.empty
1152− [k :=> v] -> DMap.singleton k <$> nt v
1153− _ ->
1154− let getInitial = DMap.traverseWithKey (\_ -> sample . current . nt) dm
1155− edmPre = mergeG getCompose $ DMap.map (Compose . updated . nt) dm
1156− result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
1157− olds <- sample $ current result
1158− return $ DMap.unionWithKey (\_ _ new -> new) olds news
1159− in result
1160−
1161−-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
1162−distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
1163−distributeListOverDyn = distributeListOverDynWith id
1164−
1165−-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
1166−distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
1167−distributeListOverDynWith f =
1168− fmap (f . map fromDSum . DMap.toAscList) .
1169− distributeDMapOverDynPure .
1170− DMap.fromDistinctAscList .
1171− zipWith toDSum [0..]
1172− where
1173− toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
1174− toDSum k v = Const2 k :=> v
1175− fromDSum :: DSum (Const2 Int a) Identity -> a
1176− fromDSum (Const2 _ :=> Identity v) = v
1177−
1178−-- | Create a new 'Event' that occurs when the first supplied 'Event' occurs
1179−-- unless the second supplied 'Event' occurs simultaneously.
1180−difference :: Reflex t => Event t a -> Event t b -> Event t a
1181−difference = alignEventWithMaybe $ \case
1182− This a -> Just a
1183− _ -> Nothing
1184−
1185−-- | Zips two values by taking the union of their shapes and combining with the provided function.
1186−-- 'Nothing' values are dropped.
1187−alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c
1188−alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $
1189− merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1190−
1191−-- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that
1192−-- matches the provided key.
1193−filterEventKey
1194− :: forall t m k v a.
1195− ( Reflex t
1196− , MonadFix m
1197− , MonadHold t m
1198− , GEq k
1199− )
1200− => k a
1201− -> Event t (DSum k v)
1202− -> m (Event t (v a))
1203−filterEventKey k kv' = do
1204− let f :: DSum k v -> Maybe (v a)
1205− f (newK :=> newV) = case newK `geq` k of
1206− Just Refl -> Just newV
1207− Nothing -> Nothing
1208− takeWhileJustE f kv'
1209−
1210−-- | "Factor" the input 'DSum' 'Event' to produce an 'Event' which
1211−-- fires when the 'DSum' key changes and contains both the value of the
1212−-- 'DSum' at switchover and an 'Event' of values produced by subsequent
1213−-- firings of the input 'Event' that do not change the 'DSum' key.
1214−factorEvent
1215− :: forall t m k v a.
1216− ( Reflex t
1217− , MonadFix m
1218− , MonadHold t m
1219− , GEq k
1220− )
1221− => k a
1222− -> Event t (DSum k v)
1223− -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v))))
1224−factorEvent k0 kv' = do
1225− key :: Behavior t (Some k) <- hold (Some k0) $ fmapCheap (\(k :=> _) -> Some k) kv'
1226− let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case
1227− Some oldKey -> case newKey `geq` oldKey of
1228− Just Refl -> return Nothing
1229− Nothing -> do
1230− newInner <- filterEventKey newKey kv'
1231− return $ Just $ newKey :=> Pair newVal (Compose newInner)
1232− eInitial <- filterEventKey k0 kv'
1233− return (eInitial, update)
1234−
1235−--------------------------------------------------------------------------------
1236−-- Accumulator
1237−--------------------------------------------------------------------------------
1238−
1239−-- | An 'Accumulator' type can be built by accumulating occurrences of an
1240−-- 'Event'.
1241−#if __GLASGOW_HASKELL__ < 802
1242−{-# WARNING accum "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1243−{-# WARNING accumM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1244−{-# WARNING accumMaybe "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1245−{-# WARNING accumMaybeM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1246−#endif
1247−class Reflex t => Accumulator t f | f -> t where
1248− accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
1249− accum f = accumMaybe $ \v o -> Just $ f v o
1250− accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
1251− accumM f = accumMaybeM $ \v o -> Just <$> f v o
1252− accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
1253− accumMaybe f = accumMaybeM $ \v o -> return $ f v o
1254− accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
1255− mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
1256− mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
1257− mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
1258− mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
1259− mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1260− mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
1261− mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1262−
1263−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1264−-- with the provided function. See 'foldDyn'.
1265−accumDyn
1266− :: (Reflex t, MonadHold t m, MonadFix m)
1267− => (a -> b -> a)
1268− -> a
1269− -> Event t b
1270− -> m (Dynamic t a)
1271−accumDyn f = accumMaybeDyn $ \v o -> Just $ f v o
1272−
1273−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1274−-- with the provided 'PushM' action.
1275−accumMDyn
1276− :: (Reflex t, MonadHold t m, MonadFix m)
1277− => (a -> b -> PushM t a)
1278− -> a
1279− -> Event t b
1280− -> m (Dynamic t a)
1281−accumMDyn f = accumMaybeMDyn $ \v o -> Just <$> f v o
1282−
1283−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1284−-- with the provided function, discarding 'Nothing' results.
1285−accumMaybeDyn
1286− :: (Reflex t, MonadHold t m, MonadFix m)
1287− => (a -> b -> Maybe a)
1288− -> a
1289− -> Event t b
1290− -> m (Dynamic t a)
1291−accumMaybeDyn f = accumMaybeMDyn $ \v o -> return $ f v o
1292−
1293−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1294−-- with the provided 'PushM' action, discarding 'Nothing' results.
1295−accumMaybeMDyn
1296− :: (Reflex t, MonadHold t m, MonadFix m)
1297− => (a -> b -> PushM t (Maybe a))
1298− -> a
1299− -> Event t b
1300− -> m (Dynamic t a)
1301−accumMaybeMDyn f z e = do
1302− rec let e' = flip push e $ \o -> do
1303− v <- sample $ current d'
1304− f v o
1305− d' <- holdDyn z e'
1306− return d'
1307−
1308−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1309−-- with a function that both accumulates and produces a value to fire
1310−-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1311−mapAccumDyn
1312− :: (Reflex t, MonadHold t m, MonadFix m)
1313− => (a -> b -> (a, c))
1314− -> a
1315− -> Event t b
1316− -> m (Dynamic t a, Event t c)
1317−mapAccumDyn f = mapAccumMaybeDyn $ \v o -> bimap Just Just $ f v o
1318−
1319−-- | Similar to 'mapAccumDyn' except that the combining function is a
1320−-- 'PushM' action.
1321−mapAccumMDyn
1322− :: (Reflex t, MonadHold t m, MonadFix m)
1323− => (a -> b -> PushM t (a, c))
1324− -> a
1325− -> Event t b
1326− -> m (Dynamic t a, Event t c)
1327−mapAccumMDyn f = mapAccumMaybeMDyn $ \v o -> bimap Just Just <$> f v o
1328−
1329−-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event' with
1330−-- a function that both optionally accumulates and optionally produces
1331−-- a value to fire as a separate output 'Event'.
1332−-- Note that because 'Nothing's are discarded in both cases, the output
1333−-- 'Event' may fire even though the output 'Dynamic' has not changed, and
1334−-- the output 'Dynamic' may update even when the output 'Event' is not firing.
1335−mapAccumMaybeDyn
1336− :: (Reflex t, MonadHold t m, MonadFix m)
1337− => (a -> b -> (Maybe a, Maybe c))
1338− -> a
1339− -> Event t b
1340− -> m (Dynamic t a, Event t c)
1341−mapAccumMaybeDyn f = mapAccumMaybeMDyn $ \v o -> return $ f v o
1342−
1343−-- | Like 'mapAccumMaybeDyn' except that the combining function is a
1344−-- 'PushM' action.
1345−mapAccumMaybeMDyn
1346− :: (Reflex t, MonadHold t m, MonadFix m)
1347− => (a -> b -> PushM t (Maybe a, Maybe c))
1348− -> a
1349− -> Event t b
1350− -> m (Dynamic t a, Event t c)
1351−mapAccumMaybeMDyn f z e = do
1352− rec let e' = flip push e $ \o -> do
1353− v <- sample $ current d'
1354− result <- f v o
1355− return $ case result of
1356− (Nothing, Nothing) -> Nothing
1357− _ -> Just result
1358− d' <- holdDyn z $ mapMaybe fst e'
1359− return (d', mapMaybe snd e')
1360−
1361−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1362−-- with the provided function.
1363−{-# INLINE accumB #-}
1364−accumB
1365− :: (Reflex t, MonadHold t m, MonadFix m)
1366− => (a -> b -> a)
1367− -> a
1368− -> Event t b
1369− -> m (Behavior t a)
1370−accumB f = accumMaybeB $ \v o -> Just $ f v o
1371−
1372−-- | Like 'accumB' except that the combining function is a 'PushM' action.
1373−{-# INLINE accumMB #-}
1374−accumMB
1375− :: (Reflex t, MonadHold t m, MonadFix m)
1376− => (a -> b -> PushM t a)
1377− -> a
1378− -> Event t b
1379− -> m (Behavior t a)
1380−accumMB f = accumMaybeMB $ \v o -> Just <$> f v o
1381−
1382−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1383−-- with the provided function, discarding 'Nothing' results.
1384−{-# INLINE accumMaybeB #-}
1385−accumMaybeB
1386− :: (Reflex t, MonadHold t m, MonadFix m)
1387− => (a -> b -> Maybe a)
1388− -> a
1389− -> Event t b
1390− -> m (Behavior t a)
1391−accumMaybeB f = accumMaybeMB $ \v o -> return $ f v o
1392−
1393−-- | Like 'accumMaybeB' except that the combining function is a 'PushM' action.
1394−{-# INLINE accumMaybeMB #-}
1395−accumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (Behavior t a)
1396−accumMaybeMB f z e = do
1397− rec let e' = flip push e $ \o -> do
1398− v <- sample d'
1399− f v o
1400− d' <- hold z e'
1401− return d'
1402−
1403−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1404−-- with a function that both accumulates and produces a value to fire
1405−-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1406−{-# INLINE mapAccumB #-}
1407−mapAccumB
1408− :: (Reflex t, MonadHold t m, MonadFix m)
1409− => (a -> b -> (a, c))
1410− -> a
1411− -> Event t b
1412− -> m (Behavior t a, Event t c)
1413−mapAccumB f = mapAccumMaybeB $ \v o -> bimap Just Just $ f v o
1414−
1415−-- | Like 'mapAccumB' except that the combining function is a 'PushM' action.
1416−{-# INLINE mapAccumMB #-}
1417−mapAccumMB
1418− :: (Reflex t, MonadHold t m, MonadFix m)
1419− => (a -> b -> PushM t (a, c))
1420− -> a
1421− -> Event t b
1422− -> m (Behavior t a, Event t c)
1423−mapAccumMB f = mapAccumMaybeMB $ \v o -> bimap Just Just <$> f v o
1424−
1425−-- | Accumulate a 'Behavior' by folding occurrences of an 'Event' with
1426−-- a function that both optionally accumulates and optionally produces
1427−-- a value to fire as a separate output 'Event'. 'Nothing's are discarded.
1428−{-# INLINE mapAccumMaybeB #-}
1429−mapAccumMaybeB
1430− :: (Reflex t, MonadHold t m, MonadFix m)
1431− => (a -> b -> (Maybe a, Maybe c))
1432− -> a
1433− -> Event t b
1434− -> m (Behavior t a, Event t c)
1435−mapAccumMaybeB f = mapAccumMaybeMB $ \v o -> return $ f v o
1436−
1437−-- | Like 'mapAccumMaybeB' except that the combining function is a 'PushM' action.
1438−{-# INLINE mapAccumMaybeMB #-}
1439−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)
1440−mapAccumMaybeMB f z e = do
1441− rec let e' = flip push e $ \o -> do
1442− v <- sample d'
1443− result <- f v o
1444− return $ case result of
1445− (Nothing, Nothing) -> Nothing
1446− _ -> Just result
1447− d' <- hold z $ mapMaybe fst e'
1448− return (d', mapMaybe snd e')
1449−
1450−-- | Accumulate occurrences of an 'Event', producing an output occurrence each
1451−-- time. Discard the underlying 'Accumulator'.
1452−{-# INLINE mapAccum_ #-}
1453−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)
1454−mapAccum_ f z e = do
1455− (_, result) <- mapAccumB f z e
1456− return result
1457−
1458−-- | Accumulate occurrences of an 'Event', possibly producing an output
1459−-- occurrence each time. Discard the underlying 'Accumulator'.
1460−{-# INLINE mapAccumMaybe_ #-}
1461−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)
1462−mapAccumMaybe_ f z e = do
1463− (_, result) <- mapAccumMaybeB f z e
1464− return result
1465−
1466−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
1467−-- an output occurrence each time. Discard the underlying 'Accumulator'.
1468−{-# INLINE mapAccumM_ #-}
1469−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)
1470−mapAccumM_ f z e = do
1471− (_, result) <- mapAccumMB f z e
1472− return result
1473−
1474−-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
1475−-- producing an output occurrence each time. Discard the underlying
1476−-- 'Accumulator'.
1477−{-# INLINE mapAccumMaybeM_ #-}
1478−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)
1479−mapAccumMaybeM_ f z e = do
1480− (_, result) <- mapAccumMaybeMB f z e
1481− return result
1482−
1483−instance Reflex t => Accumulator t (Dynamic t) where
1484− accumMaybeM = accumMaybeMDyn
1485− mapAccumMaybeM = mapAccumMaybeMDyn
1486−
1487−instance Reflex t => Accumulator t (Behavior t) where
1488− accumMaybeM = accumMaybeMB
1489− mapAccumMaybeM = mapAccumMaybeMB
1490−
1491−instance Reflex t => Accumulator t (Event t) where
1492− accumMaybeM f z e = updated <$> accumMaybeM f z e
1493− mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
1494−
1495−-- | Create a new 'Event' by combining each occurrence with the next value of the
1496−-- list using the supplied function. If the list runs out of items, all
1497−-- subsequent 'Event' occurrences will be ignored.
1498−zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
1499−zipListWithEvent f l e = do
1500− let f' a b = case a of
1501− h:t -> (Just t, Just $ f h b)
1502− _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
1503− mapAccumMaybe_ f' l e
1504−
1505−-- | Assign a number to each occurrence of the given 'Event', starting from 0
1506−{-# INLINE numberOccurrences #-}
1507−numberOccurrences :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Event t (b, a))
1508−numberOccurrences = numberOccurrencesFrom 0
1509−
1510−-- | Assign a number to each occurrence of the given 'Event'
1511−{-# INLINE numberOccurrencesFrom #-}
1512−numberOccurrencesFrom :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t (b, a))
1513−numberOccurrencesFrom = mapAccum_ (\n a -> let !next = n + 1 in (next, (n, a)))
1514−
1515−-- | Assign a number to each occurrence of the given 'Event'; discard the occurrences' values
1516−{-# INLINE numberOccurrencesFrom_ #-}
1517−numberOccurrencesFrom_ :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t b)
1518−numberOccurrencesFrom_ = mapAccum_ (\n _ -> let !next = n + 1 in (next, n))
1519−
1520−-- | This is used to sample the value of a 'Behavior' using an 'Event'.
1521−--
1522−-- The '<@>' operator is intended to be used in conjunction with
1523−-- the 'Applicative' instance for 'Behavior'.
1524−--
1525−-- This is useful when we want to combine the values of one 'Event' and
1526−-- the value of several 'Behavior's at the time the 'Event' is firing.
1527−--
1528−-- If we have:
1529−--
1530−-- > f :: a -> b -> c -> d
1531−-- > b1 :: Behavior t a
1532−-- > b2 :: Behavior t b
1533−-- > e :: Event t c
1534−--
1535−-- then we can do:
1536−--
1537−-- > f <$> b1 <*> b2 <@> e :: Event t d
1538−--
1539−-- in order to apply the function 'f' to the relevant values.
1540−--
1541−-- The alternative would be something like:
1542−--
1543−-- > attachWith (\(x1, x2) y -> f x1 x2 y) ((,) <$> b1 <*> b2) e :: Event t d
1544−--
1545−-- or a variation involing a custom data type to hold the combination of
1546−-- 'Behavior's even when that combination might only ever be used by 'f'.
1547−--
1548−-- A more suggestive example might be:
1549−--
1550−-- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)
1551−--
1552−(<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b
1553−(<@>) b = push $ \x -> do
1554− f <- sample b
1555− return . Just . f $ x
1556−infixl 4 <@>
1557−
1558−-- | An version of '<@>' that does not use the value of the 'Event'.
1559−--
1560−-- Alternatively, it is 'tag' in operator form.
1561−--
1562−-- This is useful when we want to combine the values of several
1563−-- 'Behavior's at particular points in time using an 'Applicative'
1564−-- style syntax.
1565−--
1566−-- If we have:
1567−--
1568−-- > g :: a -> b -> d
1569−-- > b1 :: Behavior t a
1570−-- > b2 :: Behavior t b
1571−-- > e :: Event t c
1572−--
1573−-- where 'e' is firing at the points in time of interest.
1574−--
1575−-- Then we can use '<@':
1576−--
1577−-- > g <$> b1 <*> b2 <@ e :: Event t d
1578−--
1579−-- to combine the values of 'b1' and 'b2' at each of those points of time,
1580−-- with the function 'g' being used to combine the values.
1581−--
1582−-- This is the same as '<@>' except that the 'Event' is being used only
1583−-- to act as a trigger.
1584−(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b
1585−(<@) = tag
1586−infixl 4 <@
1587−
1588−------------------
1589−-- Cheap Functions
1590−------------------
1591−
1592−-- | A "cheap" version of 'pushAlways'. See the performance note on 'pushCheap'.
1593−{-# INLINE pushAlwaysCheap #-}
1594−pushAlwaysCheap :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
1595−pushAlwaysCheap f = pushCheap (fmap Just . f)
1596−
1597−-- | A "cheap" version of 'mapMaybe'. See the performance note on 'pushCheap'.
1598−{-# INLINE mapMaybeCheap #-}
1599−mapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1600−mapMaybeCheap f = pushCheap $ return . f
1601−
1602−-- | An alias for 'mapMaybeCheap'
1603−{-# INLINE fmapMaybeCheap #-}
1604−fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1605−fmapMaybeCheap = mapMaybeCheap
1606−
1607−
1608−-- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'.
1609−{-# INLINE fforMaybeCheap #-}
1610−fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b
1611−fforMaybeCheap = flip mapMaybeCheap
1612−
1613−-- | A "cheap" version of 'ffor'. See the performance note on 'pushCheap'.
1614−{-# INLINE fforCheap #-}
1615−fforCheap :: Reflex t => Event t a -> (a -> b) -> Event t b
1616−fforCheap = flip fmapCheap
1617−
1618−-- | A "cheap" version of 'fmap'. See the performance note on 'pushCheap'.
1619−{-# INLINE fmapCheap #-}
1620−fmapCheap :: Reflex t => (a -> b) -> Event t a -> Event t b
1621−fmapCheap f = pushCheap $ return . Just . f
1622−
1623−-- | A "cheap" version of 'tag'. See the performance note on 'pushCheap'.
1624−{-# INLINE tagCheap #-}
1625−tagCheap :: Reflex t => Behavior t b -> Event t a -> Event t b
1626−tagCheap b = pushAlwaysCheap $ \_ -> sample b
1627−
1628−-- | Merge a collection of events; the resulting 'Event' will only occur if at
1629−-- least one input event is occurring, and will contain all of the input keys
1630−-- that are occurring simultaneously
1631−merge :: (Reflex t, GCompare k) => DMap k (Event t) -> Event t (DMap k Identity)
1632−merge = mergeG coerceEvent
1633−{-# INLINE merge #-}
1634−
1635−-- | Create a merge whose parents can change over time
1636−mergeIncremental :: (Reflex t, GCompare k)
1637− => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
1638−mergeIncremental = mergeIncrementalG coerceEvent
1639−
1640−-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
1641−mergeIncrementalWithMove :: (Reflex t, GCompare k)
1642− => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity)
1643−mergeIncrementalWithMove = mergeIncrementalWithMoveG coerceEvent
1644−
1645−-- | A "cheap" version of 'mergeWithCheap'. See the performance note on 'pushCheap'.
1646−{-# INLINE mergeWithCheap #-}
1647−mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
1648−mergeWithCheap = mergeWithCheap' id
1649−
1650−-- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'.
1651−{-# INLINE mergeWithCheap' #-}
1652−mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
1653−mergeWithCheap' f g = mergeWithFoldCheap' $ foldl1 g . fmap f
1654−
1655−-- | A "cheap" version of 'mergeWithFoldCheap''. See the performance note on 'pushCheap'.
1656−{-# INLINE mergeWithFoldCheap' #-}
1657−mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b
1658−mergeWithFoldCheap' f es =
1659− fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)
1660− . mergeInt
1661− . IntMap.fromDistinctAscList
1662− $ zip [0 :: Int ..] es
1663−
1664−--------------------------------------------------------------------------------
1665−-- Deprecated functions
1666−--------------------------------------------------------------------------------
1667−
1668−{-# 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'. " #-}
1669−-- | See 'switchHoldPromptly'
1670−switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1671−switchPromptly = switchHoldPromptly
1672−{-# 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'. " #-}
1673−-- | See 'switchHoldPromptOnly'
1674−switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1675−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−29
@@ -1,29 +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
29−
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 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 from reverseMapping
159− in Just (to, NodeInfo (From_Move from) $ Just movingTo)
160−
161−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
162−-- will produce a 'Map' with the same values as the second 'Map' but with the
163−-- values sorted with the given ordering function.
164−patchThatChangesAndSortsMapWith :: forall k v. (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
165−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
166− where newList = Map.toList newByIndexUnsorted
167− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
168−
169−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
170−-- will produce the second 'Map'.
171−patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
172−patchThatChangesMap oldByIndex newByIndex = patch
173− where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
174− (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
175− let f k v = do
176− remainingValues <- get
177− let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
178− then Map.delete v remainingValues
179− else Map.insert v remainingKeys remainingValues
180− case Map.lookup v remainingValues of
181− Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
182− Just fromKs ->
183− if k `Set.member` fromKs
184− then do
185− putRemainingKeys $ Set.delete k fromKs
186− return $ NodeInfo (From_Move k) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
187− else do
188− (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
189− putRemainingKeys remainingKeys
190− return $ NodeInfo (From_Move fromK) $ Just undefined
191− Map.traverseWithKey f newByIndex
192− unusedOldKeys = fold unusedValuesByValue
193− pointlessMove k = \case
194− From_Move k' | k == k' -> True
195− _ -> False
196− keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
197− then Just undefined
198− else Nothing
199− patch = unsafePatchMapWithMove $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
200−
201−-- | Change the 'From' value of a 'NodeInfo'
202−nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
203−nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
204−
205−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
206−-- 'Applicative', 'Monad', etc.) action to get the new value
207−nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
208−nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
209−
210−-- | Set the 'To' field of a 'NodeInfo'
211−nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
212−nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
213−
214−-- |Helper data structure used for composing patches using the monoid instance.
215−data Fixup k v
216− = Fixup_Delete
217− | Fixup_Update (These (From k v) (To k))
218−
219−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
220−instance Ord k => Semigroup (PatchMapWithMove k v) where
221− PatchMapWithMove ma <> PatchMapWithMove mb = PatchMapWithMove m
222− where
223− connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
224− h :: (k, (Maybe k, From k v)) -> [(k, Fixup k v)]
225− h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
226− (Just toAfter, From_Move fromBefore)
227− | fromBefore == toAfter
228− -> [(toAfter, Fixup_Delete)]
229− | otherwise
230− -> [ (toAfter, Fixup_Update (This editBefore))
231− , (fromBefore, Fixup_Update (That mToAfter))
232− ]
233− (Nothing, From_Move fromBefore) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
234− (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
235− (Nothing, _) -> []
236− mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
237− mergeFixups _ (Fixup_Update a) (Fixup_Update b)
238− | This x <- a, That y <- b
239− = Fixup_Update $ These x y
240− | That y <- a, This x <- b
241− = Fixup_Update $ These x y
242− mergeFixups _ _ _ = error "PatchMapWithMove: incompatible fixups"
243− fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
244− combineNodeInfos _ nia nib = NodeInfo
245− { _nodeInfo_from = _nodeInfo_from nia
246− , _nodeInfo_to = _nodeInfo_to nib
247− }
248− applyFixup _ ni = \case
249− Fixup_Delete -> Nothing
250− Fixup_Update u -> Just $ NodeInfo
251− { _nodeInfo_from = fromMaybe (_nodeInfo_from ni) $ getHere u
252− , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
253− }
254− m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
255− getHere :: These a b -> Maybe a
256− getHere = \case
257− This a -> Just a
258− These a _ -> Just a
259− That _ -> Nothing
260− getThere :: These a b -> Maybe b
261− getThere = \case
262− This _ -> Nothing
263− These _ b -> Just b
264− That b -> Just b
265−
266−--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
267−-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
268−instance Ord k => Monoid (PatchMapWithMove k v) where
269− mempty = PatchMapWithMove mempty
270− mappend = (<>)
src/Reflex/PerformEvent/Base.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 (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−2707
@@ -1,2707 +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−
107−#ifdef DEBUG_TRACE_EVENTS
108−import qualified Data.ByteString.Char8 as BS8
109−import System.IO (stderr)
110−#endif
111−
112−#ifdef DEBUG_TRACE_EVENTS
113−
114−withStackOneLine :: (BS8.ByteString -> a) -> a
115−withStackOneLine expr = unsafePerformIO $ do
116− stack <- currentCallStack
117− return (expr (BS8.pack (unwords (reverse stack))))
118−
119−#endif
120−
121−debugPropagate :: Bool
122−
123−debugInvalidateHeight :: Bool
124−
125−debugInvalidate :: Bool
126−
127−#ifdef DEBUG
128−
129−#define DEBUG_NODEIDS
130−
131−debugPropagate = True
132−
133−debugInvalidateHeight = False
134−
135−debugInvalidate = True
136−
137−class HasNodeId a where
138− getNodeId :: a -> Int
139−
140−instance HasNodeId (Hold x p a) where
141− getNodeId = holdNodeId
142−
143−instance HasNodeId (PushSubscribed x a b) where
144− getNodeId = pushSubscribedNodeId
145−
146−instance HasNodeId (SwitchSubscribed x a) where
147− getNodeId = switchSubscribedNodeId
148−
149−instance HasNodeId (FanSubscribed x a) where
150− getNodeId = fanSubscribedNodeId
151−
152−instance HasNodeId (CoincidenceSubscribed x a) where
153− getNodeId = coincidenceSubscribedNodeId
154−
155−instance HasNodeId (RootSubscribed x a) where
156− getNodeId = rootSubscribedNodeId
157−
158−instance HasNodeId (Pull x a) where
159− getNodeId = pullNodeId
160−
161−{-# INLINE showNodeId #-}
162−showNodeId :: HasNodeId a => a -> String
163−showNodeId = ("#"<>) . show . getNodeId
164−
165−showSubscriberType :: Subscriber x a -> String
166−showSubscriberType = \case
167− SubscriberPush _ _ -> "SubscriberPush"
168− SubscriberMerge _ _ -> "SubscriberMerge"
169− SubscriberFan _ -> "SubscriberFan"
170− SubscriberMergeChange _ -> "SubscriberMergeChange"
171− SubscriberHold _ -> "SubscriberHold"
172− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
173− SubscriberSwitch _ -> "SubscriberSwitch"
174− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
175− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
176− SubscriberHandle -> "SubscriberHandle"
177−
178−showEventType :: Event x a -> String
179−showEventType = \case
180− EventRoot _ _ -> "EventRoot"
181− EventNever -> "EventNever"
182− EventPush _ -> "EventPush"
183− EventMerge _ -> "EventMerge"
184− EventFan _ _ -> "EventFan"
185− EventSwitch _ -> "EventSwitch"
186− EventCoincidence _ -> "EventCoincidence"
187− EventHold _ -> "EventHold"
188− EventDyn _ -> "EventDyn"
189− EventHoldIdentity _ -> "EventHoldIdentity"
190− EventDynIdentity _ -> "EventDynIdentity"
191−
192−#else
193−
194−debugPropagate = False
195−
196−debugInvalidateHeight = False
197−
198−debugInvalidate = False
199−
200−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
201−{-# INLINE showNodeId #-}
202−showNodeId :: a -> String
203−showNodeId _ = ""
204−
205−#endif
206−
207−#ifdef DEBUG_NODEIDS
208−{-# NOINLINE nextNodeIdRef #-}
209−nextNodeIdRef :: IORef Int
210−nextNodeIdRef = unsafePerformIO $ newIORef 1
211−
212−newNodeId :: IO Int
213−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
214−#endif
215−
216−--------------------------------------------------------------------------------
217−-- EventSubscription
218−--------------------------------------------------------------------------------
219−
220−--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
221−-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
222−data EventSubscription x = EventSubscription
223− { _eventSubscription_unsubscribe :: !(IO ())
224− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
225− }
226−
227−unsubscribe :: EventSubscription x -> IO ()
228−unsubscribe (EventSubscription u _) = u
229−
230−--------------------------------------------------------------------------------
231−-- Event
232−--------------------------------------------------------------------------------
233−
234−newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
235−
236−{-# INLINE subscribeAndRead #-}
237−subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
238−subscribeAndRead = unEvent
239−
240−{-# RULES
241−"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
242−"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
243−"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
244− #-}
245−
246−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
247−-- caching; if the computation function is very cheap, this is (much) more
248−-- efficient than 'push'
249−{-# INLINE [1] pushCheap #-}
250−pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
251−pushCheap !f e = Event $ \sub -> do
252− (subscription, occ) <- subscribeAndRead e $ sub
253− { subscriberPropagate = \a -> do
254− mb <- f a
255− mapM_ (subscriberPropagate sub) mb
256− }
257− occ' <- join <$> mapM f occ
258− return (subscription, occ')
259−
260−-- | A subscriber that never triggers other 'Event's
261−{-# INLINE terminalSubscriber #-}
262−terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
263−terminalSubscriber p = Subscriber
264− { subscriberPropagate = p
265− , subscriberInvalidateHeight = \_ -> return ()
266− , subscriberRecalculateHeight = \_ -> return ()
267− }
268−
269−-- | Subscribe to an Event only for the duration of one occurrence
270−{-# INLINE subscribeAndReadHead #-}
271−subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
272−subscribeAndReadHead e sub = do
273− subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
274− (subscription, occ) <- subscribeAndRead e $ sub
275− { subscriberPropagate = \a -> do
276− liftIO $ unsubscribe =<< readIORef subscriptionRef
277− subscriberPropagate sub a
278− }
279− liftIO $ case occ of
280− Nothing -> writeIORef subscriptionRef $! subscription
281− Just _ -> unsubscribe subscription
282− return (subscription, occ)
283−
284−--TODO: Make this lazy in its input event
285−headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
286−headE originalE = do
287− parent <- liftIO $ newIORef $ Just originalE
288− defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
289− let clearParent = liftIO $ writeIORef parent Nothing
290− (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
291− when (isJust occ) clearParent
292− return $ Event $ \sub -> do
293− liftIO (readIORef parent) >>= \case
294− Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
295− Just e -> subscribeAndReadHead e sub
296−
297−data CacheSubscribed x a
298− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
299− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
300− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
301− }
302−
303−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
304−-- repeatedly
305−--
306−--TODO: Try a caching strategy where we subscribe directly to the parent when
307−--there's only one subscriber, and then build our own FastWeakBag only when a second
308−--subscriber joins
309−{-# NOINLINE [0] cacheEvent #-}
310−cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
311−cacheEvent e =
312−#ifdef DEBUG_TRACE_EVENTS
313− withStackOneLine $ \callSite -> Event $
314−#else
315− Event $
316−#endif
317− unsafePerformIO $ do
318− mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
319− <- newIORef emptyFastWeak
320− pure $ \sub -> {-# SCC "cacheEvent" #-} do
321−#ifdef DEBUG_TRACE_EVENTS
322− unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
323−#endif
324− subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
325− Just subscribedTicket -> return subscribedTicket
326− Nothing -> do
327− subscribers <- liftIO FastWeakBag.empty
328− occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
329− (parentSub, occ) <- subscribeAndRead e $ Subscriber
330− { subscriberPropagate = \a -> do
331− liftIO $ writeIORef occRef $ Just a
332− scheduleClear occRef
333− propagateFast a subscribers
334− , subscriberInvalidateHeight = \old -> do
335− FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
336− , subscriberRecalculateHeight = \new -> do
337− FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
338− }
339− when (isJust occ) $ do
340− liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
341− scheduleClear occRef
342− let !subscribed = CacheSubscribed
343− { _cacheSubscribed_subscribers = subscribers
344− , _cacheSubscribed_parent = parentSub
345− , _cacheSubscribed_occurrence = occRef
346− }
347− subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
348− liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
349− return subscribedTicket
350− liftIO $ do
351− subscribed <- getFastWeakTicketValue subscribedTicket
352− ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
353− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
354− let es = EventSubscription
355− { _eventSubscription_unsubscribe = do
356− FastWeakBag.remove ticket
357− isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
358− when isEmpty $ do
359− writeIORef mSubscribedRef emptyFastWeak
360− unsubscribe $ _cacheSubscribed_parent subscribed
361− touch ticket
362− touch subscribedTicket
363− , _eventSubscription_subscribed = EventSubscribed
364− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
365− , eventSubscribedRetained = toAny subscribedTicket
366− }
367− }
368− return (es, occ)
369−
370−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
371−subscribe e s = fst <$> subscribeAndRead e s
372−
373−{-# INLINE wrap #-}
374−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
375−wrap tag getSpecificSubscribed sub = do
376− (sln, subd, occ) <- getSpecificSubscribed sub
377− let es = tag subd
378− return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
379−
380−eventRoot :: GCompare k => k a -> Root x k -> Event x a
381−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
382−
383−eventNever :: Event x a
384−eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
385−
386−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
387−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
388−
389−eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
390−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
391−
392−eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
393−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
394−
395−eventHold :: Hold x p -> Event x p
396−eventHold !h = Event $ subscribeHoldEvent h
397−
398−eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
399−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
400−
401−{-# INLINE subscribeCoincidenceInner #-}
402−subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
403−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
404− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
405− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
406− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
407− let height = max innerHeight outerHeight
408− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
409− return (innerOcc, height, innerSubd)
410−
411−--------------------------------------------------------------------------------
412−-- Subscriber
413−--------------------------------------------------------------------------------
414−
415−data Subscriber x a = Subscriber
416− { subscriberPropagate :: !(a -> EventM x ())
417− , subscriberInvalidateHeight :: !(Height -> IO ())
418− , subscriberRecalculateHeight :: !(Height -> IO ())
419− }
420−
421−--TODO: Move this comment to WeakBag
422−-- These function are constructor functions that are marked NOINLINE so they are
423−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
424−-- so any weak references that are attached to the constructors will have their
425−-- finalizer run. Using the opaque constructor, does not see the
426−-- constructor application, so it behaves like an IORef and cannot be fused away.
427−--
428−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
429−-- the weak pointer to it in some cases.
430−
431−newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
432−newSubscriberHold h = return $ Subscriber
433− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
434− , subscriberInvalidateHeight = \_ -> return ()
435− , subscriberRecalculateHeight = \_ -> return ()
436− }
437−
438−newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
439−newSubscriberFan subscribed = return $ Subscriber
440− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
441− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
442− tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
443− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
444− scheduleClear $ fanSubscribedOccurrence subscribed
445− let f _ (Pair v subsubs) = do
446− propagate v $ _fanSubscribedChildren_list subsubs
447− return $ Constant ()
448− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
449− return ()
450− , subscriberInvalidateHeight = \old -> do
451− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
452− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
453− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
454− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
455− , subscriberRecalculateHeight = \new -> do
456− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
457− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
458− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
459− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
460− }
461−
462−newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
463−newSubscriberSwitch subscribed = return $ Subscriber
464− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
465− tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
466− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
467− scheduleClear $ switchSubscribedOccurrence subscribed
468− propagate a $ switchSubscribedSubscribers subscribed
469− , subscriberInvalidateHeight = \_ -> do
470− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
471− oldHeight <- readIORef $ switchSubscribedHeight subscribed
472− when (oldHeight /= invalidHeight) $ do
473− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
474− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
475− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
476− , subscriberRecalculateHeight = \new -> do
477− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
478− updateSwitchHeight new subscribed
479− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
480− }
481−
482−newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
483−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
484− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
485− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
486− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
487− tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
488− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
489− tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
490− tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
491− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
492− scheduleClear $ coincidenceSubscribedInnerParent subscribed
493− case occ of
494− Nothing -> do
495− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
496− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
497− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
498− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
499− Just o -> do -- Since it's already firing, no need to adjust height
500− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
501− scheduleClear $ coincidenceSubscribedOccurrence subscribed
502− propagate o $ coincidenceSubscribedSubscribers subscribed
503− , subscriberInvalidateHeight = \_ -> do
504− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
505− invalidateCoincidenceHeight subscribed
506− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
507− , subscriberRecalculateHeight = \_ -> do
508− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
509− recalculateCoincidenceHeight subscribed
510− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
511− }
512−
513−newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
514−newSubscriberCoincidenceInner subscribed = return $ Subscriber
515− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
516− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
517− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
518− case occ of
519− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
520− Nothing -> do
521− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
522− scheduleClear $ coincidenceSubscribedOccurrence subscribed
523− propagate a $ coincidenceSubscribedSubscribers subscribed
524− , subscriberInvalidateHeight = \_ -> do
525− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
526− invalidateCoincidenceHeight subscribed
527− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
528− , subscriberRecalculateHeight = \_ -> do
529− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
530− recalculateCoincidenceHeight subscribed
531− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
532− }
533−
534−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
535−invalidateSubscriberHeight = flip subscriberInvalidateHeight
536−
537−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
538−recalculateSubscriberHeight = flip subscriberRecalculateHeight
539−
540−-- | Propagate everything at the current height
541−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
542−propagate a subscribers = withIncreasedDepth $ do
543− -- 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
544− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
545− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
546−
547−-- | Propagate everything at the current height
548−propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
549−propagateFast a subscribers = withIncreasedDepth $ do
550− -- 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
551− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
552− FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
553−
554−--------------------------------------------------------------------------------
555−-- EventSubscribed
556−--------------------------------------------------------------------------------
557−
558−toAny :: a -> Any
559−toAny = unsafeCoerce
560−
561−-- Why do we use Any here, instead of just giving eventSubscribedRetained an
562−-- existential type? Sadly, GHC does not currently know how to unbox types
563−-- with existentially quantified fields. So instead we just coerce values
564−-- to type Any on the way in. Since we never coerce them back, this is
565−-- perfectly safe.
566−data EventSubscribed x = EventSubscribed
567− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
568− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
569−#ifdef DEBUG_CYCLES
570− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
571− , eventSubscribedHasOwnHeightRef :: !Bool
572− , eventSubscribedWhoCreated :: !(IO [String])
573−#endif
574− }
575−
576−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
577−eventSubscribedRoot !r = EventSubscribed
578− { eventSubscribedHeightRef = zeroRef
579− , eventSubscribedRetained = toAny r
580−#ifdef DEBUG_CYCLES
581− , eventSubscribedGetParents = return []
582− , eventSubscribedHasOwnHeightRef = False
583− , eventSubscribedWhoCreated = return ["root"]
584−#endif
585− }
586−
587−eventSubscribedNever :: EventSubscribed x
588−eventSubscribedNever = EventSubscribed
589− { eventSubscribedHeightRef = zeroRef
590− , eventSubscribedRetained = toAny ()
591−#ifdef DEBUG_CYCLES
592− , eventSubscribedGetParents = return []
593− , eventSubscribedHasOwnHeightRef = False
594− , eventSubscribedWhoCreated = return ["never"]
595−#endif
596− }
597−
598−eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
599−eventSubscribedFan !subscribed = EventSubscribed
600− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
601− , eventSubscribedRetained = toAny subscribed
602−#ifdef DEBUG_CYCLES
603− , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
604− , eventSubscribedHasOwnHeightRef = False
605− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
606−#endif
607− }
608−
609−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
610−eventSubscribedSwitch !subscribed = EventSubscribed
611− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
612− , eventSubscribedRetained = toAny subscribed
613−#ifdef DEBUG_CYCLES
614− , eventSubscribedGetParents = do
615− s <- readIORef $ switchSubscribedCurrentParent subscribed
616− return [Some $ _eventSubscription_subscribed s]
617− , eventSubscribedHasOwnHeightRef = True
618− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
619−#endif
620− }
621−
622−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
623−eventSubscribedCoincidence !subscribed = EventSubscribed
624− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
625− , eventSubscribedRetained = toAny subscribed
626−#ifdef DEBUG_CYCLES
627− , eventSubscribedGetParents = do
628− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
629− let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
630− innerParents = maybeToList $ fmap Some innerSubscription
631− return $ outerParent : innerParents
632− , eventSubscribedHasOwnHeightRef = True
633− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
634−#endif
635− }
636−
637−getEventSubscribedHeight :: EventSubscribed x -> IO Height
638−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
639−
640−#ifdef DEBUG_CYCLES
641−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
642−whoCreatedEventSubscribed = eventSubscribedWhoCreated
643−
644−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
645−walkInvalidHeightParents s0 = do
646− subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
647− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
648− when (h == invalidHeight) $ do
649− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
650− modify (Some s :)
651− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
652− forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
653− return subscribers
654−#endif
655−
656−{-# INLINE subscribeHoldEvent #-}
657−subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
658−subscribeHoldEvent = subscribeAndRead . holdEvent
659−
660−--------------------------------------------------------------------------------
661−-- Behavior
662−--------------------------------------------------------------------------------
663−
664−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
665−
666−behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
667−behaviorHold !h = Behavior $ readHoldTracked h
668−
669−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
670−behaviorHoldIdentity = behaviorHold
671−
672−behaviorConst :: a -> Behavior x a
673−behaviorConst !a = Behavior $ return a
674−
675−behaviorPull :: Pull x a -> Behavior x a
676−behaviorPull !p = Behavior $ do
677− val <- liftIO $ readIORef $ pullValue p
678− case val of
679− Just subscribed -> do
680− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
681− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
682− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
683− return $ pullSubscribedValue subscribed
684− Nothing -> do
685− i <- liftIO $ newInvalidatorPull p
686− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
687− parentsRef <- liftIO $ newIORef []
688− holdInits <- askBehaviorHoldInits
689− a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
690− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
691− parents <- liftIO $ readIORef parentsRef
692− let subscribed = PullSubscribed
693− { pullSubscribedValue = a
694− , pullSubscribedInvalidators = invsRef
695− , pullSubscribedOwnInvalidator = i
696− , pullSubscribedParents = parents
697− }
698− liftIO $ writeIORef (pullValue p) $ Just subscribed
699− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
700− return a
701−
702−behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
703−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
704−
705−{-# INLINE readHoldTracked #-}
706−readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
707−readHoldTracked h = do
708− result <- liftIO $ readIORef $ holdValue h
709− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
710− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
711− liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
712− return result
713−
714−{-# INLINABLE readBehaviorUntracked #-}
715−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
716−readBehaviorUntracked b = do
717− holdInits <- getDeferralQueue
718− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
719−
720−--------------------------------------------------------------------------------
721−-- Dynamic
722−--------------------------------------------------------------------------------
723−
724−type DynamicS x p = Dynamic x (PatchTarget p) p
725−
726−data Dynamic x target p = Dynamic
727− { dynamicCurrent :: !(Behavior x target)
728− , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
729− }
730−
731−deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
732−
733−
734−
735−
736−dynamicHold :: Hold x p -> DynamicS x p
737−dynamicHold !h = Dynamic
738− { dynamicCurrent = behaviorHold h
739− , dynamicUpdated = eventHold h
740− }
741−
742−dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
743−dynamicHoldIdentity = dynamicHold
744−
745−dynamicConst :: PatchTarget p -> DynamicS x p
746−dynamicConst !a = Dynamic
747− { dynamicCurrent = behaviorConst a
748− , dynamicUpdated = eventNever
749− }
750−
751−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
752−dynamicDyn !d = Dynamic
753− { dynamicCurrent = behaviorDyn d
754− , dynamicUpdated = eventDyn d
755− }
756−
757−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
758−dynamicDynIdentity = dynamicDyn
759−
760−--------------------------------------------------------------------------------
761−-- Combinators
762−--------------------------------------------------------------------------------
763−
764−--type role Hold representational
765−data Hold x p
766− = Hold { holdValue :: !(IORef (PatchTarget p))
767− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
768− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
769− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
770−#ifdef DEBUG_NODEIDS
771− , holdNodeId :: Int
772−#endif
773− }
774−
775−-- | A statically allocated 'SpiderTimeline'
776−data Global
777−
778−{-# NOINLINE globalSpiderTimelineEnv #-}
779−globalSpiderTimelineEnv :: SpiderTimelineEnv Global
780−globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
781−
782−-- | Stores all global data relevant to a particular Spider timeline; only one
783−-- value should exist for each type @x@
784−newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
785−-- We implement SpiderTimelineEnv with a newtype wrapper so
786−-- we can get the coercions we want safely.
787−type role SpiderTimelineEnv nominal
788−
789−data SpiderTimelineEnv' x = SpiderTimelineEnv
790− { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
791− , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
792−#ifdef DEBUG
793− , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
794−#endif
795− }
796−type role SpiderTimelineEnv' phantom
797−
798−instance Eq (SpiderTimelineEnv x) where
799− _ == _ = True -- Since only one exists of each type
800−
801−instance GEq SpiderTimelineEnv where
802− a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
803− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
804− else Nothing
805−
806−data EventEnv x
807− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
808− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
809− , eventEnvDynInits :: !(IORef [SomeDynInit x])
810− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
811− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
812− , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
813− , eventEnvIntClears :: !(IORef [Some IntClear])
814− , eventEnvRootClears :: !(IORef [Some RootClear])
815− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
816− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
817− , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
818− }
819−
820−{-# INLINE runEventM #-}
821−runEventM :: EventM x a -> IO a
822−runEventM = unEventM
823−
824−asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
825−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
826−
827−class MonadIO m => Defer a m where
828− getDeferralQueue :: m (IORef [a])
829−
830−{-# INLINE defer #-}
831−defer :: Defer a m => a -> m ()
832−defer a = do
833− q <- getDeferralQueue
834− liftIO $ modifyIORef' q (a:)
835−
836−instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
837− {-# INLINE getDeferralQueue #-}
838− getDeferralQueue = asksEventEnv eventEnvAssignments
839−
840−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
841− {-# INLINE getDeferralQueue #-}
842− getDeferralQueue = asksEventEnv eventEnvHoldInits
843−
844−instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
845− {-# INLINE getDeferralQueue #-}
846− getDeferralQueue = asksEventEnv eventEnvDynInits
847−
848−instance Defer (SomeHoldInit x) (BehaviorM x) where
849− {-# INLINE getDeferralQueue #-}
850− getDeferralQueue = BehaviorM $ asks snd
851−
852−instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
853− {-# INLINE getDeferralQueue #-}
854− getDeferralQueue = asksEventEnv eventEnvMergeUpdates
855−
856−instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
857− {-# INLINE getDeferralQueue #-}
858− getDeferralQueue = asksEventEnv eventEnvMergeInits
859−
860−class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
861− getCurrentHeight :: m Height
862− scheduleMerge :: Height -> EventM x () -> m ()
863−
864−instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
865− {-# INLINE getCurrentHeight #-}
866− getCurrentHeight = do
867− heightRef <- asksEventEnv eventEnvCurrentHeight
868− liftIO $ readIORef heightRef
869− {-# INLINE scheduleMerge #-}
870− scheduleMerge height subscribed = do
871− delayedRef <- asksEventEnv eventEnvDelayedMerges
872− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
873−
874−class HasSpiderTimeline x where
875− -- | Retrieve the current SpiderTimelineEnv
876− spiderTimeline :: SpiderTimelineEnv x
877−
878−instance HasSpiderTimeline Global where
879− spiderTimeline = globalSpiderTimelineEnv
880−
881−putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
882−putCurrentHeight h = do
883− heightRef <- asksEventEnv eventEnvCurrentHeight
884− liftIO $ writeIORef heightRef $! h
885−
886−instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
887− {-# INLINE getDeferralQueue #-}
888− getDeferralQueue = asksEventEnv eventEnvClears
889−
890−{-# INLINE scheduleClear #-}
891−scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
892−scheduleClear r = defer $ Some $ Clear r
893−
894−instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
895− {-# INLINE getDeferralQueue #-}
896− getDeferralQueue = asksEventEnv eventEnvIntClears
897−
898−{-# INLINE scheduleIntClear #-}
899−scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
900−scheduleIntClear r = defer $ Some $ IntClear r
901−
902−instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
903− {-# INLINE getDeferralQueue #-}
904− getDeferralQueue = asksEventEnv eventEnvRootClears
905−
906−{-# INLINE scheduleRootClear #-}
907−scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
908−scheduleRootClear r = defer $ Some $ RootClear r
909−
910−instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
911− {-# INLINE getDeferralQueue #-}
912− getDeferralQueue = asksEventEnv eventEnvResetCoincidences
913−
914−-- Note: hold cannot examine its event until after the phase is over
915−{-# INLINE [1] hold #-}
916−hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
917−hold v0 e = do
918− valRef <- liftIO $ newIORef v0
919− invsRef <- liftIO $ newIORef []
920− parentRef <- liftIO $ newIORef Nothing
921−#ifdef DEBUG_NODEIDS
922− nodeId <- liftIO newNodeId
923−#endif
924− let h = Hold
925− { holdValue = valRef
926− , holdInvalidators = invsRef
927− , holdEvent = e
928− , holdParent = parentRef
929−#ifdef DEBUG_NODEIDS
930− , holdNodeId = nodeId
931−#endif
932− }
933− defer $ SomeHoldInit h
934− return h
935−
936−{-# INLINE getHoldEventSubscription #-}
937−getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
938−getHoldEventSubscription h = do
939− ep <- liftIO $ readIORef $ holdParent h
940− case ep of
941− Just subd -> return subd
942− Nothing -> do
943− let e = holdEvent h
944− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
945− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
946− liftIO $ writeIORef subscriptionRef $! subscription
947− case occ of
948− Nothing -> return ()
949− Just o -> do
950− old <- liftIO $ readIORef $ holdValue h
951− case apply o old of
952− Nothing -> return ()
953− Just new -> do
954− -- Need to evaluate these so that we don't retain the Hold itself
955− v <- liftIO $ evaluate $ holdValue h
956− i <- liftIO $ evaluate $ holdInvalidators h
957− defer $ SomeAssignment v i new
958− liftIO $ writeIORef (holdParent h) $ Just subscription
959− return subscription
960−
961−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
962−
963−-- BehaviorM can sample behaviors
964−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
965− deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
966−
967−instance Monad (BehaviorM x) where
968− {-# INLINE (>>=) #-}
969− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
970− {-# INLINE (>>) #-}
971− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
972− {-# INLINE return #-}
973− return x = BehaviorM $ return x
974− {-# INLINE fail #-}
975− fail s = BehaviorM $ fail s
976−
977−data BehaviorSubscribed x a
978− = forall p. BehaviorSubscribedHold (Hold x p)
979− | BehaviorSubscribedPull (PullSubscribed x a)
980−
981−newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
982−
983−--type role PullSubscribed representational
984−data PullSubscribed x a
985− = PullSubscribed { pullSubscribedValue :: !a
986− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
987− , pullSubscribedOwnInvalidator :: !(Invalidator x)
988− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
989− }
990−
991−--type role Pull representational
992−data Pull x a
993− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
994− , pullCompute :: !(BehaviorM x a)
995−#ifdef DEBUG_NODEIDS
996− , pullNodeId :: Int
997−#endif
998− }
999−
1000−data Invalidator x
1001− = forall a. InvalidatorPull (Pull x a)
1002− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
1003−
1004−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1005− { rootSubscribedKey :: !(k a)
1006− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1007− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1008− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1009− , rootSubscribedUninit :: IO ()
1010− , 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?
1011−#ifdef DEBUG_NODEIDS
1012− , rootSubscribedNodeId :: Int
1013−#endif
1014− }
1015−
1016−data Root x k
1017− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1018− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1019− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1020− }
1021−
1022−data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1023−
1024−data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1025−
1026−data SomeMergeUpdate x = SomeMergeUpdate
1027− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1028− , _someMergeUpdate_invalidateHeight :: !(IO ())
1029− , _someMergeUpdate_recalculateHeight :: !(IO ())
1030− }
1031−
1032−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1033−
1034−-- EventM can do everything BehaviorM can, plus create holds
1035−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
1036−
1037−newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1038−
1039−data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1040− { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1041− , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1042− }
1043−
1044−data HeightBag = HeightBag
1045− { _heightBag_size :: {-# UNPACK #-} !Int
1046− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1047− }
1048− deriving (Show, Read, Eq, Ord)
1049−
1050−heightBagEmpty :: HeightBag
1051−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1052−
1053−heightBagSize :: HeightBag -> Int
1054−heightBagSize = _heightBag_size
1055−
1056−heightBagFromList :: [Height] -> HeightBag
1057−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1058−
1059−heightBagAdd :: Height -> HeightBag -> HeightBag
1060−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1061−
1062−heightBagRemove :: Height -> HeightBag -> HeightBag
1063−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1064− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1065− Just old -> HeightBag (pred s) $ case old of
1066− 0 -> IntMap.delete h c
1067− _ -> IntMap.insert h (pred old) c
1068−
1069−heightBagMax :: HeightBag -> Height
1070−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1071− Just ((h, _), _) -> Height h
1072− Nothing -> zeroHeight
1073−
1074−heightBagVerify :: HeightBag -> HeightBag
1075−#ifdef DEBUG
1076−heightBagVerify b@(HeightBag s c) = if
1077− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1078− -> error $ "heightBagVerify: size doesn't match: " <> show b
1079− | unHeight invalidHeight `IntMap.member` c
1080− -> error $ "heightBagVerify: contains invalid height: " <> show b
1081− | otherwise -> b
1082−#else
1083−heightBagVerify = id
1084−#endif
1085−
1086−data FanSubscribedChildren x k v a = FanSubscribedChildren
1087− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1088− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1089− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1090− }
1091−
1092−data FanSubscribed x k v
1093− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1094− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1095− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1096− , fanSubscribedParent :: !(EventSubscription x)
1097−#ifdef DEBUG_NODEIDS
1098− , fanSubscribedNodeId :: Int
1099−#endif
1100− }
1101−
1102−data Fan x k v
1103− = Fan { fanParent :: !(Event x (DMap k v))
1104− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1105− }
1106−
1107−data SwitchSubscribed x a
1108− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1109− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1110− , switchSubscribedHeight :: !(IORef Height)
1111− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1112− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1113− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1114− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1115− , switchSubscribedParent :: !(Behavior x (Event x a))
1116− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1117− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1118−#ifdef DEBUG_NODEIDS
1119− , switchSubscribedNodeId :: Int
1120−#endif
1121− }
1122−
1123−data Switch x a
1124− = Switch { switchParent :: !(Behavior x (Event x a))
1125− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1126− }
1127−
1128−#ifdef USE_TEMPLATE_HASKELL
1129−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1130−#endif
1131−data CoincidenceSubscribed x a
1132− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1133− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1134− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1135− , coincidenceSubscribedHeight :: !(IORef Height)
1136− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1137− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1138− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1139− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1140−#ifdef DEBUG_NODEIDS
1141− , coincidenceSubscribedNodeId :: Int
1142−#endif
1143− }
1144−
1145−data Coincidence x a
1146− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1147− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1148− }
1149−
1150−{-# NOINLINE newInvalidatorSwitch #-}
1151−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1152−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1153−
1154−{-# NOINLINE newInvalidatorPull #-}
1155−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1156−newInvalidatorPull p = return $! InvalidatorPull p
1157−
1158−instance HasSpiderTimeline x => Filterable (Event x) where
1159− mapMaybe f = push $ return . f
1160−
1161−instance HasSpiderTimeline x => Align (Event x) where
1162− nil = eventNever
1163−#if MIN_VERSION_these(0, 8, 0)
1164−instance HasSpiderTimeline x => Semialign (Event x) where
1165−#endif
1166− align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1167− DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1168−
1169−#ifdef MIN_VERSION_semialign
1170−#if MIN_VERSION_semialign(1,1,0)
1171−instance HasSpiderTimeline x => Zip (Event x) where
1172−#endif
1173− zip x y = mapMaybe justThese $ align x y
1174−#endif
1175−
1176−data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1177− | BuildDyn !(EventM x (PatchTarget p), Event x p)
1178− | HoldDyn !(Hold x p)
1179−
1180−newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1181−
1182−newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
1183−newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1184−
1185−--TODO: Avoid the duplication between this and R.zipDynWith
1186−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
1187−zipDynWith f da db =
1188− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1189− ec = flip push eab $ \o -> do
1190− (a, b) <- case o of
1191− This (Identity a) -> do
1192− b <- readBehaviorUntracked $ dynamicCurrent db
1193− return (a, b)
1194− That (Identity b) -> do
1195− a <- readBehaviorUntracked $ dynamicCurrent da
1196− return (a, b)
1197− These (Identity a) (Identity b) -> return (a, b)
1198− return $ Just $ Identity $ f a b
1199− in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1200−
1201−buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1202−buildDynamic readV0 v' = do
1203− result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1204− let !d = Dyn result
1205− defer $ SomeDynInit d
1206− return d
1207−
1208−unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1209−unsafeBuildDynamic readV0 v' =
1210− Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1211−
1212−-- ResultM can read behaviors and events
1213−type ResultM = EventM
1214−
1215−instance HasSpiderTimeline x => Functor (Event x) where
1216− fmap f = push $ return . Just . f
1217−
1218−instance Functor (Behavior x) where
1219− fmap f = pull . fmap f . readBehaviorTracked
1220−
1221−{-# INLINE push #-}
1222−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1223−push f e = cacheEvent (pushCheap f e)
1224−
1225−{-# INLINABLE pull #-}
1226−pull :: BehaviorM x a -> Behavior x a
1227−pull a = unsafePerformIO $ do
1228− ref <- newIORef Nothing
1229−#ifdef DEBUG_NODEIDS
1230− nid <- newNodeId
1231−#endif
1232− pure $ behaviorPull $ Pull
1233− { pullCompute = a
1234− , pullValue = ref
1235−#ifdef DEBUG_NODEIDS
1236− , pullNodeId = nid
1237−#endif
1238− }
1239−
1240−{-# INLINABLE switch #-}
1241−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1242−switch a = unsafePerformIO $ do
1243− ref <- newIORef Nothing
1244− pure $ eventSwitch $ Switch
1245− { switchParent = a
1246− , switchSubscribed = ref
1247− }
1248−
1249−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1250−coincidence a = unsafePerformIO $ do
1251− ref <- newIORef Nothing
1252− pure $ eventCoincidence $ Coincidence
1253− { coincidenceParent = a
1254− , coincidenceSubscribed = ref
1255− }
1256−
1257−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1258−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1259−run roots after = do
1260− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1261− let t = spiderTimeline :: SpiderTimelineEnv x
1262− result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
1263− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1264− occBefore <- liftIO $ do
1265− occBefore <- readIORef occRef
1266− writeIORef occRef $! DMap.insert k a occBefore
1267− return occBefore
1268− if DMap.null occBefore
1269− then do scheduleRootClear occRef
1270− return $ Just r
1271− else return Nothing
1272− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1273− propagate a subscribersRef
1274− delayedRef <- asksEventEnv eventEnvDelayedMerges
1275− let go = do
1276− delayed <- liftIO $ readIORef delayedRef
1277− case IntMap.minViewWithKey delayed of
1278− Nothing -> return ()
1279− Just ((currentHeight, cur), future) -> do
1280− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1281− putCurrentHeight $ Height currentHeight
1282− liftIO $ writeIORef delayedRef $! future
1283− sequence_ cur
1284− go
1285− go
1286− putCurrentHeight maxBound
1287− after
1288− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1289− return result
1290−
1291−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1292−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1293− height <- liftIO $ readIORef heightRef
1294− currentHeight <- getCurrentHeight
1295− case height `compare` currentHeight of
1296− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1297− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1298− EQ -> a
1299−
1300−newtype Clear a = Clear (IORef (Maybe a))
1301−
1302−newtype IntClear a = IntClear (IORef (IntMap a))
1303−
1304−newtype RootClear k = RootClear (IORef (DMap k Identity))
1305−
1306−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1307−
1308−debugFinalize :: Bool
1309−debugFinalize = False
1310−
1311−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1312−mkWeakPtrWithDebug x debugNote = do
1313− x' <- evaluate x
1314− mkWeakPtr x' $
1315− if debugFinalize
1316− then Just $ putStrLn $ "finalizing: " ++ debugNote
1317− else Nothing
1318−
1319−type WeakList a = [Weak a]
1320−
1321−{-# INLINE withIncreasedDepth #-}
1322−#ifdef DEBUG
1323−withIncreasedDepth :: CanTrace x m => m a -> m a
1324−withIncreasedDepth a = do
1325− spiderTimeline <- askSpiderTimelineEnv
1326− liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
1327− result <- a
1328− liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
1329− return result
1330−#else
1331−withIncreasedDepth :: m a -> m a
1332−withIncreasedDepth = id
1333−#endif
1334−
1335−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1336−
1337−{-# INLINE tracePropagate #-}
1338−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1339−tracePropagate p = traceWhen p debugPropagate
1340−
1341−{-# INLINE traceInvalidate #-}
1342−traceInvalidate :: String -> IO ()
1343−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1344−
1345−{-# INLINE traceWhen #-}
1346−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1347−traceWhen p b message = traceMWhen p b $ return message
1348−
1349−{-# INLINE traceMWhen #-}
1350−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1351−traceMWhen _ b getMessage = when b $ do
1352− message <- getMessage
1353−#ifdef DEBUG
1354− spiderTimeline <- askSpiderTimelineEnv
1355− d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
1356−#else
1357− let d = 0
1358−#endif
1359− liftIO $ putStrLn $ replicate d ' ' <> message
1360−
1361−whoCreatedIORef :: IORef a -> IO [String]
1362−whoCreatedIORef (IORef a) = whoCreated $! a
1363−
1364−#ifdef DEBUG_CYCLES
1365−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1366−groupByHead = \case
1367− [] -> []
1368− (x :| xs) : t -> case groupByHead t of
1369− [] -> [(x, xs :| [])]
1370− l@((y, yss) : t')
1371− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1372− | otherwise -> (x, xs :| []) : l
1373−
1374−listsToForest :: Eq a => [[a]] -> Forest a
1375−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1376−#endif
1377−
1378−{-# INLINE propagateSubscriberHold #-}
1379−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1380−propagateSubscriberHold h a = do
1381− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1382− invalidators <- liftIO $ readIORef $ holdInvalidators h
1383− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1384− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1385− case {-# SCC "apply" #-} apply a v of
1386− Nothing -> return ()
1387− Just v' -> do
1388− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1389− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1390− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1391− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1392−
1393−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1394−
1395−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1396−runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
1397−
1398−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1399−askInvalidator = do
1400− (!m, _) <- ask
1401− case m of
1402− Nothing -> return Nothing
1403− Just (!wi, _) -> return $ Just wi
1404−
1405−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1406−askParentsRef = do
1407− (!m, _) <- ask
1408− case m of
1409− Nothing -> return Nothing
1410− Just (_, !p) -> return $ Just p
1411−
1412−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1413−askBehaviorHoldInits = do
1414− (_, !his) <- ask
1415− return his
1416−
1417−{-# INLINE getDynHold #-}
1418−getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1419−getDynHold d = do
1420− mh <- liftIO $ readIORef $ unDyn d
1421− case mh of
1422− HoldDyn h -> return h
1423− UnsafeDyn (readV0, v') -> do
1424− holdInits <- getDeferralQueue
1425− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1426− hold' v0 v'
1427− BuildDyn (readV0, v') -> do
1428− v0 <- liftIO $ runEventM readV0
1429− hold' v0 v'
1430− where
1431− hold' v0 v' = do
1432− h <- hold v0 v'
1433− liftIO $ writeIORef (unDyn d) $ HoldDyn h
1434− return h
1435−
1436−
1437−-- Always refers to 0
1438−{-# NOINLINE zeroRef #-}
1439−zeroRef :: IORef Height
1440−zeroRef = unsafePerformIO $ newIORef zeroHeight
1441−
1442−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1443−getRootSubscribed k r sub = do
1444− mSubscribed <- readIORef $ rootSubscribed r
1445− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1446− case DMap.lookup k mSubscribed of
1447− Just subscribed -> {-# SCC "hitRoot" #-} do
1448− sln <- subscribeRootSubscribed subscribed sub
1449− occ <- getOcc
1450− return (sln, subscribed, occ)
1451− Nothing -> {-# SCC "missRoot" #-} do
1452− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1453− let !cached = rootSubscribed r
1454− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1455− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1456− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1457− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1458− writeIORef uninitRef $! uninit
1459−#ifdef DEBUG_NODEIDS
1460− nid <- newNodeId
1461−#endif
1462− let !subscribed = RootSubscribed
1463− { rootSubscribedKey = k
1464− , rootSubscribedCachedSubscribed = cached
1465− , rootSubscribedOccurrence = getOcc
1466− , rootSubscribedSubscribers = subs
1467− , rootSubscribedUninit = uninit
1468− , rootSubscribedWeakSelf = weakSelf
1469−#ifdef DEBUG_NODEIDS
1470− , rootSubscribedNodeId = nid
1471−#endif
1472− }
1473− -- If we die at the same moment that all our children die, they will
1474− -- try to clean us up but will fail because their Weak reference to us
1475− -- will also be dead. So, if we are dying, check if there are any
1476− -- children; since children don't bother cleaning themselves up if
1477− -- their parents are already dead, I don't think there's a race
1478− -- condition here. However, if there are any children, then we can
1479− -- infer that we need to clean ourselves up, so we do.
1480− finalCleanup = do
1481− cs <- readIORef $ _weakBag_children subs
1482− when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1483− writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1484− 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
1485− occ <- getOcc
1486− return (sln, subscribed, occ)
1487−
1488−#ifdef USE_TEMPLATE_HASKELL
1489−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1490−#endif
1491−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1492−cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1493− rootSubscribedUninit self
1494− modifyIORef' cached $ DMap.delete k
1495−
1496−{-# INLINE subscribeRootSubscribed #-}
1497−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1498−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1499−
1500−newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1501−
1502−data FanInt x a = FanInt
1503− { _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
1504− , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1505− , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1506− }
1507−
1508−newFanInt :: IO (FanInt x a)
1509−newFanInt = do
1510− 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
1511− subscriptionRef <- newIORef $ error "fanInt: no subscription"
1512− occRef <- newIORef $ error "fanInt: no occurrence"
1513− return $ FanInt
1514− { _fanInt_subscribers = subscribers
1515− , _fanInt_subscriptionRef = subscriptionRef
1516− , _fanInt_occRef = occRef
1517− }
1518−
1519−fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1520−fanInt p = unsafePerformIO $ do
1521− self <- newFanInt
1522− pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1523− isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1524− when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1525− (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1526− { subscriberPropagate = \m -> do
1527− liftIO $ writeIORef (_fanInt_occRef self) m
1528− scheduleIntClear $ _fanInt_occRef self
1529− FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1530− FastWeakBag.traverse b $ \s -> do
1531− subscriberPropagate s v
1532− , subscriberInvalidateHeight = \old -> do
1533− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1534− FastWeakBag.traverse b $ \s -> do
1535− subscriberInvalidateHeight s old
1536− , subscriberRecalculateHeight = \new -> do
1537− FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1538− FastWeakBag.traverse b $ \s -> do
1539− subscriberRecalculateHeight s new
1540− }
1541− liftIO $ do
1542− writeIORef (_fanInt_subscriptionRef self) subscription
1543− writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1544− scheduleIntClear $ _fanInt_occRef self
1545− liftIO $ do
1546− b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1547− Nothing -> do
1548− b <- FastWeakBag.empty
1549− FastMutableIntMap.insert (_fanInt_subscribers self) k b
1550− return b
1551− Just b -> return b
1552− t <- liftIO $ FastWeakBag.insert sub b
1553− currentOcc <- readIORef (_fanInt_occRef self)
1554− (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1555− return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1556−
1557−{-# INLINABLE getFanSubscribed #-}
1558−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))
1559−getFanSubscribed k f sub = do
1560− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1561− case mSubscribed of
1562− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1563− sln <- subscribeFanSubscribed k subscribed sub
1564− occ <- readIORef $ fanSubscribedOccurrence subscribed
1565− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1566− Nothing -> {-# SCC "missFan" #-} do
1567− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1568− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1569− s <- liftIO $ newSubscriberFan subscribedUnsafe
1570− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1571− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1572− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1573− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1574− occRef <- liftIO $ newIORef parentOcc
1575− when (isJust parentOcc) $ scheduleClear occRef
1576−#ifdef DEBUG_NODEIDS
1577− nid <- liftIO newNodeId
1578−#endif
1579− let subscribed = FanSubscribed
1580− { fanSubscribedCachedSubscribed = fanSubscribed f
1581− , fanSubscribedOccurrence = occRef
1582− , fanSubscribedParent = subscription
1583− , fanSubscribedSubscribers = subscribersRef
1584−#ifdef DEBUG_NODEIDS
1585− , fanSubscribedNodeId = nid
1586−#endif
1587− }
1588− let !self = (k, subscribed)
1589− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1590− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1591− liftIO $ writeIORef subscribedRef $! subscribed
1592− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1593− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1594−
1595−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1596−cleanupFanSubscribed (k, subscribed) = do
1597− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1598− let reducedSubscribers = DMap.delete k subscribers
1599− if DMap.null reducedSubscribers
1600− then do
1601− unsubscribe $ fanSubscribedParent subscribed
1602− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1603− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1604− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1605−
1606−{-# INLINE subscribeFanSubscribed #-}
1607−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1608−subscribeFanSubscribed k subscribed sub = do
1609− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1610− case DMap.lookup k subscribers of
1611− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1612− let !self = (k, subscribed)
1613− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1614− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1615− 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
1616− return sln
1617− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1618−
1619−{-# INLINABLE getSwitchSubscribed #-}
1620−getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1621−getSwitchSubscribed s sub = do
1622− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1623− case mSubscribed of
1624− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1625− sln <- subscribeSwitchSubscribed subscribed sub
1626− occ <- readIORef $ switchSubscribedOccurrence subscribed
1627− return (sln, subscribed, occ)
1628− Nothing -> {-# SCC "missSwitch" #-} do
1629− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1630− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1631− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1632− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1633− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1634− wiRef <- liftIO $ newIORef wi
1635− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1636− holdInits <- getDeferralQueue
1637− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1638− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1639− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1640− subscriptionRef <- liftIO $ newIORef subscription
1641− occRef <- liftIO $ newIORef parentOcc
1642− when (isJust parentOcc) $ scheduleClear occRef
1643− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1644− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1645−#ifdef DEBUG_NODEIDS
1646− nid <- liftIO newNodeId
1647−#endif
1648− let !subscribed = SwitchSubscribed
1649− { switchSubscribedCachedSubscribed = switchSubscribed s
1650− , switchSubscribedOccurrence = occRef
1651− , switchSubscribedHeight = heightRef
1652− , switchSubscribedSubscribers = subs
1653− , switchSubscribedOwnInvalidator = i
1654− , switchSubscribedOwnWeakInvalidator = wiRef
1655− , switchSubscribedBehaviorParents = parentsRef
1656− , switchSubscribedParent = switchParent s
1657− , switchSubscribedCurrentParent = subscriptionRef
1658− , switchSubscribedWeakSelf = weakSelf
1659−#ifdef DEBUG_NODEIDS
1660− , switchSubscribedNodeId = nid
1661−#endif
1662− }
1663− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1664− liftIO $ writeIORef subscribedRef $! subscribed
1665− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1666− return (slnForSub, subscribed, parentOcc)
1667−
1668−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1669−cleanupSwitchSubscribed subscribed = do
1670− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1671− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1672− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1673−
1674−{-# INLINE subscribeSwitchSubscribed #-}
1675−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1676−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1677−
1678−{-# INLINABLE getCoincidenceSubscribed #-}
1679−getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1680−getCoincidenceSubscribed c sub = do
1681− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1682− case mSubscribed of
1683− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1684− sln <- subscribeCoincidenceSubscribed subscribed sub
1685− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1686− return (sln, subscribed, occ)
1687− Nothing -> {-# SCC "missCoincidence" #-} do
1688− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1689− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1690− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1691− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1692− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1693− (occ, height, mInnerSubd) <- case outerOcc of
1694− Nothing -> return (Nothing, outerHeight, Nothing)
1695− Just o -> do
1696− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1697− return (occ, height, Just innerSubd)
1698− occRef <- liftIO $ newIORef occ
1699− when (isJust occ) $ scheduleClear occRef
1700− heightRef <- liftIO $ newIORef height
1701− innerSubdRef <- liftIO $ newIORef mInnerSubd
1702− scheduleClear innerSubdRef
1703− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1704− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1705−#ifdef DEBUG_NODEIDS
1706− nid <- liftIO newNodeId
1707−#endif
1708− let subscribed = CoincidenceSubscribed
1709− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1710− , coincidenceSubscribedOccurrence = occRef
1711− , coincidenceSubscribedHeight = heightRef
1712− , coincidenceSubscribedSubscribers = subs
1713− , coincidenceSubscribedOuter = subOuter
1714− , coincidenceSubscribedOuterParent = outerSubscription
1715− , coincidenceSubscribedInnerParent = innerSubdRef
1716− , coincidenceSubscribedWeakSelf = weakSelf
1717−#ifdef DEBUG_NODEIDS
1718− , coincidenceSubscribedNodeId = nid
1719−#endif
1720− }
1721− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1722− liftIO $ writeIORef subscribedRef $! subscribed
1723− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1724− return (slnForSub, subscribed, occ)
1725−
1726−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1727−cleanupCoincidenceSubscribed subscribed = do
1728− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1729− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1730−
1731−{-# INLINE subscribeCoincidenceSubscribed #-}
1732−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1733−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1734−
1735−{-# INLINE mergeG #-}
1736−mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1737− => (forall a. q a -> Event x (v a))
1738− -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1739−mergeG nt d = cacheEvent (mergeCheap nt d)
1740−
1741−{-# INLINE mergeWithMove #-}
1742−mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1743− => (forall a. q a -> Event x (v a))
1744− -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1745−mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1746−
1747−{-# INLINE [1] mergeCheap #-}
1748−mergeCheap
1749− :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1750− => (forall a. q a -> Event x (v a))
1751− -> DynamicS x (PatchDMap k q)
1752− -> Event x (DMap k v)
1753−mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1754− where
1755− updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1756− updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1757− let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1758− (mOldSubd, newPs) <- case me of
1759− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1760− Just e -> do
1761− let s = subscriber $ return k
1762− subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1763− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1764− let newParent = MergeSubscribedParent subscription
1765− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1766− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1767− forM_ mOldSubd $ \oldSubd -> do
1768− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1769− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1770− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1771− foldM f ([], oldParents) $ DMap.toList p
1772−
1773− getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1774− getInitialSubscribers initialParents subscriber = do
1775− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1776− let s = subscriber $ return k
1777− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1778− height <- liftIO $ getEventSubscribedHeight parentSubd
1779− return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1780− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1781− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1782− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1783− )
1784−
1785− destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1786− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1787−
1788−{-# INLINE [1] mergeCheapWithMove #-}
1789−mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1790− => (forall a. q a -> Event x (v a))
1791− -> DynamicS x (PatchDMapWithMove k q)
1792− -> Event x (DMap k v)
1793−mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1794− where
1795− updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1796− updateMe subscriber heightBagRef oldParents p = do
1797− -- Prepare new parents for insertion
1798− let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1799− subscribeParent k e = do
1800− keyRef <- liftIO $ newIORef k
1801− let s = subscriber $ liftIO $ readIORef keyRef
1802− subscription@(EventSubscription _ subd) <- subscribe e s
1803− liftIO $ do
1804− newParentHeight <- getEventSubscribedHeight subd
1805− modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1806− return $ MergeSubscribedParentWithMove subscription keyRef
1807− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1808− -- Collect old parents for deletion and update the keys of moved parents
1809− let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1810− moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1811− Nothing -> do
1812− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1813− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1814− return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1815− Just toKey -> do
1816− liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1817− return Nothing
1818− toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1819− return (toDelete, applyAlways p' oldParents)
1820− getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1821− getInitialSubscribers initialParents subscriber = do
1822− subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1823− keyRef <- liftIO $ newIORef k
1824− let s = subscriber $ liftIO $ readIORef keyRef
1825− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1826− height <- liftIO $ getEventSubscribedHeight parentSubd
1827− return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1828− return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1829− , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1830− , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1831− )
1832−
1833− destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1834− destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1835−
1836−type MergeUpdateFunc k v x p s
1837− = (forall a. EventM x (k a) -> Subscriber x (v a))
1838− -> IORef HeightBag
1839− -> DMap k s
1840− -> p
1841− -> EventM x ([EventSubscription x], DMap k s)
1842−
1843−type MergeInitFunc k v q x s
1844− = DMap k q
1845− -> (forall a. EventM x (k a) -> Subscriber x (v a))
1846− -> EventM x (DMap k v, [Height], DMap k s)
1847−
1848−type MergeDestroyFunc k s
1849− = DMap k s
1850− -> IO ()
1851−
1852−data Merge x k v s = Merge
1853− { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1854− , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1855− , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1856− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1857− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1858− }
1859−
1860−invalidateMergeHeight :: Merge x k v s -> IO ()
1861−invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1862−
1863−invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1864−invalidateMergeHeight' heightRef sub = do
1865− oldHeight <- readIORef heightRef
1866− 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
1867− writeIORef heightRef $! invalidHeight
1868− subscriberInvalidateHeight sub oldHeight
1869−
1870−revalidateMergeHeight :: Merge x k v s -> IO ()
1871−revalidateMergeHeight m = do
1872− currentHeight <- readIORef $ _merge_heightRef m
1873− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1874− heights <- readIORef $ _merge_heightBagRef m
1875− parents <- readIORef $ _merge_parentsRef m
1876− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1877− case heightBagSize heights `compare` DMap.size parents of
1878− LT -> return ()
1879− EQ -> do
1880− let height = succHeight $ heightBagMax heights
1881− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1882− writeIORef (_merge_heightRef m) $! height
1883− subscriberRecalculateHeight (_merge_sub m) height
1884− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1885−
1886−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1887−scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1888− vals <- liftIO $ readIORef $ _merge_accumRef m
1889− 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
1890− --TODO: Assert that m is not empty
1891− subscriberPropagate (_merge_sub m) vals
1892−
1893−mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1894−mergeSubscriber m getKey = Subscriber
1895− { subscriberPropagate = \a -> do
1896− oldM <- liftIO $ readIORef $ _merge_accumRef m
1897− k <- getKey
1898− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1899− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1900− liftIO $ writeIORef (_merge_accumRef m) $! newM
1901− when (DMap.null oldM) $ do -- Only schedule the firing once
1902− height <- liftIO $ readIORef $ _merge_heightRef m
1903− --TODO: assertions about height
1904− currentHeight <- getCurrentHeight
1905− when (height <= currentHeight) $ do
1906− if height /= invalidHeight
1907− then do
1908− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1909− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1910− else liftIO $ do
1911−#ifdef DEBUG_CYCLES
1912− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1913− stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1914− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1915−#else
1916− let cycleInfo = ""
1917−#endif
1918− error $ "Causality loop found" <> cycleInfo
1919− scheduleMergeSelf m height
1920− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1921− modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1922− invalidateMergeHeight m
1923− , subscriberRecalculateHeight = \new -> do
1924− modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1925− revalidateMergeHeight m
1926− }
1927−
1928−--TODO: Be able to run as much of this as possible promptly
1929−updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1930−updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1931− where updateMe = do
1932− oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1933− (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1934− liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1935− return subscriptionsToKill
1936−
1937−{-# INLINE mergeGCheap' #-}
1938−mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1939− => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1940−mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1941− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1942− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1943− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1944− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1945− parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1946− let m = Merge
1947− { _merge_parentsRef = parentsRef
1948− , _merge_heightBagRef = heightBagRef
1949− , _merge_heightRef = heightRef
1950− , _merge_sub = sub
1951− , _merge_accumRef = accumRef
1952− }
1953− (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1954− let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1955− myHeight = if invalidHeight `elem` heights
1956− then invalidHeight
1957− else succHeight $ heightBagMax myHeightBag
1958− currentHeight <- getCurrentHeight
1959− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1960− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1961− else (Nothing, dm)
1962− unless (DMap.null accum) $ do
1963− scheduleMergeSelf m myHeight
1964− liftIO $ writeIORef accumRef $! accum
1965− liftIO $ writeIORef heightRef $! myHeight
1966− liftIO $ writeIORef heightBagRef $! myHeightBag
1967− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1968− liftIO $ writeIORef parentsRef $! initialParentState
1969− defer $ SomeMergeInit $ do
1970− let s = Subscriber
1971− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1972− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1973− defer $ updateMerge m updateFunc a
1974− , subscriberInvalidateHeight = \_ -> return ()
1975− , subscriberRecalculateHeight = \_ -> return ()
1976− }
1977− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1978− forM_ change $ \c -> defer $ updateMerge m updateFunc c
1979− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1980− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1981− -- its subscription.
1982− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1983− let unsubscribeAll = destroy =<< readIORef parentsRef
1984− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1985− , occ
1986− )
1987−
1988−mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1989−mergeInt = cacheEvent . mergeIntCheap
1990−
1991−{-# INLINABLE mergeIntCheap #-}
1992−mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1993−mergeIntCheap d = Event $ \sub -> do
1994− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1995− accum <- liftIO $ FastMutableIntMap.newEmpty
1996− heightRef <- liftIO $ newIORef zeroHeight
1997− heightBagRef <- liftIO $ newIORef heightBagEmpty
1998− parents <- liftIO $ FastMutableIntMap.newEmpty
1999− let scheduleSelf = do
2000− height <- liftIO $ readIORef $ heightRef
2001− scheduleMerge' height heightRef $ do
2002− vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
2003− subscriberPropagate sub vals
2004− invalidateMyHeight = do
2005− invalidateMergeHeight' heightRef sub
2006− recalculateMyHeight = do
2007− currentHeight <- readIORef heightRef
2008− 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?
2009− heights <- readIORef heightBagRef
2010− numParents <- FastMutableIntMap.size parents
2011− case heightBagSize heights `compare` numParents of
2012− LT -> return ()
2013− EQ -> do
2014− let height = succHeight $ heightBagMax heights
2015− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
2016− writeIORef heightRef $! height
2017− subscriberRecalculateHeight sub height
2018− GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
2019− mySubscriber k = Subscriber
2020− { subscriberPropagate = \a -> do
2021− wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2022− liftIO $ FastMutableIntMap.insert accum k a
2023− when wasEmpty scheduleSelf
2024− , subscriberInvalidateHeight = \old -> do
2025− modifyIORef' heightBagRef $ heightBagRemove old
2026− invalidateMyHeight
2027− , subscriberRecalculateHeight = \new -> do
2028− modifyIORef' heightBagRef $ heightBagAdd new
2029− recalculateMyHeight
2030− }
2031− forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2032− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2033− liftIO $ do
2034− forM_ parentOcc $ FastMutableIntMap.insert accum k
2035− FastMutableIntMap.insert parents k subscription
2036− height <- getEventSubscribedHeight parentSubd
2037− if height == invalidHeight
2038− then writeIORef heightRef invalidHeight
2039− else do
2040− modifyIORef' heightBagRef $ heightBagAdd height
2041− modifyIORef' heightRef $ \oldHeight ->
2042− if oldHeight == invalidHeight
2043− then invalidHeight
2044− else max (succHeight height) oldHeight
2045− myHeight <- liftIO $ readIORef heightRef
2046− currentHeight <- getCurrentHeight
2047− isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2048− occ <- if currentHeight >= myHeight -- If we should have fired by now
2049− then if isEmpty
2050− then return Nothing
2051− else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2052− else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2053− return Nothing
2054− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2055− defer $ SomeMergeInit $ do
2056− let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2057− where
2058− u = do
2059− let f k newParent = do
2060− subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2061− newParentHeight <- liftIO $ getEventSubscribedHeight subd
2062− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2063− return subscription
2064− newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2065− oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2066− liftIO $ for_ oldParents $ \oldParent -> do
2067− oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2068− modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2069− return $ IntMap.elems oldParents
2070− let s = Subscriber
2071− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2072− tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2073− defer $ updateMe a
2074− , subscriberInvalidateHeight = \_ -> return ()
2075− , subscriberRecalculateHeight = \_ -> return ()
2076− }
2077− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2078− forM_ change $ \c -> defer $ updateMe c
2079− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2080− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2081− -- its subscription.
2082− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2083− let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2084− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2085− , occ
2086− )
2087−
2088−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2089−newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2090−
2091−fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2092−fanG e = unsafePerformIO $ do
2093− ref <- newIORef Nothing
2094− let f = Fan
2095− { fanParent = e
2096− , fanSubscribed = ref
2097− }
2098− pure $ EventSelectorG $ \k -> eventFan k f
2099−
2100−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2101−runHoldInits holdInitRef dynInitRef mergeInitRef = do
2102− holdInits <- liftIO $ readIORef holdInitRef
2103− dynInits <- liftIO $ readIORef dynInitRef
2104− mergeInits <- liftIO $ readIORef mergeInitRef
2105− unless (null holdInits && null dynInits && null mergeInits) $ do
2106− liftIO $ writeIORef holdInitRef []
2107− liftIO $ writeIORef dynInitRef []
2108− liftIO $ writeIORef mergeInitRef []
2109− mapM_ initHold holdInits
2110− mapM_ initDyn dynInits
2111− mapM_ unSomeMergeInit mergeInits
2112− runHoldInits holdInitRef dynInitRef mergeInitRef
2113−
2114−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2115−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2116−
2117−initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2118−initDyn (SomeDynInit d) = void $ getDynHold d
2119−
2120−newEventEnv :: IO (EventEnv x)
2121−newEventEnv = do
2122− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2123− holdInitRef <- newIORef []
2124− dynInitRef <- newIORef []
2125− mergeUpdateRef <- newIORef []
2126− mergeInitRef <- newIORef []
2127− heightRef <- newIORef zeroHeight
2128− toClearRef <- newIORef []
2129− toClearIntRef <- newIORef []
2130− toClearRootRef <- newIORef []
2131− coincidenceInfosRef <- newIORef []
2132− delayedRef <- newIORef IntMap.empty
2133− return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2134−
2135−clearEventEnv :: EventEnv x -> IO ()
2136−clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2137− writeIORef toAssignRef []
2138− writeIORef holdInitRef []
2139− writeIORef dynInitRef []
2140− writeIORef mergeUpdateRef []
2141− writeIORef mergeInitRef []
2142− writeIORef heightRef zeroHeight
2143− writeIORef toClearRef []
2144− writeIORef toClearIntRef []
2145− writeIORef toClearRootRef []
2146− writeIORef coincidenceInfosRef []
2147− writeIORef delayedRef IntMap.empty
2148−
2149−-- | Run an event action outside of a frame
2150−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2151−runFrame a = SpiderHost $ do
2152− let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
2153− let go = do
2154− result <- a
2155− 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
2156− return result
2157− result <- runEventM go
2158− toClear <- readIORef $ eventEnvClears env
2159− forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2160− toClearInt <- readIORef $ eventEnvIntClears env
2161− forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2162− toClearRoot <- readIORef $ eventEnvRootClears env
2163− forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2164− toAssign <- readIORef $ eventEnvAssignments env
2165− toReconnectRef <- newIORef []
2166− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2167− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2168− writeIORef vRef v
2169− when debugInvalidate $ putStrLn $ "Invalidating Hold"
2170− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2171− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2172− writeIORef (eventEnvMergeUpdates env) []
2173− when debugPropagate $ putStrLn "Updating merges"
2174− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2175− when debugPropagate $ putStrLn "Updating merges done"
2176− toReconnect <- readIORef toReconnectRef
2177− clearEventEnv env
2178− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2179− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2180− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2181− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2182− finalize wi
2183− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2184− wi' <- mkWeakPtrWithDebug i "wi'"
2185− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2186− writeIORef (switchSubscribedBehaviorParents subscribed) []
2187− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2188− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2189− 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
2190− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2191− sub <- newSubscriberSwitch subscribed
2192− 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
2193− {-
2194− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2195− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2196− EventRoot _ -> "EventRoot"
2197− EventNever -> "EventNever"
2198− _ -> "something else"
2199− -}
2200− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2201− return oldSubscription
2202− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2203− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2204− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2205− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2206− parentHeight <- getEventSubscribedHeight subd'
2207− myHeight <- readIORef $ switchSubscribedHeight subscribed
2208− when (parentHeight /= myHeight) $ do
2209− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2210− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2211− 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
2212− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2213− unsubscribe subscription
2214− mapM_ invalidateCoincidenceHeight mcs
2215− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2216− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2217− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2218− height <- calculateSwitchHeight subscribed
2219− updateSwitchHeight height subscribed
2220− return result
2221−
2222−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2223−
2224−{-# INLINE zeroHeight #-}
2225−zeroHeight :: Height
2226−zeroHeight = Height 0
2227−
2228−{-# INLINE invalidHeight #-}
2229−invalidHeight :: Height
2230−invalidHeight = Height (-1000)
2231−
2232−#ifdef DEBUG_CYCLES
2233−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2234−{-# INLINE invalidHeightBeingTraversed #-}
2235−invalidHeightBeingTraversed :: Height
2236−invalidHeightBeingTraversed = Height (-1001)
2237−#endif
2238−
2239−{-# INLINE succHeight #-}
2240−succHeight :: Height -> Height
2241−succHeight h@(Height a) =
2242− if h == invalidHeight
2243− then invalidHeight
2244− else Height $ succ a
2245−
2246−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2247−invalidateCoincidenceHeight subscribed = do
2248− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2249− when (oldHeight /= invalidHeight) $ do
2250− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2251− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2252−
2253−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2254−updateSwitchHeight new subscribed = do
2255− oldHeight <- readIORef $ switchSubscribedHeight subscribed
2256− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2257− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2258− writeIORef (switchSubscribedHeight subscribed) $! new
2259− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2260−
2261−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2262−recalculateCoincidenceHeight subscribed = do
2263− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2264− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2265− height <- calculateCoincidenceHeight subscribed
2266− when (height /= invalidHeight) $ do
2267− writeIORef (coincidenceSubscribedHeight subscribed) $! height
2268− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2269−
2270−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2271−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2272−
2273−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2274−calculateCoincidenceHeight subscribed = do
2275− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2276− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2277− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2278−
2279−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2280−
2281−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2282−invalidate toReconnectRef wis = do
2283− forM_ wis $ \wi -> do
2284− mi <- deRefWeak wi
2285− case mi of
2286− Nothing -> do
2287− traceInvalidate "invalidate Dead"
2288− return () --TODO: Should we clean this up here?
2289− Just i -> do
2290− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2291− case i of
2292− InvalidatorPull p -> do
2293− traceInvalidate $ "invalidate: Pull" <> showNodeId p
2294− mVal <- readIORef $ pullValue p
2295− forM_ mVal $ \val -> do
2296− writeIORef (pullValue p) Nothing
2297− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2298− InvalidatorSwitch subscribed -> do
2299− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2300− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2301− 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
2302−
2303−--------------------------------------------------------------------------------
2304−-- Reflex integration
2305−--------------------------------------------------------------------------------
2306−
2307−-- | Designates the default, global Spider timeline
2308−data SpiderTimeline x
2309−type role SpiderTimeline nominal
2310−
2311−-- | The default, global Spider environment
2312−type Spider = SpiderTimeline Global
2313−
2314−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2315− {-# INLINABLE sample #-}
2316− sample (SpiderBehavior b) = readBehaviorUntracked b
2317−
2318−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2319− {-# INLINABLE hold #-}
2320− hold = holdSpiderEventM
2321− {-# INLINABLE holdDyn #-}
2322− holdDyn = holdDynSpiderEventM
2323− {-# INLINABLE holdIncremental #-}
2324− holdIncremental = holdIncrementalSpiderEventM
2325− {-# INLINABLE buildDynamic #-}
2326− buildDynamic = buildDynamicSpiderEventM
2327− {-# INLINABLE headE #-}
2328− headE = R.slowHeadE
2329−-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2330−
2331−instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2332− {-# INLINABLE sample #-}
2333− sample = coerce . readBehaviorTracked . unSpiderBehavior
2334−
2335−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2336− {-# INLINABLE sample #-}
2337− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2338−
2339−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2340− {-# INLINABLE hold #-}
2341− hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2342− {-# INLINABLE holdDyn #-}
2343− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2344− {-# INLINABLE holdIncremental #-}
2345− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2346− {-# INLINABLE buildDynamic #-}
2347− buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2348− {-# INLINABLE headE #-}
2349− headE = R.slowHeadE
2350−-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2351−
2352−instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2353− {-# INLINE return #-}
2354− return = pure
2355− {-# INLINE (>>=) #-}
2356− x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2357− {-# INLINE (>>) #-}
2358− (>>) = (*>)
2359− {-# INLINE fail #-}
2360− fail _ = error "Dynamic does not support 'fail'"
2361−
2362−{-# INLINABLE newJoinDyn #-}
2363−newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2364−newJoinDyn d =
2365− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2366− eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2367− eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2368− eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2369− v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2370− in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2371−
2372−instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2373− fmap = mapDynamicSpider
2374− x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2375−
2376−mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2377−mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2378−{-# INLINE [1] mapDynamicSpider #-}
2379−
2380−instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2381− pure = SpiderDynamic . dynamicConst
2382−#if MIN_VERSION_base(4,10,0)
2383− liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2384−#endif
2385− SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2386− a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2387− (<*) = flip (*>) -- There are no effects, so order doesn't matter
2388−
2389−holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2390−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2391−
2392−holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2393−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2394−
2395−holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2396−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2397−
2398−buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2399−buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2400−
2401−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2402− {-# INLINABLE hold #-}
2403− hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2404− {-# INLINABLE holdDyn #-}
2405− holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2406− {-# INLINABLE holdIncremental #-}
2407− holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2408− {-# INLINABLE buildDynamic #-}
2409− buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2410− {-# INLINABLE headE #-}
2411− headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2412−
2413−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2414− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2415−
2416−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2417− {-# INLINABLE hold #-}
2418− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2419− {-# INLINABLE holdDyn #-}
2420− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2421− {-# INLINABLE holdIncremental #-}
2422− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2423− {-# INLINABLE buildDynamic #-}
2424− buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2425− {-# INLINABLE headE #-}
2426− headE = R.slowHeadE
2427−-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2428−
2429−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2430− {-# INLINABLE sample #-}
2431− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2432−
2433−instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2434− {-# INLINABLE sample #-}
2435− sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2436−
2437−instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2438− {-# INLINABLE hold #-}
2439− hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2440− {-# INLINABLE holdDyn #-}
2441− holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2442− {-# INLINABLE holdIncremental #-}
2443− holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2444− {-# INLINABLE buildDynamic #-}
2445− buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2446− {-# INLINABLE headE #-}
2447− headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2448−
2449−--------------------------------------------------------------------------------
2450−-- Deprecated items
2451−--------------------------------------------------------------------------------
2452−
2453−-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2454−{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2455−type SpiderEnv = SpiderTimeline
2456−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2457− {-# INLINABLE subscribeEvent #-}
2458− subscribeEvent e = SpiderHostFrame $ do
2459− --TODO: Unsubscribe eventually (manually and/or with weak ref)
2460− val <- liftIO $ newIORef Nothing
2461− subscription <- subscribe (unSpiderEvent e) $ Subscriber
2462− { subscriberPropagate = \a -> do
2463− liftIO $ writeIORef val $ Just a
2464− scheduleClear val
2465− , subscriberInvalidateHeight = \_ -> return ()
2466− , subscriberRecalculateHeight = \_ -> return ()
2467− }
2468− return $ SpiderEventHandle
2469− { spiderEventHandleSubscription = subscription
2470− , spiderEventHandleValue = val
2471− }
2472−
2473−instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2474− type EventTrigger (SpiderTimeline x) = RootTrigger x
2475− type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2476− type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2477−
2478−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2479− {-# NOINLINE readEvent #-}
2480− readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2481− result <- readIORef $ spiderEventHandleValue h
2482− touch h
2483− return result
2484−
2485−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2486− newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2487− newFanEventWithTrigger f = SpiderHost $ do
2488− es <- newFanEventWithTriggerIO f
2489− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2490−
2491−instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2492− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2493− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2494− es <- newFanEventWithTriggerIO f
2495− return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2496−
2497−instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2498− {-# INLINABLE subscribeEvent #-}
2499− subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2500−
2501−instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2502− type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2503− fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2504− runHostFrame = runFrame . runSpiderHostFrame
2505−
2506−unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2507−unsafeNewSpiderTimelineEnv = do
2508− lock <- newMVar ()
2509− env <- newEventEnv
2510−#ifdef DEBUG
2511− depthRef <- newIORef 0
2512−#endif
2513− return $ STE $ SpiderTimelineEnv
2514− { _spiderTimeline_lock = lock
2515− , _spiderTimeline_eventEnv = env
2516−#ifdef DEBUG
2517− , _spiderTimeline_depth = depthRef
2518−#endif
2519− }
2520−
2521−-- | Create a new SpiderTimelineEnv
2522−newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2523−newSpiderTimeline = withSpiderTimeline (pure . Some)
2524−
2525−data LocalSpiderTimeline (x :: Type) s
2526−
2527−instance Reifies s (SpiderTimelineEnv x) =>
2528− HasSpiderTimeline (LocalSpiderTimeline x s) where
2529− spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
2530−
2531−localSpiderTimeline
2532− :: proxy s
2533− -> SpiderTimelineEnv x
2534− -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2535−localSpiderTimeline _ = coerce
2536−
2537−-- | Pass a new timeline to the given function.
2538−withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2539−withSpiderTimeline k = do
2540− env <- unsafeNewSpiderTimelineEnv
2541− reify env $ \s -> k $ localSpiderTimeline s env
2542−
2543−newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2544−
2545−type ComputeM = EventM
2546−
2547−newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2548−
2549−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2550− {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2551− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2552− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2553− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2554− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
2555− type PullM (SpiderTimeline x) = SpiderPullM x
2556− type PushM (SpiderTimeline x) = SpiderPushM x
2557− {-# INLINABLE never #-}
2558− never = SpiderEvent eventNever
2559− {-# INLINABLE constant #-}
2560− constant = SpiderBehavior . behaviorConst
2561− {-# INLINE push #-}
2562− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2563− {-# INLINE pushCheap #-}
2564− pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2565− {-# INLINABLE pull #-}
2566− pull = SpiderBehavior . pull . coerce
2567− {-# INLINABLE fanG #-}
2568− fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2569− {-# INLINABLE mergeG #-}
2570− mergeG
2571− :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2572− => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2573− -> DMap k q
2574− -> R.Event (SpiderTimeline x) (DMap k v)
2575− mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2576− {-# INLINABLE switch #-}
2577− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2578− {-# INLINABLE coincidence #-}
2579− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2580− {-# INLINABLE current #-}
2581− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2582− {-# INLINABLE updated #-}
2583− updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
2584− {-# INLINABLE unsafeBuildDynamic #-}
2585− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2586− {-# INLINABLE unsafeBuildIncremental #-}
2587− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2588− {-# INLINABLE mergeIncrementalG #-}
2589− mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2590− {-# INLINABLE mergeIncrementalWithMoveG #-}
2591− mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2592− {-# INLINABLE currentIncremental #-}
2593− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2594− {-# INLINABLE updatedIncremental #-}
2595− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2596− {-# INLINABLE incrementalToDynamic #-}
2597− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2598− c <- readBehaviorUntracked $ dynamicCurrent i
2599− return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2600− eventCoercion Coercion = Coercion
2601− behaviorCoercion Coercion = Coercion
2602− dynamicCoercion Coercion = Coercion
2603− incrementalCoercion Coercion Coercion = Coercion
2604− {-# INLINABLE mergeIntIncremental #-}
2605− mergeIntIncremental = SpiderEvent . mergeInt . coerce
2606− {-# INLINABLE fanInt #-}
2607− fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2608−
2609−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2610−
2611−data SpiderEventHandle x a = SpiderEventHandle
2612− { spiderEventHandleSubscription :: EventSubscription x
2613− , spiderEventHandleValue :: IORef (Maybe a)
2614− }
2615−
2616−instance MonadRef (EventM x) where
2617− type Ref (EventM x) = Ref IO
2618− {-# INLINABLE newRef #-}
2619− {-# INLINABLE readRef #-}
2620− {-# INLINABLE writeRef #-}
2621− newRef = liftIO . newRef
2622− readRef = liftIO . readRef
2623− writeRef r a = liftIO $ writeRef r a
2624−
2625−instance MonadAtomicRef (EventM x) where
2626− {-# INLINABLE atomicModifyRef #-}
2627− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2628−
2629−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2630−newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2631−
2632−instance Monad (SpiderHost x) where
2633− {-# INLINABLE (>>=) #-}
2634− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2635− {-# INLINABLE (>>) #-}
2636− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2637− {-# INLINABLE return #-}
2638− return x = SpiderHost $ return x
2639− {-# INLINABLE fail #-}
2640− fail s = SpiderHost $ fail s
2641−
2642−-- | Run an action affecting the global Spider timeline; this will be guarded by
2643−-- a mutex for that timeline
2644−runSpiderHost :: SpiderHost Global a -> IO a
2645−runSpiderHost (SpiderHost a) = a
2646−
2647−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2648−-- mutex for that timeline
2649−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2650−runSpiderHostForTimeline (SpiderHost a) _ = a
2651−
2652−newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2653− deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2654−
2655−instance Monad (SpiderHostFrame x) where
2656− {-# INLINABLE (>>=) #-}
2657− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2658− {-# INLINABLE (>>) #-}
2659− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2660− {-# INLINABLE return #-}
2661− return x = SpiderHostFrame $ return x
2662− {-# INLINABLE fail #-}
2663− fail s = SpiderHostFrame $ fail s
2664−
2665−instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2666− notReadyUntil _ = pure ()
2667− notReady = pure ()
2668−
2669−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2670−newEventWithTriggerIO f = do
2671− es <- newFanEventWithTriggerIO $ \Refl -> f
2672− return $ select es Refl
2673−
2674−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2675−newFanEventWithTriggerIO f = do
2676− occRef <- newIORef DMap.empty
2677− subscribedRef <- newIORef DMap.empty
2678− let !r = Root
2679− { rootOccurrence = occRef
2680− , rootSubscribed = subscribedRef
2681− , rootInit = f
2682− }
2683− return $ EventSelector $ \k -> eventRoot k r
2684−
2685−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2686−
2687−instance MonadRef (SpiderHost x) where
2688− type Ref (SpiderHost x) = Ref IO
2689− newRef = SpiderHost . newRef
2690− readRef = SpiderHost . readRef
2691− writeRef r = SpiderHost . writeRef r
2692−
2693−instance MonadAtomicRef (SpiderHost x) where
2694− atomicModifyRef r = SpiderHost . atomicModifyRef r
2695−
2696−instance MonadRef (SpiderHostFrame x) where
2697− type Ref (SpiderHostFrame x) = Ref IO
2698− newRef = SpiderHostFrame . newRef
2699− readRef = SpiderHostFrame . readRef
2700− writeRef r = SpiderHostFrame . writeRef r
2701−
2702−instance MonadAtomicRef (SpiderHostFrame x) where
2703− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2704−
2705−instance PrimMonad (SpiderHostFrame x) where
2706− type PrimState (SpiderHostFrame x) = PrimState IO
2707− primitive = SpiderHostFrame . EventM . primitive
src/Reflex/Time.hsdeleted−384
@@ -1,384 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE DeriveTraversable #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RecursiveDo #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TupleSections #-}
10−{-# LANGUAGE TypeFamilies #-}
11−#ifdef USE_TEMPLATE_HASKELL
12−{-# LANGUAGE TemplateHaskell #-}
13−#endif
14−-- |
15−-- Module:
16−-- Reflex.Time
17−-- Description:
18−-- Clocks, timers, and other time-related functions.
19−module Reflex.Time where
20−
21−import Reflex.Class
22−import Reflex.Dynamic
23−import Reflex.PerformEvent.Class
24−import Reflex.PostBuild.Class
25−import Reflex.TriggerEvent.Class
26−
27−import Control.Concurrent
28−import qualified Control.Concurrent.Thread.Delay as Concurrent
29−import Control.Lens hiding ((|>))
30−import Control.Monad
31−import Control.Monad.Fix
32−import Control.Monad.IO.Class
33−import Data.Align
34−import Data.Data (Data)
35−import Data.Fixed
36−import Data.Semigroup (Semigroup(..))
37−import Data.Sequence (Seq, (|>))
38−import qualified Data.Sequence as Seq
39−import Data.These
40−import Data.Time.Clock
41−import Data.Typeable
42−import GHC.Generics (Generic)
43−import System.Random
44−
45−-- | Metadata associated with a timer "tick"
46−data TickInfo
47− = TickInfo { _tickInfo_lastUTC :: UTCTime
48− -- ^ UTC time immediately after the last tick.
49− , _tickInfo_n :: Integer
50− -- ^ Number of time periods or ticks since the start of the timer
51− , _tickInfo_alreadyElapsed :: NominalDiffTime
52− -- ^ Amount of time that has elapsed in the current tick period.
53− }
54− deriving (Eq, Ord, Show, Typeable)
55−
56−-- | Fires an 'Event' once every time provided interval elapses, approximately.
57−-- The provided 'UTCTime' is used bootstrap the determination of how much time has elapsed with each tick.
58−-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread.
59−tickLossy :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> UTCTime -> m (Event t TickInfo)
60−tickLossy dt t0 = tickLossyFrom dt t0 =<< getPostBuild
61−
62−-- | Fires an 'Event' once every time provided interval elapses, approximately.
63−-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread and the time of the post-build as the tick basis time.
64−tickLossyFromPostBuildTime :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> m (Event t TickInfo)
65−tickLossyFromPostBuildTime dt = do
66− postBuild <- getPostBuild
67− postBuildTime <- performEvent $ liftIO getCurrentTime <$ postBuild
68− tickLossyFrom' $ (dt,) <$> postBuildTime
69−
70−-- | Fires an 'Event' approximately each time the provided interval elapses. If the system starts running behind, occurrences will be dropped rather than buffered.
71−-- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the provided initial time.
72−tickLossyFrom
73− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
74− => NominalDiffTime
75− -- ^ The length of a tick interval
76− -> UTCTime
77− -- ^ The basis time from which intervals count and with which the initial calculation of elapsed time will be made.
78− -> Event t a
79− -- ^ Event that starts a tick generation thread. Usually you want this to
80− -- be something like the result of getPostBuild that only fires once. But
81− -- there could be uses for starting multiple timer threads.
82− -> m (Event t TickInfo)
83−tickLossyFrom dt t0 e = tickLossyFrom' $ (dt, t0) <$ e
84−
85−-- | Generalization of tickLossyFrom that takes the delay and initial time as an 'Event'.
86−tickLossyFrom'
87− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
88− => Event t (NominalDiffTime, UTCTime)
89− -- ^ Event that starts a tick generation thread. Usually you want this to
90− -- be something like the result of 'getPostBuild' that only fires once. But
91− -- there could be uses for starting multiple timer threads.
92− -> m (Event t TickInfo)
93−tickLossyFrom' e = do
94− rec result <- performEventAsync $ callAtNextInterval <$> leftmost [e, snd <$> result]
95− return $ fst <$> result
96− where callAtNextInterval pair cb = void $ liftIO $ forkIO $ do
97− tick <- uncurry getCurrentTick pair
98− Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000
99− cb (tick, pair)
100−
101−-- | Like 'tickLossy', but immediately calculates the first tick and provides a 'Dynamic' that is updated as ticks fire.
102−clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)
103−clockLossy dt t0 = do
104− initial <- liftIO $ getCurrentTick dt t0
105− e <- tickLossy dt t0
106− holdDyn initial e
107−
108−-- | Generates a 'TickInfo', given the specified interval and timestamp. The 'TickInfo' will include the
109−-- current time, the number of ticks that have elapsed since the timestamp, and the amount of time that
110−-- has elapsed since the start time of this tick.
111−getCurrentTick :: NominalDiffTime -> UTCTime -> IO TickInfo
112−getCurrentTick dt t0 = do
113− t <- getCurrentTime
114− let offset = t `diffUTCTime` t0
115− (n, alreadyElapsed) = offset `divMod'` dt
116− return $ TickInfo t n alreadyElapsed
117−
118−-- | Delay an Event's occurrences by a given amount in seconds.
119−delay :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
120−delay dt e = performEventAsync $ ffor e $ \a cb -> liftIO $ void $ forkIO $ do
121− Concurrent.delay $ ceiling $ dt * 1000000
122− cb a
123−
124−-- | Send events with Poisson timing with the given basis and rate
125−-- Each occurrence of the resulting event will contain the index of
126−-- the current interval, with 0 representing the basis time
127−poissonLossyFrom
128− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
129− => g
130− -> Double
131− -- ^ Poisson event rate (Hz)
132− -> UTCTime
133− -- ^ Baseline time for events
134− -> Event t a
135− -- ^ Event that starts a tick generation thread. Usually you want this to
136− -- be something like the result of getPostBuild that only fires once. But
137− -- there could be uses for starting multiple timer threads.
138− -- Start sending events in response to the event parameter.
139− -> m (Event t TickInfo)
140−poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate
141−
142−
143−-- | Send events with Poisson timing with the given basis and rate
144−-- Each occurrence of the resulting event will contain the index of
145−-- the current interval, with 0 representing the basis time.
146−-- Automatically begin sending events when the DOM is built
147−poissonLossy
148− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
149− => g
150− -> Double
151− -- ^ Poisson event rate (Hz)
152− -> UTCTime
153− -- ^ Baseline time for events
154− -> m (Event t TickInfo)
155−poissonLossy rnd rate t0 = poissonLossyFrom rnd rate t0 =<< getPostBuild
156−
157−-- | Send events with inhomogeneous Poisson timing with the given basis
158−-- and variable rate. Provide a maxRate that you expect to support.
159−inhomogeneousPoissonFrom
160− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
161− => g
162− -> Behavior t Double
163− -> Double
164− -> UTCTime
165− -> Event t a
166− -> m (Event t TickInfo)
167−inhomogeneousPoissonFrom rnd rate maxRate t0 e = do
168−
169− -- Create a thread for producing homogeneous poisson events
170− -- along with random Doubles (usage of Double's explained below)
171− ticksWithRateRand <- performEventAsync $
172− fmap callAtNextInterval e
173−
174− -- Filter homogeneous events according to associated
175− -- random values and the current rate parameter
176− return $ attachWithMaybe filterFun rate ticksWithRateRand
177−
178− where
179−
180− -- Inhomogeneous poisson processes are built from faster
181− -- homogeneous ones by randomly dropping events from the
182− -- fast process. For each fast homogeneous event, choose
183− -- a uniform random sample from (0, rMax). If the
184− -- inhomogeneous rate at this moment is greater than the
185− -- random sample, then keep this event, otherwise drop it
186− filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo
187− filterFun r (tInfo, p)
188− | r >= p = Just tInfo
189− | otherwise = Nothing
190−
191− callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0
192−
193− go tTargetLast lastGen cb lastN = do
194− t <- getCurrentTime
195−
196− -- Generate random numbers for this poisson interval (u)
197− -- and sample-retention likelihood (p)
198− let (u, nextGen) = randomR (0,1) lastGen
199− (p :: Double, nextGen') = randomR (0,maxRate) nextGen
200−
201− -- Inter-event interval is drawn from exponential
202− -- distribution accourding to u
203− let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime
204− nEvents = lastN + 1
205− alreadyElapsed = diffUTCTime t tTargetLast
206− tTarget = addUTCTime dt tTargetLast
207− thisDelay = realToFrac $ diffUTCTime tTarget t :: Double
208− Concurrent.delay $ ceiling $ thisDelay * 1000000
209− _ <- cb (TickInfo t nEvents alreadyElapsed, p)
210− go tTarget nextGen' cb nEvents
211−
212−-- | Send events with inhomogeneous Poisson timing with the given basis
213−-- and variable rate. Provide a maxRate that you expect to support
214−inhomogeneousPoisson
215− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
216− => g
217− -> Behavior t Double
218− -> Double
219− -> UTCTime
220− -> m (Event t TickInfo)
221−inhomogeneousPoisson rnd rate maxRate t0 =
222− inhomogeneousPoissonFrom rnd rate maxRate t0 =<< getPostBuild
223−
224−-- | Block occurrences of an Event until the given number of seconds elapses without
225−-- the Event firing, at which point the last occurrence of the Event will fire.
226−debounce :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
227−debounce dt e = do
228− n :: Dynamic t Integer <- count e
229− let tagged = attachPromptlyDynWith (,) n e
230− delayed <- delay dt tagged
231− return $ attachWithMaybe (\n' (t, v) -> if n' == t then Just v else Nothing) (current n) delayed
232−
233−-- | When the given 'Event' occurs, wait the given amount of time and collect
234−-- all occurrences during that time. Then, fire the output 'Event' with the
235−-- collected output.
236−batchOccurrences :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t (Seq a))
237−batchOccurrences t newValues = do
238− let f s x = (Just newState, out)
239− where newState = case x of
240− This a -> s |> a
241− That _ -> mempty
242− These a _ -> Seq.singleton a
243− out = case x of
244− This _ -> if Seq.null s then Just () else Nothing
245− That _ -> Nothing
246− These _ _ -> Just ()
247− rec (buffer, toDelay) <- mapAccumMaybe f mempty $ align newValues delayed
248− delayed <- delay t toDelay
249− return $ tag buffer delayed
250−
251−-- | Throttle an input event, ensuring that at least a given amount of time passes between occurrences of the output event. If the input event occurs too
252−-- frequently, the output event occurs with the most recently seen input value after the given delay passes since the last occurrence of the output.
253−-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
254−throttle :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
255−throttle t e = do
256− let f (immediate, buffer) x = case x of -- (Just newState, out)
257− This a -- If only the input event fires
258− | immediate -> -- and we're in immediate mode
259− -- Immediate mode turns off, and the buffer is empty.
260− -- We fire the output event with the input event value immediately.
261− (Just (False, Nothing), Just a)
262− | otherwise -> -- and we're not in immediate mode
263− -- Immediate mode remains off, and we replace the contents of the buffer (if any) with the input value.
264− -- We don't fire the output event.
265− (Just (False, Just a), Nothing)
266− That _ -> -- If only the delayed output event fires,
267− case buffer of
268− Nothing -> -- and the buffer is empty:
269− -- Immediate mode turns back on, and the buffer remains empty.
270− -- We don't fire.
271− (Just (True, Nothing), Nothing)
272− Just b -> -- and the buffer is full:
273− -- Immediate mode remains off, and the buffer is cleared.
274− -- We fire with the buffered value.
275− (Just (False, Nothing), Just b)
276− These a _ -> -- If both the input and delayed output event fire simultaneously:
277− -- Immediate mode turns off, and the buffer is empty.
278− -- We fire with the input event's value, as it is the most recent we have seen at this moment.
279− (Just (False, Nothing), Just a)
280− rec (_, outE) <- mapAccumMaybeDyn f (True, Nothing) $ align e delayed -- We start in immediate mode with an empty buffer.
281− delayed <- delay t outE
282− return outE
283−
284−data ThrottleState b
285− = ThrottleState_Immediate
286− | ThrottleState_Buffered (ThrottleBuffer b)
287− deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
288−
289−data ThrottleBuffer b
290− = ThrottleBuffer_Empty -- Empty conflicts with lens, and hiding it would require turning
291− -- on PatternSynonyms
292− | ThrottleBuffer_Full b
293− deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
294−
295−instance Semigroup b => Semigroup (ThrottleBuffer b) where
296− x <> y = case x of
297− ThrottleBuffer_Empty -> y
298− ThrottleBuffer_Full b1 -> case y of
299− ThrottleBuffer_Empty -> x
300− ThrottleBuffer_Full b2 -> ThrottleBuffer_Full $ b1 <> b2
301− {-# INLINE (<>) #-}
302−
303−instance Semigroup b => Monoid (ThrottleBuffer b) where
304− mempty = ThrottleBuffer_Empty
305− {-# INLINE mempty #-}
306− mappend = (<>)
307− {-# INLINE mappend #-}
308−
309−-- | Throttle an input event, ensuring that the output event doesn't occur more often than you are ready for it. If the input event occurs too
310−-- frequently, the output event will contain semigroup-based summaries of the input firings that happened since the last output firing.
311−-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
312−-- The first parameter is a function that receives access to the output event, and should construct an event that fires when the receiver is
313−-- ready for more input. For example, using @delay 20@ would give a simple time-based throttle.
314−--
315−-- NB: The provided lag function must *actually* delay the event.
316−throttleBatchWithLag :: (MonadFix m, MonadHold t m, PerformEvent t m, Semigroup a) => (Event t () -> m (Event t ())) -> Event t a -> m (Event t a)
317−-- Invariants:
318−-- * Immediate mode must turn off whenever output is produced.
319−-- * Output must be produced whenever immediate mode turns from on to off.
320−-- * Immediate mode can only go from off to on when the delayed event fires.
321−-- * Every input firing must go into either an immediate output firing or the
322−-- buffer, but not both.
323−-- * An existing full buffer must either stay in the buffer or go to output,
324−-- but not both.
325−throttleBatchWithLag lag e = do
326− let f state x = case x of -- (Just $ newState, out)
327− This a -> -- If only the input event fires
328− case state of
329− ThrottleState_Immediate -> -- and we're in immediate mode
330− -- Immediate mode turns off, and the buffer is empty.
331− -- We fire the output event with the input event value immediately.
332− (Just $ ThrottleState_Buffered $ ThrottleBuffer_Empty, Just a)
333− ThrottleState_Buffered b -> -- and we're not in immediate mode
334− -- Immediate mode remains off, and we accumulate the input value.
335− -- We don't fire the output event.
336− (Just $ ThrottleState_Buffered $ b <> ThrottleBuffer_Full a, Nothing)
337− That _ -> -- If only the delayed output event fires,
338− case state of
339− ThrottleState_Immediate -> -- and we're in immediate mode
340− -- Nothing happens.
341− (Nothing, Nothing)
342− ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
343− -- Immediate mode turns back on, and the buffer remains empty.
344− -- We don't fire.
345− (Just ThrottleState_Immediate, Nothing)
346− ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
347− -- Immediate mode remains off, and the buffer is cleared.
348− -- We fire with the buffered value.
349− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just b)
350− These a _ -> -- If both the input and delayed output event fire simultaneously:
351− case state of
352− ThrottleState_Immediate -> -- and we're in immediate mode
353− -- Immediate mode turns off, and the buffer is empty.
354− -- We fire with the input event's value, as it is the most recent we have seen at this moment.
355− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
356− ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
357− -- Immediate mode stays off, and the buffer remains empty.
358− -- We fire with the input event's value.
359− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
360− ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
361− -- Immediate mode remains off, and the buffer is cleared.
362− -- We fire with everything including the buffered value.
363− (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just (b <> a))
364− rec (_stateDyn, outE) <- mapAccumMaybeDyn f
365− ThrottleState_Immediate -- We start in immediate mode with an empty buffer.
366− (align e delayed)
367− delayed <- lag (void outE)
368− return outE
369−
370−#ifdef USE_TEMPLATE_HASKELL
371−makeLensesWith (lensRules & simpleLenses .~ True) ''TickInfo
372−#else
373−tickInfo_lastUTC :: Lens' TickInfo UTCTime
374−tickInfo_lastUTC f (TickInfo x1 x2 x3) = (\y -> TickInfo y x2 x3) <$> f x1
375−{-# INLINE tickInfo_lastUTC #-}
376−
377−tickInfo_n :: Lens' TickInfo Integer
378−tickInfo_n f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 y x3) <$> f x2
379−{-# INLINE tickInfo_n #-}
380−
381−tickInfo_alreadyElapsed :: Lens' TickInfo NominalDiffTime
382−tickInfo_alreadyElapsed f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 x2 y) <$> f x3
383−{-# INLINE tickInfo_alreadyElapsed #-}
384−#endif
src/Reflex/TriggerEvent/Base.hsdeleted−148
@@ -1,148 +0,0 @@
1−-- | This module defines 'TriggerEventT', the standard implementation of
2−-- 'TriggerEvent'.
3−{-# LANGUAGE DeriveFunctor #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE TypeFamilies #-}
8−module Reflex.TriggerEvent.Base
9− ( TriggerEventT (..)
10− , runTriggerEventT
11− , askEvents
12− , TriggerInvocation (..)
13− , EventTriggerRef (..)
14− ) where
15−
16−import Control.Applicative (liftA2)
17−import Control.Concurrent
18−import Control.Monad.Exception
19−import Control.Monad.Primitive
20−import Control.Monad.Reader
21−import Control.Monad.Ref
22−import Data.Coerce
23−import Data.Dependent.Sum
24−import Data.IORef
25−import Data.Monoid ((<>))
26−import qualified Data.Semigroup as S
27−import Reflex.Class
28−import Reflex.Adjustable.Class
29−import Reflex.Host.Class
30−import Reflex.PerformEvent.Class
31−import Reflex.PostBuild.Class
32−import Reflex.TriggerEvent.Class
33−
34−-- | A value with which to fire an 'Event', as well as a callback to invoke
35−-- after its propagation has completed.
36−data TriggerInvocation a = TriggerInvocation a (IO ())
37−
38−-- | A reference to an 'EventTrigger' suitable for firing with 'TriggerEventT'.
39−newtype EventTriggerRef t a = EventTriggerRef { unEventTriggerRef :: IORef (Maybe (EventTrigger t a)) }
40−
41−-- | A basic implementation of 'TriggerEvent'.
42−newtype TriggerEventT t m a = TriggerEventT { unTriggerEventT :: ReaderT (Chan [DSum (EventTriggerRef t) TriggerInvocation]) m a }
43− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
44−
45−-- | Run a 'TriggerEventT' action. The argument should be a 'Chan' into which
46−-- 'TriggerInvocation's can be passed; it is expected that some other thread
47−-- will be responsible for popping values out of the 'Chan' and firing their
48−-- 'EventTrigger's.
49−runTriggerEventT :: TriggerEventT t m a -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a
50−runTriggerEventT = runReaderT . unTriggerEventT
51−
52−instance MonadTrans (TriggerEventT t) where
53− {-# INLINABLE lift #-}
54− lift = TriggerEventT . lift
55−
56−instance PrimMonad m => PrimMonad (TriggerEventT t m) where
57− type PrimState (TriggerEventT t m) = PrimState m
58− {-# INLINABLE primitive #-}
59− primitive = lift . primitive
60−
61−instance PerformEvent t m => PerformEvent t (TriggerEventT t m) where
62− type Performable (TriggerEventT t m) = Performable m
63− {-# INLINABLE performEvent_ #-}
64− performEvent_ e = lift $ performEvent_ e
65− {-# INLINABLE performEvent #-}
66− performEvent e = lift $ performEvent e
67−
68−instance PostBuild t m => PostBuild t (TriggerEventT t m) where
69− {-# INLINABLE getPostBuild #-}
70− getPostBuild = lift getPostBuild
71−
72−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (TriggerEventT t m) where
73− {-# INLINABLE newEventWithTrigger #-}
74− newEventWithTrigger = lift . newEventWithTrigger
75− {-# INLINABLE newFanEventWithTrigger #-}
76− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
77−
78−instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (TriggerEventT t m) where
79− {-# INLINABLE newTriggerEvent #-}
80− newTriggerEvent = do
81− (e, t) <- newTriggerEventWithOnComplete
82− return (e, \a -> t a $ return ())
83− {-# INLINABLE newTriggerEventWithOnComplete #-}
84− newTriggerEventWithOnComplete = do
85− events <- askEvents
86− (eResult, reResultTrigger) <- lift newEventWithTriggerRef
87− return . (,) eResult $ \a cb ->
88− writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
89− {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
90− newEventWithLazyTriggerWithOnComplete f = do
91− events <- askEvents
92− lift . newEventWithTrigger $ \t ->
93− f $ \a cb -> do
94− reResultTrigger <- newRef $ Just t
95− writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
96−
97−instance MonadRef m => MonadRef (TriggerEventT t m) where
98− type Ref (TriggerEventT t m) = Ref m
99− {-# INLINABLE newRef #-}
100− newRef = lift . newRef
101− {-# INLINABLE readRef #-}
102− readRef = lift . readRef
103− {-# INLINABLE writeRef #-}
104− writeRef r = lift . writeRef r
105−
106−instance MonadAtomicRef m => MonadAtomicRef (TriggerEventT t m) where
107− {-# INLINABLE atomicModifyRef #-}
108− atomicModifyRef r = lift . atomicModifyRef r
109−
110−instance MonadSample t m => MonadSample t (TriggerEventT t m) where
111− {-# INLINABLE sample #-}
112− sample = lift . sample
113−
114−instance MonadHold t m => MonadHold t (TriggerEventT t m) where
115− {-# INLINABLE hold #-}
116− hold v0 v' = lift $ hold v0 v'
117− {-# INLINABLE holdDyn #-}
118− holdDyn v0 v' = lift $ holdDyn v0 v'
119− {-# INLINABLE holdIncremental #-}
120− holdIncremental v0 v' = lift $ holdIncremental v0 v'
121− {-# INLINABLE buildDynamic #-}
122− buildDynamic a0 = lift . buildDynamic a0
123− {-# INLINABLE headE #-}
124− headE = lift . headE
125−
126−instance Adjustable t m => Adjustable t (TriggerEventT t m) where
127− {-# INLINABLE runWithReplace #-}
128− runWithReplace (TriggerEventT a0) a' = TriggerEventT $ runWithReplace a0 (coerceEvent a')
129− {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
130− traverseIntMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseIntMapWithKeyWithAdjust (coerce . f) dm0 dm'
131− {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
132− traverseDMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
133− {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}
134− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
135−
136−-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
137−instance (Monoid a, Applicative m) => Monoid (TriggerEventT t m a) where
138− mempty = pure mempty
139− mappend = (<>)
140−
141−instance (S.Semigroup a, Applicative m) => S.Semigroup (TriggerEventT t m a) where
142− (<>) = liftA2 (S.<>)
143−
144−
145−-- | Retrieve the current 'Chan'; event trigger invocations pushed into it will
146−-- be fired.
147−askEvents :: Monad m => TriggerEventT t m (Chan [DSum (EventTriggerRef t) TriggerInvocation])
148−askEvents = TriggerEventT ask
src/Reflex/TriggerEvent/Class.hsdeleted−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 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−8
@@ -1,7 +1,7 @@
11module Main where
22
33import Control.Monad
4−import Language.Haskell.HLint3 (hlint)
4+import Language.Haskell.HLint (hlint)
55import System.Directory
66import System.Exit (exitFailure, exitSuccess)
77import System.FilePath
@@ -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
@@ -30,16 +31,9 @@ main = do
3031 ]
3132 matchFile = and <$> sequence
3233 [ extension ==? ".hs"
33− , let notElem' = liftOp notElem
34− in filePath `notElem'` filePathExceptions pwd
3534 ]
3635 files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
3736 ideas <- fmap concat $ forM files $ \f -> do
3837 putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
3938 runHlint f
4039 if null ideas then exitSuccess else exitFailure
41−
42−filePathExceptions :: FilePath -> [FilePath]
43−filePathExceptions pwd = map (pwd </>) $
44− [ "src/Data/AppendMap.hs" -- parse error when hlint runs
45− ]
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