on 0071805 help sign in
90 files changed+13948−1484
since splitsnapshots
unifiedsplit
.github/workflows/haskell.yml−47 .travis.yml+169 CONTRIBUTING.md+2−6 ChangeLog.md+26−51 Quickref.md+311 README.md+14−41 bench/Main.hs+110 bench/RunAll.hs+157 cabal.haskell-ci+7 default.nix+42 dep/reflex-platform/default.nix−8 dep/reflex-platform/github.json−8 hydra.json+29 jobsets.nix+70 patch.cabal−100 reflex-platform.nix+8 reflex.cabal+398 release.nix+7−47 src/Data/AppendMap.hs+80 src/Data/FastMutableIntMap.hs+93 src/Data/FastWeakBag.hs+156 src/Data/Functor/Misc.hs+7−4 src/Data/Map/Misc.hs+71 src/Data/Monoid/DecidablyEmpty.hs−115 src/Data/Patch.hs−95 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+1655 src/Reflex/Collection.hs+222 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+30 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/Data/Patch/Class.hs → src/Reflex/Patch/Class.hs+3−14 src/Data/Patch/DMap.hs → src/Reflex/Patch/DMap.hs+5−16 src/Data/Patch/DMapWithMove.hs → src/Reflex/Patch/DMapWithMove.hs+12−20 src/Data/Patch/IntMap.hs → src/Reflex/Patch/IntMap.hs+14−31 src/Data/Patch/Map.hs → src/Reflex/Patch/Map.hs+21−38 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+223 src/Reflex/Pure.hs+210 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+2681 src/Reflex/Time.hs+384 src/Reflex/TriggerEvent/Base.hs+148 src/Reflex/TriggerEvent/Class.hs+50 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+369 test/Reflex/Plan/Pure.hs+72 test/Reflex/Plan/Reflex.hs+135 test/Reflex/Test.hs+66 test/Reflex/Test/CrossImpl.hs+257 test/Reflex/Test/Micro.hs+346 test/Reflex/TestPlan.hs+52 test/RequesterT.hs+174 test/Test/Run.hs+74 test/hlint.hs+8−2 test/rootCleanup.hs+25 test/semantics.hs+47 test/tests.hs−43
.github/workflows/haskell.ymldeleted−47
@@ -1,47 +0,0 @@
1−name: github-action
2−
3−on: [push, pull_request]
4−
5−jobs:
6− build:
7− strategy:
8− matrix:
9− ghc: ['8.0.2', '8.2.2', '8.4.4', '8.6.5', '8.8.4', '8.10.2']
10− os: ['ubuntu-latest', 'macos-latest']
11− exclude:
12− # There are some linker warnings in 802 on darwin that
13− # cause compilation to fail
14− # See https://github.com/NixOS/nixpkgs/issues/25139
15− - ghc: '8.0.2'
16− os: 'macos-latest'
17− runs-on: ${{ matrix.os }}
18−
19− name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20− steps:
21− - uses: actions/checkout@v2
22− - uses: actions/setup-haskell@v1
23− with:
24− ghc-version: ${{ matrix.ghc }}
25− - name: Cache
26− uses: actions/cache@v1
27− env:
28− cache-name: cache-cabal
29− with:
30− path: ~/.cabal
31− key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32− restore-keys: |
33− ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34− ${{ runner.os }}-${{ matrix.ghc }}-build-
35− ${{ runner.os }}-${{ matrix.ghc }}-
36− ${{ runner.os }}
37−
38− - name: Install dependencies
39− run: |
40− cabal update
41− cabal build --only-dependencies --enable-tests --enable-benchmarks
42− - name: Build
43− run: cabal build --enable-tests --enable-benchmarks all
44− - name: Run tests
45− run: cabal test --enable-tests all
46− - name: Build Docs
47− run: cabal haddock
.travis.ymlnew file+169
@@ -0,0 +1,169 @@
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.20190804.2
8+#
9+language: c
10+dist: bionic
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":["ghcjs-8.4","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/ghc;
44+ sudo add-apt-repository -y ppa:hvr/ghcjs;
45+ sudo apt-get update;
46+ sudo apt-get install $CC cabal-install-3.0;
47+ fi
48+ - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//')
49+ - WITHCOMPILER="-w $HC"
50+ - |
51+ if echo $CC | grep -q ghcjs; then
52+ GHCJS=true
53+ HC=${HC}js
54+ WITHCOMPILER="--ghcjs ${WITHCOMPILER}js"
55+ else
56+ GHCJS=false;
57+ fi
58+ - if $GHCJS ; then sudo apt-get install -y ghc-8.6.5 ; fi
59+ - if $GHCJS ; then PATH="/opt/ghc/8.6.5/bin:$PATH" ; fi
60+ - HCPKG="$HC-pkg"
61+ - unset CC
62+ - CABAL=/opt/ghc/bin/cabal
63+ - CABALHOME=$HOME/.cabal
64+ - export PATH="$CABALHOME/bin:$PATH"
65+ - TOP=$(pwd)
66+ - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')"
67+ - echo $HCNUMVER
68+ - CABAL="$CABAL -vnormal+nowrap+markoutput"
69+ - set -o pipefail
70+ - |
71+ echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk
72+ echo 'BEGIN { state = "output"; }' >> .colorful.awk
73+ echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk
74+ echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk
75+ echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk
76+ echo ' if (state == "cabal") {' >> .colorful.awk
77+ echo ' print blue($0)' >> .colorful.awk
78+ echo ' } else {' >> .colorful.awk
79+ echo ' print $0' >> .colorful.awk
80+ echo ' }' >> .colorful.awk
81+ echo '}' >> .colorful.awk
82+ - cat .colorful.awk
83+ - |
84+ color_cabal_output () {
85+ awk -f $TOP/.colorful.awk
86+ }
87+ - echo text | color_cabal_output
88+install:
89+ - ${CABAL} --version
90+ - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"
91+ - node --version
92+ - echo $GHCJS
93+ - TEST=--enable-tests
94+ - BENCH=--enable-benchmarks
95+ - HEADHACKAGE=false
96+ - rm -f $CABALHOME/config
97+ - |
98+ echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config
99+ echo "remote-build-reporting: anonymous" >> $CABALHOME/config
100+ echo "write-ghc-environment-files: always" >> $CABALHOME/config
101+ echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config
102+ echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config
103+ echo "world-file: $CABALHOME/world" >> $CABALHOME/config
104+ echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config
105+ echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config
106+ echo "installdir: $CABALHOME/bin" >> $CABALHOME/config
107+ echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config
108+ echo "store-dir: $CABALHOME/store" >> $CABALHOME/config
109+ echo "install-dirs user" >> $CABALHOME/config
110+ echo " prefix: $CABALHOME" >> $CABALHOME/config
111+ echo "repository hackage.haskell.org" >> $CABALHOME/config
112+ echo " url: http://hackage.haskell.org/" >> $CABALHOME/config
113+ - cat $CABALHOME/config
114+ - rm -fv cabal.project cabal.project.local cabal.project.freeze
115+ - travis_retry ${CABAL} v2-update -v
116+ - if $GHCJS ; then (cd /tmp && ${CABAL} v2-install -w ghc-8.6.5 happy) ; fi
117+ # Generate cabal.project
118+ - rm -rf cabal.project cabal.project.local cabal.project.freeze
119+ - touch cabal.project
120+ - |
121+ echo "packages: ." >> cabal.project
122+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(reflex)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done"
123+ - cat cabal.project || true
124+ - cat cabal.project.local || true
125+ - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi
126+ - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output
127+ - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'"
128+ - rm cabal.project.freeze
129+script:
130+ - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)
131+ # Packaging...
132+ - ${CABAL} v2-sdist all | color_cabal_output
133+ # Unpacking...
134+ - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/
135+ - cd ${DISTDIR} || false
136+ - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \;
137+ - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \;
138+ - PKGDIR_reflex="$(find . -maxdepth 1 -type d -regex '.*/reflex-[0-9.]*')"
139+ # Generate cabal.project
140+ - rm -rf cabal.project cabal.project.local cabal.project.freeze
141+ - touch cabal.project
142+ - |
143+ echo "packages: ${PKGDIR_reflex}" >> cabal.project
144+ - |
145+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(reflex)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done"
146+ - cat cabal.project || true
147+ - cat cabal.project.local || true
148+ # Building...
149+ # this builds all libraries and executables (without tests/benchmarks)
150+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all | color_cabal_output
151+ # Building with tests and benchmarks...
152+ # build & run tests, build benchmarks
153+ - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output
154+ # Testing...
155+ - if ! $GHCJS && [ $HCNUMVER -ge 80000 ] && [ $HCNUMVER -lt 80606 ] ; then ${CABAL} v2-test $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output ; fi
156+ # cabal check...
157+ - (cd ${PKGDIR_reflex} && ${CABAL} -vnormal check)
158+ # haddock...
159+ - if ! $GHCJS && [ $HCNUMVER -ge 80000 ] && [ $HCNUMVER -lt 80606 ] ; then ${CABAL} v2-haddock $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output ; fi
160+ # Building without installed constraints for packages in global-db...
161+ - rm -f cabal.project.local
162+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all | color_cabal_output
163+ # Constraint sets
164+ - rm -rf cabal.project.local
165+ # Constraint set no-th
166+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --constraint='reflex -use-template-haskell' all | color_cabal_output
167+
168+# REGENDATA ["--config=cabal.haskell-ci","cabal.project"]
169+# EOF
CONTRIBUTING.md+2−6
@@ -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 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.
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.
2020
2121## Submitting Changes
2222
@@ -45,10 +45,6 @@ Your pull request should add no new warnings to the project. It should also gene
4545
4646Make sure the project builds and that the tests pass! This will generally also be checked by CI before merge, but trying it yourself first means you'll catch problems earlier and your contribution can be merged that much sooner!
4747
48−#### Dependencies
49−
50−Include version bounds whenever adding a dependency to the library stanza of the cabal file. Note that libraries added to patch.cabal also need to be added to default.nix.
51−
5248### Documentation
5349
5450#### In the code
ChangeLog.md+26−51
@@ -1,61 +1,36 @@
1−# Revision history for patch
1+# Revision history for reflex
22
3−## Unreleased
3+## 0.6.2.1
44
5−* New dep of `data-orphans` for old GHC to get instances honestly instead of
6− via `monoidal-containers`.
5+* Generalize `fan` to `fanG` to take a `DMap` with non-`Identity`
6+ values.
77
8−## 0.0.5.0 - 2021-12-17
8+* Generalize merging functions:
9+ `merge` to `mergeG`,
10+ `mergeIncremental` to `mergeIncrementalG`,
11+ `distributeDMapOverDynPure` to `distributeDMapOverDynPureG`,
12+ `mergeIncrementalWithMove` to `mergeIncrementalWithMoveG`.
913
10−* `Additive` now lives in `Data.Semigroup.Additive`, but is still reexported
11− from `Data.Patch` for compatability.
1214
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.
15+## 0.6.2.0
1816
19−## 0.0.4.0 - 2021-04-20
17+* Fix `holdDyn` so that it is lazy in its event argument
18+ These produce `DMap`s whose values needn't be `Identity`.
19+* Stop using the now-deprecated `*Tag` classes (e.g., `ShowTag`).
20+* Fix `holdDyn` so that it is lazy in its event argument.
2021
21−* Enable PolyKinds
22+## 0.6.1.0
2223
23−## 0.0.3.2 - 2020-11-06
24+* Re-export all of `Data.Map.Monoidal`
25+* Fix `QueryT` and `RequesterT` tests
2426
25−* Update version bounds
27+## 0.6.0.0 -- 2019-03-20
2628
27−## 0.0.3.1 - 2020-02-05
28−
29−* Replace `fromJust` with something easier to debug.
30−
31−## 0.0.3.0 - 2020-02-05
32−
33−* Create `PatchMapWithPatchingMove` variant which supports moves with a patch.
34−
35−* Create `DecidablyEmpty` subclass of `Monoid`.
36−
37−## 0.0.2.0 - 2020-01-17
38−
39−* Consistently provide:
40−
41− - `Wrapped` instances
42−
43− - `*WithIndex` instances
44−
45− - `un*` newtype unwrappers
46−
47− for `PatchMap`, `PatchIntMap`, and `PatchMapWithMove`.
48−
49−## 0.0.1.0 - 2020-01-09
50−
51−* Support older GHCs with `split-these` flag.
52−
53−* Additional instances for the `Group` class for basic types.
54−
55−## 0.0.0.1 - 2020-01-08
56−
57−* Remove unneeded dependencies
58−
59−## 0.0.0.0 - 2020-01-08
60−
61−* Extract patching functionality from Reflex.
29+* Deprecate `FunctorMaybe` in favor of `Data.Witherable.Filterable`. We still export `fmapMaybe`, `ffilter`, etc., but they all rely on `Filterable` now.
30+* Rename `MonadDynamicWriter` to `DynamicWriter` and add a deprecation for the old name.
31+* Remove many deprecated functions.
32+* Add a `Num` instance for `Dynamic`.
33+* Add `matchRequestsWithResponses` to make it easier to use `Requester` with protocols that don't do this matching for you.
34+* Add `withRequesterT` to map functions over the request and response of a `RequesterT`.
35+* Suppress nil patches in `QueryT` as an optimization. The `Query` type must now have an `Eq` instance.
36+* Add `throttleBatchWithLag` to `Reflex.Time`. See that module for details.
Quickref.mdnew file+311
@@ -0,0 +1,311 @@
1+# Reflex Quick(ish) Reference
2+
3+## Typeclasses
4+
5+Many Reflex functions operate in monadic context `m a`, where the monad 'm' supports various additional typeclasses such as MonadWidget, MonadHold, or MonadSample in addition to Monad itself. The actual 'm' in use will be determined by the top-level entry point of the FRP host (such as Reflex-Dom -- see the bottom of the Reflex-Dom quick reference for details).
6+
7+The function signatures here have been simplified by removing many typeclass constraints and adding simple annotations to each function. Also the ubiquitous 't' type parameter has been removed.
8+
9+Some of these functions are *pure*: They operate on Events, Behaviors, or Dynamics uniformly without regard to the "current time". Other functions must operate in some monadic context, because they produce a result "as of now" (e.g., any function that takes an "initial" value, or returns a "current" value). Annotations are used to distinguish these cases:
10+
11+```haskell
12+[ ] -- Pure function
13+[S] -- Function runs in any monad supporting MonadSample
14+[H] -- Function runs in any monad supporting MonadHold
15+```
16+Since MonadHold depends on MonadSample, any [S] function also runs in [H] context.
17+
18+## Functions producing Event
19+
20+```haskell
21+-- Trivial Event
22+[ ] never :: Event a
23+
24+-- Extract Event from Dynamic
25+[ ] updated :: Dynamic a -> Event a
26+
27+-- Transform Event to Event using function
28+[ ] fmap :: (a -> b) -> Event a -> Event b
29+[ ] fmapMaybe :: (a -> Maybe b) -> Event a -> Event b
30+[ ] ffilter :: (a -> Bool) -> Event a -> Event a
31+[ ] ffor :: Event a -> (a -> b) -> Event b
32+[ ] fforMaybe :: Event a -> (a -> Maybe b) -> Event b
33+[ ] <$ :: a -> Event b -> Event a
34+
35+-- Event to identical Event with debug trace. (Only prints if Event is ultimately used.)
36+[ ] traceEvent :: Show a => String -> Event a -> Event a
37+[ ] traceEventWith :: (a -> String) -> Event a -> Event a
38+
39+-- Transform Event to Event by sampling Behavior or Dynamic
40+[ ] gate :: Behavior Bool -> Event a -> Event a
41+[ ] tag :: Behavior a -> Event b -> Event a
42+[ ] tagPromptlyDyn :: Dynamic a -> Event b -> Event a
43+[ ] attach :: Behavior a -> Event b -> Event (a, b)
44+[ ] attachPromptlyDyn :: Dynamic a -> Event b -> Event (a, b)
45+[ ] attachWith :: (a -> b -> c) -> Behavior a -> Event b -> Event c
46+[ ] attachPromptlyDynWith :: (a -> b -> c) -> Dynamic a -> Event b -> Event c
47+[ ] attachWithMaybe :: (a -> b -> Maybe c) -> Behavior a -> Event b -> Event c
48+[ ] attachPromptlyDynWithMaybe :: (a -> b -> Maybe c) -> Dynamic a -> Event b -> Event c
49+[ ] <@> :: Behavior (a -> b) -> Event a -> Event b
50+[ ] <@ :: Behavior a -> Event b -> Event a
51+
52+-- Combine multiple Events
53+[ ] <> :: Semigroup a => Event a -> Event a -> Event a
54+[ ] difference :: Event a -> Event b -> Event a
55+[ ] align :: Event a -> Event b -> Event (These a b)
56+[ ] alignWith :: (These a b -> c) -> Event a -> Event b -> Event c
57+[ ] mergeWith :: (a -> a -> a) -> [Event a] -> Event a
58+[ ] leftmost :: [Event a] -> Event a
59+[ ] mergeList :: [Event a] -> Event (NonEmpty a)
60+[ ] merge :: GCompare k => DMap k Event -> Event (DMap k Identity)
61+[ ] mergeMap :: Ord k => Map k (Event a) -> Event (Map k a)
62+
63+-- Efficient one-to-many fanout
64+[ ] fanMap :: Ord k => Event (Map k a) -> EventSelector (Const2 k a)
65+[ ] fan :: GCompare k => Event (DMap k Identity) -> EventSelector k
66+[ ] select :: EventSelector k -> k a -> Event a
67+[ ] fanEither :: Event (Either a b) -> (Event a, Event b)
68+[ ] fanThese :: Event (These a b) -> (Event a, Event b)
69+
70+-- Event to Event via function that can sample current values
71+[ ] push :: (a -> m (Maybe b)) -> Event a -> Event b
72+[ ] pushAlways :: (a -> m b ) -> Event a -> Event b
73+ -- Note supplied function operates in [H] context
74+
75+-- Split Event into next occurrence and all other future occurrences, as of now.
76+[H] headE :: Event a -> m (Event a)
77+[H] tailE :: Event a -> m (Event a)
78+[H] headTailE :: Event a -> m (Event a, Event a)
79+```
80+
81+## Functions producing Behavior
82+
83+```haskell
84+-- Trivial Behavior
85+[ ] constant :: a -> Behavior a
86+
87+-- Extract Behavior from Dynamic
88+[ ] current :: Dynamic a -> Behavior a
89+
90+-- Create Behavior with given initial value, updated when the Event fires.
91+[H] hold :: a -> Event a -> m (Behavior a)
92+
93+-- Transform Behavior to Behavior using function
94+[ ] fmap :: (a -> b) -> Behavior a -> Behavior b
95+[ ] ffor :: Behavior a -> (a -> b) -> Behavior b
96+[ ] <*> :: Behavior (a -> b) -> Behavior a -> Behavior b
97+[ ] >>= :: Behavior a -> (a -> Behavior b) -> Behavior b
98+[ ] <> :: Monoid a => Behavior a -> Behavior a -> Behavior a
99+-- ... plus many more due to typeclass membership
100+
101+-- Combine multiple behaviors via applicative instance
102+[ ] ffor2 :: Behavior a -> Behavior b -> (a -> b -> c) -> Behavior c
103+[ ] ffor3 :: Behavior a -> Behavior b -> Behavior c -> (a -> b -> c -> d) -> Behavior d
104+
105+-- Behavior to Behavior by sampling current values
106+[S] sample :: Behavior a -> m a
107+[ ] pull :: m a -> Behavior a
108+ -- Note supplied value is in [S] context
109+```
110+
111+## Functions producing Dynamic
112+
113+```haskell
114+-- Trivial Dynamic
115+[ ] constDyn :: a -> Dynamic a
116+
117+-- Create Dynamic with given initial value, updated (various ways) when the Event fires.
118+[H] holdDyn :: a -> Event a -> m (Dynamic a)
119+[H] foldDyn :: (a -> b -> b ) -> b -> Event a -> m (Dynamic b)
120+[H] foldDynMaybe :: (a -> b -> Maybe b ) -> b -> Event a -> m (Dynamic b)
121+[H] foldDynM :: (a -> b -> m' b ) -> b -> Event a -> m (Dynamic b)
122+[H] foldDynMaybeM :: (a -> b -> m' (Maybe b)) -> b -> Event a -> m (Dynamic b)
123+ -- Note m' supplies [H] context
124+
125+-- Initial value is 0; counts Event firings from now.
126+[H] count :: Num b => Event a -> m (Dynamic b)
127+-- Initial Bool value is supplied; toggles at each Event firing.
128+[H] toggle :: Bool -> Event a -> m (Dynamic Bool)
129+
130+-- Transform Dynamic to Dynamic using function
131+[ ] ffor :: Dynamic a -> (a -> b) -> Dynamic b
132+[ ] fmap :: (a -> b) -> Dynamic a -> Dynamic b
133+[ ] splitDynPure :: Dynamic (a, b) -> (Dynamic a, Dynamic b)
134+
135+-- Combine multiple Dynamics
136+[ ] mconcat :: Monoid a => [Dynamic a] -> Dynamic a
137+[ ] distributeDMapOverDynPure :: GCompare k => DMap (WrapArg Dynamic k) -> Dynamic (DMap k)
138+[ ] <*> :: Dynamic (a -> b) -> Dynamic a -> Dynamic b
139+[ ] >>= :: Dynamic a -> (a -> Dynamic b) -> Dynamic b
140+[ ] zipDynWith :: (a -> b -> c) -> Dynamic a -> Dynamic b -> Dynamic c
141+
142+-- Combine multiple dynamics via applicative instance
143+[ ] ffor2 :: Dynamic a -> Dynamic b -> (a -> b -> c) -> Dynamic c
144+[ ] ffor3 :: Dynamic a -> Dynamic b -> Dynamic c -> (a -> b -> c -> d) -> Dynamic d
145+
146+-- Efficient one-to-many fanout
147+[ ] demux :: Ord k => Dynamic k -> Demux k
148+[ ] demuxed :: Eq k => Demux k -> k -> Dynamic Bool
149+
150+-- Dynamic to Dynamic, removing updates w/o value change
151+[H] holdUniqDyn :: Eq a => Dynamic a -> m (Dynamic a)
152+[H] holdUniqDynBy :: (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
153+
154+-- Dynamic to identical Dynamic with debug trace. (Only prints if Dynamic is ultimately used.)
155+[ ] traceDyn :: Show a => String -> Dynamic a -> Dynamic a
156+[ ] traceDynWith :: (a -> String) -> Dynamic a -> Dynamic a
157+```
158+
159+## Flattening functions
160+
161+These functions flatten nested types such as Event-of-Event, Behavior-of-Event, Event-of-Behavior etc, removing the outer wrapper.
162+
163+For Events, the returned Event fires whenever the latest Event supplied by the wrapper fires. There are differences in how the functions handle *coincidences* -- situations where the old or new Event fires at the same instant that we switch from old to new. In some cases, the output Event tracks the old Event at the instant of switchover, while in other cases it tracks the new Event.
164+
165+```haskell
166+-- Flatten Behavior-of-Event to Event. Old Event is used during switchover.
167+[ ] switch :: Behavior (Event a) -> Event a
168+
169+-- Flatten Dynamic-of-Event to Event. New Event is used immediately.
170+[ ] switchDyn :: Dynamic (Event a) -> Event a
171+
172+-- Flatten Event-of-Event to Event that fires when both wrapper AND new Event fire.
173+[ ] coincidence :: Event (Event a) -> Event a
174+
175+-- Flatten Behavior-of-Behavior to Behavior. Behavior is an instance of Monad,
176+-- so the 'join' function from 'Control.Monad' suffices. The output of 'join' is
177+-- a Behavior whose value is equal to the current value of the current value of
178+-- the input.
179+[ ] join :: Behavior (Behavior a) -> Behavior a
180+
181+
182+-- Flatten Dynamic-of-Dynamic to Dynamic. New Dynamic is used immediately.
183+-- Output updated whenever inner OR outer Dynamic updates.
184+[ ] join :: Dynamic (Dynamic a) -> Dynamic a
185+[ ] joinDynThroughMap :: Ord k => Dynamic (Map k (Dynamic a)) -> Dynamic (Map k a)
186+
187+-- Analogous to 'hold': Create a Behavior that is initially identical to the
188+-- supplied Behavior. Updated to track a new Behavior whenever the Event fires.
189+[H] switcher :: Behavior a -> Event (Behavior a) -> m (Behavior a)
190+
191+-- Similar to above, for Events. Created Event initially tracks the first argument.
192+-- At switchover, the output Event immediately tracks the new Event.
193+[H] switchHold :: Event a -> Event (Event a) -> m (Event a)
194+```
195+
196+## Typeclasses to introspect and modify an FRP network.
197+
198+The functions mentioned above are used to create a static FRP network.
199+There are additional typeclasses that can be used to modify the FRP network, to have it interact with IO action, or to introspect the building of the network.
200+
201+Th typeclasses and their associated annotations include:
202+
203+- `PostBuild`
204+ Fire an Event when an FRP network has been set up.
205+ ```haskell
206+ [B] -- Function runs in any monad supporting PostBuild
207+ ```
208+
209+- `Adjustable`
210+ Use Events to add or remove pieces of an FRP network.
211+ ```haskell
212+ [A] -- Function runs in any monad supporting Adjustable
213+ ```
214+
215+- `TriggerEvent`
216+ Create new externally-fired Events from within an FRP network.
217+ ```haskell
218+ [T] -- Function runs in any monad supporting TriggerEvent
219+ ```
220+
221+- `PerformEvent`
222+ Use Events to trigger IO actions and to collect their results.
223+ ```haskell
224+ [P] -- Function runs in any monad supporting PerformEvent
225+ ```
226+
227+## Startup
228+
229+```haskell
230+-- One-shot Event that is triggered once the FRP network has been built
231+[B] getPostBuild :: m (Event ())
232+```
233+
234+## Collection management functions
235+
236+```haskell
237+-- Turn a Dynamic key/value map into a set of dynamically-changing widgets.
238+[H,A,B] listWithKey :: Ord k =>
239+ Dynamic (Map k v) -> (k -> Dynamic v -> m a ) -> m (Dynamic (Map k a))
240+
241+-- Same as above where the widget constructor doesn't care about the key.
242+[H,A,B] list :: Ord k =>
243+ Dynamic (Map k v) -> ( Dynamic v -> m a ) -> m (Dynamic (Map k a))
244+
245+-- Even simpler version where there are no keys and we just use a list.
246+[H,A,B] simpleList ::
247+ Dynamic [v] -> ( Dynamic v -> m a ) -> m (Dynamic [a])
248+
249+-- Like listWithKey specialized for widgets returning (Event a).
250+[H,A,B] listViewWithKey :: Ord k =>
251+ Dynamic (Map k v) -> (k -> Dynamic v -> m (Event a)) -> m (Event (Map k a))
252+
253+-- Create a dynamically-changing set of widgets, one of which is selected at any time.
254+[H,A,B] selectViewListWithKey_ :: Ord k => Dynamic k ->
255+ Dynamic (Map k v) -> (k -> Dynamic v -> Dynamic Bool -> m (Event a)) -> m (Event k)
256+
257+-- Same as listWithKey, but takes initial values and an updates Event instead of a Dynamic.
258+[H,A] listWithKeyShallowDiff :: Ord k =>
259+ Map k v -> Event (Map k (Maybe v)) -> (k -> v -> Event v -> m a) -> m (Dynamic (Map k a))
260+```
261+
262+## Creating new events from within an FRP network.
263+
264+```haskell
265+-- Create a new Event and a function that will cause the Event to fire, from within an FRP network
266+[T] newTriggerEvent :: m (Event a, a -> IO ())
267+```
268+
269+## Connecting to the real world (I/O)
270+
271+```haskell
272+-- Run side-effecting actions in Event when it occurs; returned Event contains
273+-- results. Side effects run in the (Performable m) monad which is associated with
274+-- the (PerformEvent t m) typeclass constraint.
275+-- This allows for working with IO when a ((MonadIO (Performable m)) constraint is available.
276+[P] performEvent :: Event (Performable m a ) -> m (Event a)
277+
278+-- Just run side-effects; no return Event
279+[P] performEvent_ :: Event (Performable m ()) -> m ()
280+
281+-- Actions run asynchronously; actions are given a callback to send return values
282+[P,T] performEventAsync :: Event ((a -> IO ()) -> Performable m ()) -> m (Event a)
283+```
284+
285+### Time
286+
287+```haskell
288+-- Create Event at given interval with given basis time.
289+[P,T] tickLossy :: NominalDiffTime -> UTCTime -> m (Event t TickInfo)
290+
291+-- Delay an Event's occurrences by a given amount in seconds.
292+[P,T] delay :: NominalDiffTime -> Event t a -> m (Event t a)
293+```
294+
295+## Networks
296+
297+```haskell
298+-- Functions from Reflex.Network used to deal with Dynamics/Events carrying (m a)
299+
300+-- Given a Dynamic of network-creating actions, create a network that is recreated whenever the Dynamic updates.
301+-- The returned Event of network results occurs when the Dynamic does. Note: Often, the type a is an Event,
302+-- in which case the return value is an Event-of-Events that would typically be flattened (via switchHold).
303+[P,A] networkView :: Dynamic (m a) -> m (Event a)
304+
305+-- Given an initial network and an Event of network-creating actions, create a network that is recreated whenever the
306+-- Event fires. The returned Dynamic of network results occurs when the Event does. Note: Often, the type a is an
307+-- Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
308+[H,A] networkHold :: m a -> Event (m a) -> m (Dynamic a)
309+
310+-- Render a placeholder network to be shown while another network is not yet done building
311+[P,A] untilReady :: m a -> m b -> m (a, Event b)
README.md+14−41
@@ -1,52 +1,25 @@
1−# patch
1+## [Reflex](https://reflex-frp.org/)
22
3−[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/patch.svg)](https://hackage.haskell.org/package/patch) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/patch/badge)](https://matrix.hackage.haskell.org/#/package/patch) [![Travis CI](https://api.travis-ci.org/reflex-frp/patch.svg?branch=develop)](https://travis-ci.org/reflex-frp/patch) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/reflex-frp/patch/LICENSE)
3+[![Hackage](https://img.shields.io/hackage/v/reflex.svg)](http://hackage.haskell.org/package/reflex)
44
5−Data structures for describing changes to other data structures.
5+### Practical Functional Reactive Programming
66
7−A `Patch` type represents a kind of change made to a data structure.
7+Reflex is a fully-deterministic, higher-order Functional Reactive Programming (FRP) interface and an engine that efficiently implements that interface.
88
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−```
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.
1610
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).
11+A summary of Reflex functions is available in the [quick reference](Quickref.md).
1912
20−`PatchMap` is defined as:
13+**Visit https://reflex-frp.org/ for more information, tutorials, documentation and [examples](https://examples.reflex-frp.org/).**
2114
22−```haskell
23−newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
24−```
15+### Resources
16+[Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
2517
26−The `Maybe` around the value is used to represent insertion/updates or deletion of the element at a given key.
18+[/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
2719
28−Its `Patch` instance begins with:
20+[irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
2921
30−```haskell
31−instance Ord k => Patch (PatchMap k v) where
32− type PatchTarget (PatchMap k v) = Map k v
33− ...
34−```
22+### Hacking
3523
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`!
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.
bench/Main.hsnew file+110
@@ -0,0 +1,110 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+{-# LANGUAGE TupleSections #-}
5+{-# LANGUAGE TypeFamilies #-}
6+
7+-- The instance for NFData (TVar a) is an orphan, but necessary here
8+{-# OPTIONS_GHC -fno-warn-orphans #-}
9+
10+module Main where
11+
12+import Control.Concurrent.STM
13+import Control.DeepSeq
14+import Control.Exception (evaluate)
15+import Control.Monad.Identity
16+import Control.Monad.IO.Class
17+import Criterion.Main
18+import Data.Dependent.Map (DMap)
19+import qualified Data.Dependent.Map as DMap
20+import Data.Dependent.Sum
21+import Data.Functor.Misc
22+import Data.IORef
23+import Data.Maybe (fromJust)
24+import Reflex
25+import Reflex.Host.Class
26+
27+main :: IO ()
28+main = defaultMain
29+ [ bgroup "micro" micros ]
30+
31+#if !(MIN_VERSION_deepseq(1,4,2))
32+instance NFData (IORef a) where
33+ rnf x = seq x ()
34+#endif
35+
36+instance NFData (TVar a) where
37+ rnf x = seq x ()
38+
39+newtype WHNF a = WHNF a
40+instance NFData (WHNF a) where
41+ rnf (WHNF a) = seq a ()
42+
43+withSetup :: NFData b => String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
44+withSetup name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
45+ bench name . nfIO $ runSpiderHost (action a)
46+
47+withSetupWHNF :: String -> SpiderHost Global a -> (a -> SpiderHost Global b) -> Benchmark
48+withSetupWHNF name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
49+ bench name . whnfIO $ runSpiderHost (action a)
50+
51+micros :: [Benchmark]
52+micros =
53+ [ bench "newIORef" $ whnfIO $ void $ newIORef ()
54+ , env (newIORef (42 :: Int)) (bench "readIORef" . whnfIO . readIORef)
55+ , bench "newTVar" $ whnfIO $ void $ newTVarIO ()
56+ , env (newTVarIO (42 :: Int)) (bench "readTVar" . whnfIO . readTVarIO)
57+ , bench "newEventWithTrigger" $ whnfIO . void $ runSpiderHost $ newEventWithTrigger $
58+ \trigger -> return () <$ evaluate trigger
59+ , bench "newEventWithTriggerRef" $ whnfIO . void $ runSpiderHost newEventWithTriggerRef
60+ , withSetupWHNF "subscribeEvent" newEventWithTriggerRef $ subscribeEvent . fst
61+ , withSetupWHNF "subscribeSwitch"
62+ (join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)
63+ (subscribeEvent . switch)
64+ , withSetupWHNF "subscribeMerge(1)" (setupMerge 1) $ \(ev,_) -> subscribeEvent ev
65+ , withSetupWHNF "subscribeMerge(100)" (setupMerge 100) (subscribeEvent . fst)
66+ , withSetupWHNF "subscribeMerge(10000)" (setupMerge 10000) (subscribeEvent . fst)
67+ , bench "runHostFrame" $ whnfIO $ runSpiderHost $ runHostFrame $ return ()
68+ , withSetupWHNF "fireEventsAndRead(single/single)"
69+ (newEventWithTriggerRef >>= subscribePair)
70+ (\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)
71+ , withSetupWHNF "fireEventsOnly"
72+ (newEventWithTriggerRef >>= subscribePair)
73+ (\(_, trigger) -> do
74+ key <- fromJust <$> liftIO (readIORef trigger)
75+ fireEvents [key :=> Identity (42 :: Int)])
76+ , withSetupWHNF "fireEventsAndRead(head/merge1)"
77+ (setupMerge 1 >>= subscribePair)
78+ (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
79+ , withSetupWHNF "fireEventsAndRead(head/merge100)"
80+ (setupMerge 100 >>= subscribePair)
81+ (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
82+ , withSetupWHNF "fireEventsAndRead(head/merge10000)"
83+ (setupMerge 10000 >>= subscribePair)
84+ (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)
85+ , withSetupWHNF "fireEventsOnly(head/merge100)"
86+ (setupMerge 100 >>= subscribePair)
87+ (\(_, t:_) -> do
88+ key <- fromJust <$> liftIO (readIORef t)
89+ fireEvents [key :=> Identity (42 :: Int)])
90+ , withSetupWHNF "hold" newEventWithTriggerRef $ \(ev, _) -> hold (42 :: Int) ev
91+ , withSetupWHNF "sample" (newEventWithTriggerRef >>= hold (42 :: Int) . fst) sample
92+ ]
93+
94+setupMerge :: Int
95+ -> SpiderHost Global ( Event (SpiderTimeline Global) (DMap (Const2 Int a) Identity)
96+ , [IORef (Maybe (EventTrigger Spider a))]
97+ )
98+setupMerge num = do
99+ (evs, triggers) <- unzip <$> replicateM num newEventWithTriggerRef
100+ let !m = DMap.fromList [Const2 i :=> v | (i,v) <- zip [0..] evs]
101+ pure (merge m, triggers)
102+
103+subscribePair :: (Event (SpiderTimeline Global) a, b) -> SpiderHost Global (EventHandle (SpiderTimeline Global) a, b)
104+subscribePair (ev, b) = (,b) <$> subscribeEvent ev
105+
106+fireAndRead :: IORef (Maybe (EventTrigger (SpiderTimeline Global) a)) -> a -> EventHandle (SpiderTimeline Global) b
107+ -> SpiderHost Global (Maybe b)
108+fireAndRead trigger val subd = do
109+ key <- fromJust <$> liftIO (readIORef trigger)
110+ fireEventsAndRead [key :=> Identity val] $ readEvent subd >>= sequence
bench/RunAll.hsnew file+157
@@ -0,0 +1,157 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE ForeignFunctionInterface #-}
6+{-# LANGUAGE GADTs #-}
7+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
9+{-# LANGUAGE PatternSynonyms #-}
10+{-# LANGUAGE RankNTypes #-}
11+{-# LANGUAGE ScopedTypeVariables #-}
12+{-# LANGUAGE TemplateHaskell #-}
13+{-# LANGUAGE TupleSections #-}
14+{-# LANGUAGE TypeSynonymInstances #-}
15+{-# LANGUAGE ViewPatterns #-}
16+{-# OPTIONS_GHC -fno-warn-orphans #-}
17+
18+module Main where
19+
20+import Criterion.Main
21+import Criterion.Types
22+
23+import Reflex
24+import Reflex.Host.Class
25+
26+import Reflex.Plan.Reflex
27+import Reflex.TestPlan
28+
29+import qualified Reflex.Bench.Focused as Focused
30+import Reflex.Spider.Internal (SpiderEventHandle)
31+
32+import Control.Applicative
33+import Control.DeepSeq (NFData (..))
34+
35+import Prelude
36+import System.IO
37+import System.Mem
38+
39+import Control.Arrow
40+import Control.Concurrent
41+import Control.Concurrent.STM
42+import Control.Exception
43+import Control.Monad
44+import Control.Monad.Trans
45+import Data.Bool
46+import Data.Function
47+import Data.Int
48+import Data.IORef
49+import Data.Monoid
50+import Data.Time.Clock
51+import Debug.Trace.LocationTH
52+import GHC.Stats
53+import System.Environment
54+import System.Mem.Weak
55+import System.Process
56+import Text.Read
57+
58+import Unsafe.Coerce
59+
60+import Data.Map (Map)
61+import qualified Data.Map as Map
62+
63+type MonadReflexHost' t m = (MonadReflexHost t m, MonadIORef m, MonadIORef (HostFrame t))
64+
65+
66+setupFiring :: (MonadReflexHost t m, MonadIORef m) => Plan t (Event t a) -> m (EventHandle t a, Schedule t)
67+setupFiring p = do
68+ (e, s) <- runPlan p
69+ h <- subscribeEvent e
70+ return (h, s)
71+
72+-- Hack to avoid the NFData constraint for EventHandle which is a synonym
73+newtype Ignore a = Ignore a
74+instance NFData (Ignore a) where
75+ rnf !_ = ()
76+
77+instance NFData (SpiderEventHandle x a) where
78+ rnf !_ = ()
79+
80+instance NFData (Behavior t a) where
81+ rnf !_ = ()
82+
83+instance NFData (Firing t) where
84+ rnf !_ = ()
85+
86+-- Measure the running time
87+benchFiring :: forall t m. (MonadReflexHost' t m, MonadSample t m) => (forall a. m a -> IO a) -> TestCase -> Int -> IO ()
88+benchFiring runHost tc n = runHost $ do
89+ let runIterations :: m a -> m ()
90+ runIterations test = replicateM_ (10*n) $ do
91+ result <- test
92+ liftIO $ evaluate result
93+ case tc of
94+ TestE p -> do
95+ (h, s) <- setupFiring p
96+ runIterations $ readSchedule_ s $ readEvent' h
97+ TestB p -> do
98+ (b, s) <- runPlan p
99+ runIterations $ readSchedule_ (makeDense s) $ sample b
100+
101+waitForFinalizers :: IO ()
102+waitForFinalizers = do
103+ performGC
104+ x <- getCurrentTime
105+ isFinalized <- newIORef False
106+ mkWeakPtr x $ Just $ writeIORef isFinalized True
107+ performGC
108+ fix $ \loop -> do
109+ f <- readIORef isFinalized
110+ unless f $ do
111+ threadDelay 1
112+ loop
113+
114+benchmarks :: [(String, Int -> IO ())]
115+benchmarks = implGroup "spider" runSpiderHost cases
116+ where
117+ implGroup :: (MonadReflexHost' t m, MonadSample t m) => String -> (forall a. m a -> IO a) -> [(String, TestCase)] -> [(String, Int -> IO ())]
118+ implGroup name runHost = group name . fmap (second (benchFiring runHost))
119+ group name = fmap $ first ((name <> "/") <>)
120+ sub n frames = group ("subscribing " ++ show (n, frames)) $ Focused.subscribing n frames
121+ firing n = group ("firing " <> show n) $ Focused.firing n
122+ merging n = group ("merging " <> show n) $ Focused.merging n
123+ dynamics n = group ("dynamics " <> show n) $ Focused.dynamics n
124+ cases = concat
125+ [ sub 100 40
126+ , dynamics 100
127+ , dynamics 1000
128+ , firing 1000
129+ , firing 10000
130+ , merging 10
131+ , merging 50
132+ , merging 100
133+ , merging 200
134+ ]
135+
136+pattern RunTestCaseFlag = "--run-test-case"
137+
138+spawnBenchmark :: String -> Benchmark
139+spawnBenchmark name = bench name . toBenchmarkable $ \n -> do
140+ self <- getExecutablePath
141+ callProcess self [RunTestCaseFlag, name, show n, "+RTS", "-N1"]
142+
143+foreign import ccall unsafe "myCapabilityHasOtherRunnableThreads" myCapabilityHasOtherRunnableThreads :: IO Bool
144+
145+main :: IO ()
146+main = do
147+ args <- getArgs
148+ case args of
149+ RunTestCaseFlag : t -> case t of
150+ [name, readMaybe -> Just count] -> do
151+ case lookup name benchmarks of
152+ Just testCase -> testCase count
153+ performGC
154+ fix $ \loop -> bool (return ()) (yield >> loop) =<< myCapabilityHasOtherRunnableThreads
155+ return ()
156+ _ -> $failure "--run-test-case: expected test name and iteration count to follow"
157+ _ -> defaultMainWith (defaultConfig { timeLimit = 20, csvFile = Just "dmap-original.csv", reportFile = Just "report.html" }) $ fmap (spawnBenchmark . fst) benchmarks
cabal.haskell-cinew file+7
@@ -0,0 +1,7 @@
1+distribution: bionic
2+
3+-- https://github.com/haskell/cabal/issues/6106
4+install-dependencies: False
5+
6+constraint-set no-th
7+ constraints: reflex -use-template-haskell
default.nixnew file+42
@@ -0,0 +1,42 @@
1+{ mkDerivation, ghc, base, bifunctors, containers, deepseq
2+, dependent-map, dependent-sum, exception-transformers
3+, haskell-src-exts, haskell-src-meta, hlint, lens, MemoTrie
4+, monad-control, mtl, primitive, random, ref-tf
5+, semigroupoids , semigroups, split, stdenv, stm, syb
6+, template-haskell , these, time, transformers
7+, transformers-compat, unbounded-delays, prim-uniq
8+, data-default, filepath, directory, filemanip, ghcjs-base
9+, monoidal-containers, witherable
10+, semialign ? null, splitThese ? (semialign != null)
11+, useTemplateHaskell ? true
12+}:
13+mkDerivation {
14+ pname = "reflex";
15+ version = "0.6.2.2";
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+ ] ++ (if ghc.isGhcjs or false then [
27+ ghcjs-base
28+ ] else []) ++ (if !useTemplateHaskell then [] else [
29+ haskell-src-exts haskell-src-meta
30+ ]) ++ (if splitThese then [
31+ semialign
32+ ] else []);
33+ testHaskellDepends = if ghc.isGhcjs or false then [] else [
34+ hlint filepath directory filemanip
35+ ];
36+ configureFlags =
37+ stdenv.lib.optional (!useTemplateHaskell) [ "-f-use-template-haskell" ] ++
38+ stdenv.lib.optional (!splitThese) [ "-f-split-these" ];
39+ homepage = "https://github.com/reflex-frp/reflex";
40+ description = "Higher-order Functional Reactive Programming";
41+ license = stdenv.lib.licenses.bsd3;
42+}
dep/reflex-platform/default.nixdeleted−8
@@ -1,8 +0,0 @@
1−# DO NOT HAND-EDIT THIS FILE
2−let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3− if !fetchSubmodules && !private then builtins.fetchTarball {
4− url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5− } else (import <nixpkgs> {}).fetchFromGitHub {
6− inherit owner repo rev sha256 fetchSubmodules private;
7− };
8−in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))
dep/reflex-platform/github.jsondeleted−8
@@ -1,8 +0,0 @@
1−{
2− "owner": "reflex-frp",
3− "repo": "reflex-platform",
4− "branch": "master",
5− "private": false,
6− "rev": "c9d11db1b98855fe8ab24a3ff6a5dbe0ad902ad9",
7− "sha256": "0sfzkqdvyah5mwvmli0wq1nl0b8cvk2cmfgfy4rz57wv42x3099y"
8−}
hydra.jsonnew file+29
@@ -0,0 +1,29 @@
1+{
2+ "enabled": 1,
3+ "hidden": true,
4+ "description": "Jobsets",
5+ "nixexprinput": "src",
6+ "nixexprpath": "jobsets.nix",
7+ "checkinterval": 300,
8+ "schedulingshares": 100,
9+ "enableemail": false,
10+ "emailoverride": "",
11+ "keepnr": 10,
12+ "inputs": {
13+ "src": {
14+ "type": "git",
15+ "value": "https://github.com/reflex-frp/reflex.git develop",
16+ "emailresponsible": false
17+ },
18+ "nixpkgs": {
19+ "type": "git",
20+ "value": "https://github.com/NixOS/nixpkgs-channels nixos-unstable",
21+ "emailresponsible": false
22+ },
23+ "prs": {
24+ "type": "githubpulls",
25+ "value": "reflex-frp reflex",
26+ "emailresponsible": false
27+ }
28+ }
29+}
jobsets.nixnew file+70
@@ -0,0 +1,70 @@
1+{ prs }:
2+
3+let
4+ pkgs = (import ./reflex-platform.nix {}).nixpkgs;
5+ mkFetchGithub = value: {
6+ inherit value;
7+ type = "git";
8+ emailresponsible = false;
9+ };
10+in
11+with pkgs.lib;
12+let
13+ defaults = jobs: {
14+ inherit (jobs) description;
15+ enabled = 1;
16+ hidden = false;
17+ keepnr = 10;
18+ schedulingshares = 100;
19+ checkinterval = 120;
20+ enableemail = false;
21+ emailoverride = "";
22+ nixexprinput = "reflex";
23+ nixexprpath = "release.nix";
24+ inputs = jobs.inputs // {
25+ nixpkgs = {
26+ type = "git";
27+ value = "https://github.com/NixOS/nixpkgs-channels nixos-unstable";
28+ emailresponsible = false;
29+ };
30+ config = {
31+ type = "nix";
32+ value = "{ android_sdk.accept_license = true; }";
33+ emailresponsible = false;
34+ };
35+ };
36+ };
37+ branchJobset = branch: defaults {
38+ description = "reflex-${branch}";
39+ inputs = {
40+ reflex = {
41+ value = "https://github.com/reflex-frp/reflex ${branch}";
42+ type = "git";
43+ emailresponsible = false;
44+ };
45+ };
46+ };
47+ makePr = num: info: {
48+ name = "reflex-pr-${num}";
49+ value = defaults {
50+ description = "#${num}: ${info.title}";
51+ inputs = {
52+ reflex = {
53+ #NOTE: This should really use "pull/${num}/merge"; however, GitHub's
54+ #status checks only operate on PR heads. This creates a race
55+ #condition, which can currently only be solved by requiring PRs to be
56+ #up to date before they're merged. See
57+ #https://github.com/isaacs/github/issues/1002
58+ value = "https://github.com/reflex-frp/reflex pull/${num}/head";
59+ type = "git";
60+ emailresponsible = false;
61+ };
62+ };
63+ };
64+ };
65+ processedPrs = mapAttrs' makePr (builtins.fromJSON (builtins.readFile prs));
66+ jobsetsAttrs = processedPrs //
67+ genAttrs ["develop"] branchJobset;
68+in {
69+ jobsets = pkgs.writeText "spec.json" (builtins.toJSON jobsetsAttrs);
70+}
patch.cabaldeleted−100
@@ -1,100 +0,0 @@
1−Name: patch
2−Version: 0.0.5.0
3−Synopsis: Data structures for describing changes to other data structures.
4−Description:
5− Data structures for describing changes to other data structures.
6− .
7− In this library, a patch is something which can be applied, analogous to a
8− function, and which distinguishes returning the argument it was provided from
9− returning something else.
10−License: BSD3
11−License-file: LICENSE
12−Author: Ryan Trinkle
13−Maintainer: maintainer@obsidian.systems
14−Stability: Experimental
15−Category: FRP
16−Build-type: Simple
17−Cabal-version: >=1.10
18−homepage: https://obsidian.systems
19−bug-reports: https://github.com/reflex-frp/patch/issues
20−extra-source-files:
21− README.md
22− ChangeLog.md
23−
24−tested-with:
25− GHC ==8.0.2 || ==8.2.2 || ==8.4.4 || ==8.6.5 || ==8.8.1
26− GHCJS ==8.4
27−
28−flag split-these
29− description: Use split these/semialign packages
30− manual: False
31− default: True
32−
33−library
34− hs-source-dirs: src
35− default-language: Haskell2010
36− build-depends: base >= 4.9 && < 4.15
37− , constraints-extras >= 0.3 && < 0.4
38− , containers >= 0.6 && < 0.7
39− , dependent-map >= 0.3 && < 0.5
40− , dependent-sum >= 0.6 && < 0.8
41− , lens >= 4.7 && < 5
42− , semigroupoids >= 4.0 && < 6
43− , transformers >= 0.5.6.0 && < 0.6
44− , witherable >= 0.3 && < 0.5
45−
46− if impl(ghc < 8.6) -- really, if base < 8.12
47− build-depends: base-orphans >= 0.8 && < 0.9
48−
49− exposed-modules: Data.Functor.Misc
50− , Data.Monoid.DecidablyEmpty
51− , Data.Patch
52− , Data.Patch.Class
53− , Data.Patch.DMap
54− , Data.Patch.DMapWithMove
55− , Data.Patch.IntMap
56− , Data.Patch.Map
57− , Data.Patch.MapWithMove
58− , Data.Patch.MapWithPatchingMove
59− , Data.Semigroup.Additive
60−
61− ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs
62− default-extensions: PolyKinds
63−
64− if flag(split-these)
65− build-depends: these >= 1 && <1.2
66− , semialign >=1 && <1.2
67− , monoidal-containers >= 0.6 && < 0.7
68− else
69− build-depends: these >= 0.4 && <0.9
70− , monoidal-containers == 0.4.0.0
71−
72−test-suite tests
73− default-language: Haskell2010
74− type: exitcode-stdio-1.0
75− main-is: tests.hs
76− hs-source-dirs: test
77− build-depends: base
78− , patch
79− , containers
80− , hedgehog
81− , HUnit
82− if impl(ghcjs)
83− buildable: False
84−
85−test-suite hlint
86− default-language: Haskell2010
87− type: exitcode-stdio-1.0
88− main-is: hlint.hs
89− hs-source-dirs: test
90− build-depends: base
91− , directory
92− , filepath
93− , filemanip
94− , hlint (< 2.1 || >= 2.2.2) && < 3.3
95− if impl(ghcjs)
96− buildable: False
97−
98−source-repository head
99− type: git
100− location: https://github.com/reflex-frp/patch
reflex-platform.nixnew file+8
@@ -0,0 +1,8 @@
1+let
2+ reflex-platform-src = (import <nixpkgs> {}).fetchFromGitHub {
3+ owner = "reflex-frp";
4+ repo = "reflex-platform";
5+ rev = "384cd850f3adf1d404bced2424b5f6efb0f415f2";
6+ sha256 = "1ws77prqx8khmp8j6br1ij4k2v4dlgv170r9fmg0p1jivfbn8y9d";
7+ };
8+in import reflex-platform-src
reflex.cabalnew file+398
@@ -0,0 +1,398 @@
1+Name: reflex
2+Version: 0.6.2.2
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+ random == 1.1.*,
68+ ref-tf == 0.4.*,
69+ reflection == 2.1.*,
70+ semigroupoids >= 4.0 && < 6,
71+ stm >= 2.4 && < 2.6,
72+ syb >= 0.5 && < 0.8,
73+ time >= 1.4 && < 1.9,
74+ transformers >= 0.5.6.0 && < 0.6,
75+ unbounded-delays >= 0.1.0.0 && < 0.2,
76+ witherable >= 0.2 && < 0.4
77+
78+ if flag(split-these)
79+ build-depends: these >= 1 && <1.1,
80+ semialign >=1 && <1.1,
81+ monoidal-containers >= 0.5.0.1 && < 0.6
82+ else
83+ build-depends: these >= 0.4 && <0.9,
84+ monoidal-containers == 0.5.0.0
85+
86+ exposed-modules:
87+ Data.AppendMap,
88+ Data.FastMutableIntMap,
89+ Data.FastWeakBag,
90+ Data.Functor.Misc,
91+ Data.Map.Misc,
92+ Data.WeakBag,
93+ Reflex,
94+ Reflex.Class,
95+ Reflex.Adjustable.Class,
96+ Reflex.BehaviorWriter.Base,
97+ Reflex.BehaviorWriter.Class,
98+ Reflex.Collection,
99+ Reflex.Dynamic,
100+ Reflex.Dynamic.Uniq,
101+ Reflex.DynamicWriter,
102+ Reflex.DynamicWriter.Base,
103+ Reflex.DynamicWriter.Class,
104+ Reflex.EventWriter,
105+ Reflex.EventWriter.Base,
106+ Reflex.EventWriter.Class,
107+ Reflex.FastWeak,
108+ Reflex.FunctorMaybe,
109+ Reflex.Host.Class,
110+ Reflex.Network,
111+ Reflex.NotReady.Class,
112+ Reflex.Patch,
113+ Reflex.Patch.Class,
114+ Reflex.Patch.DMap,
115+ Reflex.Patch.DMapWithMove,
116+ Reflex.Patch.IntMap,
117+ Reflex.Patch.Map,
118+ Reflex.Patch.MapWithMove,
119+ Reflex.PerformEvent.Base,
120+ Reflex.PerformEvent.Class,
121+ Reflex.PostBuild.Base,
122+ Reflex.PostBuild.Class,
123+ Reflex.Profiled,
124+ Reflex.Pure,
125+ Reflex.Query.Base,
126+ Reflex.Query.Class,
127+ Reflex.Requester.Base,
128+ Reflex.Requester.Class,
129+ Reflex.Spider,
130+ Reflex.Spider.Internal,
131+ Reflex.Time,
132+ Reflex.TriggerEvent.Base,
133+ Reflex.TriggerEvent.Class,
134+ Reflex.Widget.Basic,
135+ Reflex.Workflow
136+
137+ ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs -funbox-strict-fields -O2 -fspecialise-aggressively
138+
139+ if flag(debug-trace-events)
140+ cpp-options: -DDEBUG_TRACE_EVENTS
141+ build-depends: bytestring
142+
143+ if flag(use-reflex-optimizer)
144+ cpp-options: -DUSE_REFLEX_OPTIMIZER
145+ build-depends: ghc
146+ exposed-modules: Reflex.Optimizer
147+
148+ if flag(use-template-haskell)
149+ cpp-options: -DUSE_TEMPLATE_HASKELL
150+ build-depends:
151+ dependent-sum >= 0.6 && < 0.7,
152+ haskell-src-exts >= 1.16 && < 1.22,
153+ haskell-src-meta >= 0.6 && < 0.9,
154+ template-haskell >= 2.9 && < 2.15
155+ exposed-modules:
156+ Reflex.Dynamic.TH
157+ other-extensions: TemplateHaskell
158+ else
159+ build-depends:
160+ dependent-sum >= 0.6 && < 0.7
161+
162+ if flag(fast-weak) && impl(ghcjs)
163+ cpp-options: -DGHCJS_FAST_WEAK
164+
165+ if impl(ghcjs)
166+ build-depends: ghcjs-base
167+
168+test-suite semantics
169+ type: exitcode-stdio-1.0
170+ main-is: semantics.hs
171+ hs-source-dirs: test
172+ ghc-options: -O2 -Wall -rtsopts
173+ build-depends:
174+ base,
175+ bifunctors,
176+ containers,
177+ deepseq >= 1.3 && < 1.5,
178+ dependent-map,
179+ dependent-sum,
180+ mtl,
181+ ref-tf,
182+ reflex,
183+ split,
184+ transformers
185+ other-modules:
186+ Reflex.Bench.Focused
187+ Reflex.Plan.Pure
188+ Reflex.Plan.Reflex
189+ Reflex.Test
190+ Reflex.Test.Micro
191+ Reflex.TestPlan
192+
193+test-suite CrossImpl
194+ type: exitcode-stdio-1.0
195+ main-is: Reflex/Test/CrossImpl.hs
196+ hs-source-dirs: test
197+ ghc-options: -O2 -Wall -rtsopts
198+ build-depends:
199+ base,
200+ containers,
201+ dependent-map,
202+ dependent-sum,
203+ deepseq >= 1.3 && < 1.5,
204+ mtl,
205+ transformers,
206+ ref-tf,
207+ reflex
208+ other-modules:
209+ Reflex.Test
210+ Reflex.TestPlan
211+ Reflex.Plan.Reflex
212+ Reflex.Plan.Pure
213+
214+test-suite hlint
215+ type: exitcode-stdio-1.0
216+ main-is: hlint.hs
217+ hs-source-dirs: test
218+ build-depends: base
219+ , directory
220+ , filepath
221+ , filemanip
222+ , hlint >= 2.2.2 && < 2.3
223+ if impl(ghcjs)
224+ buildable: False
225+
226+test-suite EventWriterT
227+ type: exitcode-stdio-1.0
228+ main-is: EventWriterT.hs
229+ hs-source-dirs: test
230+ build-depends: base
231+ , containers
232+ , deepseq >= 1.3 && < 1.5
233+ , dependent-map
234+ , dependent-sum
235+ , lens
236+ , mtl
237+ , these
238+ , transformers
239+ , reflex
240+ , ref-tf
241+
242+ if flag(split-these)
243+ build-depends: these-lens
244+
245+ other-modules:
246+ Reflex.Test
247+ Reflex.TestPlan
248+ Reflex.Plan.Reflex
249+ Reflex.Plan.Pure
250+ Test.Run
251+
252+
253+test-suite RequesterT
254+ type: exitcode-stdio-1.0
255+ main-is: RequesterT.hs
256+ hs-source-dirs: test
257+ build-depends: base
258+ , containers
259+ , deepseq >= 1.3 && < 1.5
260+ , dependent-sum
261+ , dependent-map
262+ , lens
263+ , mtl
264+ , these
265+ , transformers
266+ , reflex
267+ , ref-tf
268+
269+ if flag(split-these)
270+ build-depends: these-lens
271+
272+ other-modules:
273+ Reflex.TestPlan
274+ Reflex.Plan.Pure
275+ Test.Run
276+
277+test-suite QueryT
278+ type: exitcode-stdio-1.0
279+ main-is: QueryT.hs
280+ hs-source-dirs: test
281+ build-depends: base
282+ , containers
283+ , dependent-map
284+ , dependent-sum
285+ , deepseq >= 1.3 && < 1.5
286+ , lens
287+ , monoidal-containers
288+ , mtl
289+ , ref-tf
290+ , reflex
291+ , these
292+ , transformers
293+
294+ if flag(split-these)
295+ build-depends: semialign, these-lens
296+
297+ other-modules:
298+ Test.Run
299+ Reflex.TestPlan
300+ Reflex.Plan.Reflex
301+ Reflex.Plan.Pure
302+
303+test-suite GC-Semantics
304+ type: exitcode-stdio-1.0
305+ main-is: GC.hs
306+ hs-source-dirs: test
307+ build-depends: base
308+ , containers
309+ , dependent-sum
310+ , dependent-map
311+ , deepseq >= 1.3 && < 1.5
312+ , mtl
313+ , these
314+ , transformers
315+ , reflex
316+ , ref-tf
317+
318+ if flag(split-these)
319+ build-depends: semialign
320+
321+ other-modules:
322+ Reflex.Plan.Pure
323+ Reflex.Plan.Reflex
324+ Reflex.TestPlan
325+ Test.Run
326+
327+test-suite rootCleanup
328+ type: exitcode-stdio-1.0
329+ main-is: rootCleanup.hs
330+ hs-source-dirs: test
331+ build-depends: base
332+ , containers
333+ , deepseq >= 1.3 && < 1.5
334+ , dependent-sum
335+ , mtl
336+ , reflex
337+ , ref-tf
338+ , these
339+ other-modules:
340+ Reflex.Plan.Pure
341+ Reflex.TestPlan
342+ Test.Run
343+
344+benchmark spider-bench
345+ type: exitcode-stdio-1.0
346+ hs-source-dirs: bench test
347+ main-is: Main.hs
348+ ghc-options: -Wall -O2 -rtsopts
349+ build-depends:
350+ base,
351+ containers,
352+ criterion >= 1.1 && < 1.6,
353+ deepseq >= 1.3 && < 1.5,
354+ dependent-map,
355+ dependent-sum,
356+ ref-tf,
357+ mtl,
358+ primitive,
359+ reflex,
360+ split,
361+ stm,
362+ transformers >= 0.3
363+ other-modules:
364+ Reflex.TestPlan
365+ Reflex.Plan.Reflex
366+ Reflex.Bench.Focused
367+
368+benchmark saulzar-bench
369+ type: exitcode-stdio-1.0
370+ hs-source-dirs: bench test
371+ c-sources: bench-cbits/checkCapability.c
372+ main-is: RunAll.hs
373+ ghc-options: -Wall -O2 -rtsopts -threaded
374+ build-depends:
375+ base,
376+ containers,
377+ criterion >= 1.1 && < 1.6,
378+ deepseq >= 1.3 && < 1.5,
379+ dependent-map,
380+ dependent-sum,
381+ loch-th,
382+ mtl,
383+ primitive,
384+ process,
385+ ref-tf,
386+ reflex,
387+ split,
388+ stm,
389+ time,
390+ transformers
391+ other-modules:
392+ Reflex.TestPlan
393+ Reflex.Plan.Reflex
394+ Reflex.Bench.Focused
395+
396+source-repository head
397+ type: git
398+ location: https://github.com/reflex-frp/reflex
release.nix+7−47
@@ -1,49 +1,9 @@
1−{ reflex-platform-fun ? import ./dep/reflex-platform
1+{ rp ? import ./reflex-platform.nix {}
22}:
3−
43let
5− native-reflex-platform = reflex-platform-fun {};
6− inherit (native-reflex-platform.nixpkgs) lib;
7− systems = ["x86_64-linux" "x86_64-darwin"];
8−
9− perPlatform = lib.genAttrs systems (system: let
10− reflex-platform = reflex-platform-fun { inherit system; };
11− compilers = [
12− "ghc"
13− "ghcjs"
14− ] ++ lib.optionals (reflex-platform.androidSupport) [
15− "ghcAndroidAarch64"
16− "ghcAndroidAarch32"
17− ] ++ lib.optionals (reflex-platform.iosSupport) [
18− "ghcIosAarch64"
19− ];
20− compilerPkgs = lib.genAttrs compilers (ghc: let
21− reflex-platform = reflex-platform-fun {
22− inherit system;
23− haskellOverlays = [
24− # Use this package's source for reflex
25− (self: super: {
26− _dep = super._dep // {
27− patch = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
28− "release.nix"
29− ".git"
30− "dist"
31− "dist-newstyle"
32− "cabal.haskell-ci"
33− "cabal.project"
34− ".travis.yml"
35− ])) ./.;
36− };
37− })
38− ];
39− };
40− in reflex-platform.${ghc}.patch);
41− in compilerPkgs // {
42− cache = reflex-platform.pinBuildInputs "patch-${system}"
43− (builtins.attrValues compilerPkgs);
44− });
45−
46− metaCache = native-reflex-platform.pinBuildInputs "patch-everywhere"
47− (map (a: a.cache) (builtins.attrValues perPlatform));
48−
49−in perPlatform // { inherit metaCache; }
4+ inherit (rp.nixpkgs) lib;
5+ compilers = ["ghc8_4" "ghc8_0" "ghcjs8_4" "ghcjs8_0"];
6+in lib.attrValues (lib.genAttrs compilers (ghc: {
7+ reflex-useTemplateHaskell = rp.${ghc}.callPackage ./. { useTemplateHaskell = true; splitThese = false; };
8+ reflex = rp.${ghc}.callPackage ./. { useTemplateHaskell = false; splitThese = false; };
9+}))
src/Data/AppendMap.hsnew file+80
@@ -0,0 +1,80 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE PatternSynonyms #-}
6+{-# LANGUAGE RoleAnnotations #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE TypeFamilies #-}
9+{-# OPTIONS_GHC -fno-warn-orphans #-}
10+-- |
11+-- Module:
12+-- Data.AppendMap
13+-- Description:
14+-- Instances and convenience functions for 'Data.Map.Monoidal'. We use
15+-- monoidal-containers to take advantage of its better monoid instance.
16+-- 'Data.Map' has @mappend = union@, which is left-biased. 'MonoidalMap'
17+-- has @mappend = unionWith mappend@ instead.
18+module Data.AppendMap
19+ ( module Data.AppendMap
20+ , module Data.Map.Monoidal
21+ ) where
22+
23+import Prelude hiding (map, null)
24+
25+import Data.Coerce
26+import Data.Default
27+import Data.Map (Map)
28+#if MIN_VERSION_containers(0,5,11)
29+import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith)
30+#else
31+import qualified Data.Map as Map (showTree, showTreeWith)
32+#endif
33+import qualified Data.Witherable as W
34+import Data.Map.Monoidal
35+
36+{-# DEPRECATED AppendMap "Use 'MonoidalMap' instead" #-}
37+-- | AppendMap is a synonym for 'Data.Map.Monoidal.MonoidalMap'
38+type AppendMap = MonoidalMap
39+
40+{-# DEPRECATED _unAppendMap "Use 'getMonoidalMap' instead" #-}
41+-- | A synonym for 'getMonoidalMap'
42+_unAppendMap :: MonoidalMap k v -> Map k v
43+_unAppendMap = getMonoidalMap
44+
45+-- | Pattern synonym for 'MonoidalMap'
46+pattern AppendMap :: Map k v -> MonoidalMap k v
47+pattern AppendMap m = MonoidalMap m
48+
49+instance W.Filterable (MonoidalMap k) where
50+ mapMaybe = mapMaybe
51+
52+-- | Deletes a key, returning 'Nothing' if the result is empty.
53+nonEmptyDelete :: Ord k => k -> MonoidalMap k a -> Maybe (MonoidalMap k a)
54+nonEmptyDelete k vs =
55+ let deleted = delete k vs
56+ in if null deleted
57+ then Nothing
58+ else Just deleted
59+
60+-- | Like 'mapMaybe' but indicates whether the resulting container is empty
61+mapMaybeNoNull :: (a -> Maybe b)
62+ -> MonoidalMap token a
63+ -> Maybe (MonoidalMap token b)
64+mapMaybeNoNull f as =
65+ let bs = mapMaybe f as
66+ in if null bs
67+ then Nothing
68+ else Just bs
69+
70+-- TODO: Move instances to `Reflex.Patch`
71+-- | Displays a 'MonoidalMap' as a tree. See 'Data.Map.Lazy.showTree' for details.
72+showTree :: forall k a. (Show k, Show a) => MonoidalMap k a -> String
73+showTree = coerce (Map.showTree :: Map k a -> String)
74+
75+-- | Displays a 'MonoidalMap' as a tree, using the supplied function to convert nodes to string.
76+showTreeWith :: forall k a. (k -> a -> String) -> Bool -> Bool -> MonoidalMap k a -> String
77+showTreeWith = coerce (Map.showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String)
78+
79+instance Default (MonoidalMap k a) where
80+ def = empty
src/Data/FastMutableIntMap.hsnew file+93
@@ -0,0 +1,93 @@
1+{-# LANGUAGE TypeFamilies #-}
2+-- |
3+-- Module:
4+-- Data.FastMutableIntMap
5+-- Description:
6+-- A mutable version of 'IntMap'
7+module Data.FastMutableIntMap
8+ ( FastMutableIntMap
9+ , new
10+ , newEmpty
11+ , insert
12+ , isEmpty
13+ , getFrozenAndClear
14+ , size
15+ , applyPatch
16+ , PatchIntMap (..)
17+ , traverseIntMapPatchWithKey
18+ , lookup
19+ , forIntersectionWithImmutable_
20+ , for_
21+ , patchIntMapNewElements
22+ , patchIntMapNewElementsMap
23+ , getDeletions
24+ ) where
25+
26+--TODO: Pure JS version
27+--TODO: Fast copy to FastIntMap
28+--TODO: Fast patch type
29+
30+import Prelude hiding (lookup)
31+
32+import Control.Monad.IO.Class
33+import Data.Foldable (traverse_)
34+import Data.IntMap.Strict (IntMap)
35+import qualified Data.IntMap.Strict as IntMap
36+import Data.IORef
37+import Reflex.Patch.Class
38+import Reflex.Patch.IntMap
39+
40+-- | A 'FastMutableIntMap' holds a map of values of type @a@ and allows low-overhead modifications via IO.
41+-- Operations on 'FastMutableIntMap' run in IO.
42+newtype FastMutableIntMap a = FastMutableIntMap (IORef (IntMap a))
43+
44+-- | Create a new 'FastMutableIntMap' out of an 'IntMap'
45+new :: IntMap a -> IO (FastMutableIntMap a)
46+new m = FastMutableIntMap <$> newIORef m
47+
48+-- | Create a new empty 'FastMutableIntMap'
49+newEmpty :: IO (FastMutableIntMap a)
50+newEmpty = FastMutableIntMap <$> newIORef IntMap.empty
51+
52+-- | Insert an element into a 'FastMutableIntMap' at the given key
53+insert :: FastMutableIntMap a -> Int -> a -> IO ()
54+insert (FastMutableIntMap r) k v = modifyIORef' r $ IntMap.insert k v
55+
56+-- | Attempt to lookup an element by key in a 'FastMutableIntMap'
57+lookup :: FastMutableIntMap a -> Int -> IO (Maybe a)
58+lookup (FastMutableIntMap r) k = IntMap.lookup k <$> readIORef r
59+
60+-- | Runs the provided action over the intersection of a 'FastMutableIntMap' and an 'IntMap'
61+forIntersectionWithImmutable_ :: MonadIO m => FastMutableIntMap a -> IntMap b -> (a -> b -> m ()) -> m ()
62+forIntersectionWithImmutable_ (FastMutableIntMap r) b f = do
63+ a <- liftIO $ readIORef r
64+ traverse_ (uncurry f) $ IntMap.intersectionWith (,) a b
65+
66+-- | Runs the provided action over the values of a 'FastMutableIntMap'
67+for_ :: MonadIO m => FastMutableIntMap a -> (a -> m ()) -> m ()
68+for_ (FastMutableIntMap r) f = do
69+ a <- liftIO $ readIORef r
70+ traverse_ f a
71+
72+-- | Checks whether a 'FastMutableIntMap' is empty
73+isEmpty :: FastMutableIntMap a -> IO Bool
74+isEmpty (FastMutableIntMap r) = IntMap.null <$> readIORef r
75+
76+-- | Retrieves the size of a 'FastMutableIntMap'
77+size :: FastMutableIntMap a -> IO Int
78+size (FastMutableIntMap r) = IntMap.size <$> readIORef r
79+
80+-- | Make an immutable snapshot of the datastructure and clear it
81+getFrozenAndClear :: FastMutableIntMap a -> IO (IntMap a)
82+getFrozenAndClear (FastMutableIntMap r) = do
83+ result <- readIORef r
84+ writeIORef r IntMap.empty
85+ return result
86+
87+-- | Updates the value of a 'FastMutableIntMap' with the given patch (see 'Reflex.Patch.IntMap'),
88+-- and returns an 'IntMap' with the modified keys and values.
89+applyPatch :: FastMutableIntMap a -> PatchIntMap a -> IO (IntMap a)
90+applyPatch (FastMutableIntMap r) p@(PatchIntMap m) = do
91+ v <- readIORef r
92+ writeIORef r $! applyAlways p v
93+ return $ IntMap.intersection v m
src/Data/FastWeakBag.hsnew file+156
@@ -0,0 +1,156 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ExistentialQuantification #-}
3+#ifdef USE_REFLEX_OPTIMIZER
4+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5+#endif
6+#ifdef GHCJS_FAST_WEAK
7+{-# LANGUAGE ForeignFunctionInterface #-}
8+{-# LANGUAGE JavaScriptFFI #-}
9+#endif
10+-- | This module defines the 'FastWeakBag' type, which represents a mutable
11+-- collection of items that does not cause the items to be retained in memory.
12+-- This is useful for situations where a value needs to be inspected or modified
13+-- if it is still alive, but can be ignored if it is dead.
14+module Data.FastWeakBag
15+ ( FastWeakBag
16+ , FastWeakBagTicket
17+ , empty
18+ , isEmpty
19+ , insert
20+ , traverse
21+ , remove
22+ -- * Internal functions
23+ -- These will not always be available.
24+#ifndef GHCJS_FAST_WEAK
25+ , _weakBag_children --TODO: Don't export this
26+#endif
27+ ) where
28+
29+import Prelude hiding (traverse)
30+
31+import Control.Monad
32+import Control.Monad.IO.Class
33+
34+#ifdef GHCJS_FAST_WEAK
35+import GHCJS.Types
36+import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)
37+#else
38+import Control.Exception
39+import Data.IntMap.Strict (IntMap)
40+import qualified Data.IntMap.Strict as IntMap
41+import Data.IORef
42+import System.Mem.Weak
43+#endif
44+
45+-- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them -
46+-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
47+-- alive, the 'FastWeakBag' will continue to refer to them.
48+#ifdef GHCJS_FAST_WEAK
49+newtype FastWeakBag a = FastWeakBag JSVal
50+#else
51+data FastWeakBag a = FastWeakBag
52+ { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
53+ , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'
54+ }
55+#endif
56+
57+-- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned. If
58+-- the caller retains the ticket, the item is guranteed to stay in memory (and
59+-- thus in the 'FastWeakBag'). The ticket can also be used to remove the item from
60+-- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.
61+#ifdef GHCJS_FAST_WEAK
62+newtype FastWeakBagTicket a = FastWeakBagTicket JSVal
63+#else
64+data FastWeakBagTicket a = FastWeakBagTicket
65+ { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
66+ , _weakBagTicket_item :: {-# NOUNPACK #-} !a
67+ }
68+#endif
69+
70+-- | Insert an item into a 'FastWeakBag'.
71+{-# INLINE insert #-}
72+insert :: a -- ^ The item
73+ -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into
74+ -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item
75+ -- is retained and allows the item to be removed.
76+#ifdef GHCJS_FAST_WEAK
77+insert a wb = js_insert (unsafeToRawJSVal a) wb
78+foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)
79+#else
80+insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do
81+ a' <- evaluate a
82+ myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
83+ let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())
84+ wa <- mkWeakPtr a' $ Just cleanup
85+ atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
86+ return $ FastWeakBagTicket
87+ { _weakBagTicket_weakItem = wa
88+ , _weakBagTicket_item = a'
89+ }
90+#endif
91+
92+-- | Create an empty 'FastWeakBag'.
93+{-# INLINE empty #-}
94+empty :: IO (FastWeakBag a)
95+#ifdef GHCJS_FAST_WEAK
96+empty = js_empty
97+foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)
98+#else
99+empty = {-# SCC "empty" #-} do
100+ nextId <- newIORef 1
101+ children <- newIORef IntMap.empty
102+ let bag = FastWeakBag
103+ { _weakBag_nextId = nextId
104+ , _weakBag_children = children
105+ }
106+ return bag
107+#endif
108+
109+-- | Check whether a 'FastWeakBag' is empty.
110+{-# INLINE isEmpty #-}
111+isEmpty :: FastWeakBag a -> IO Bool
112+#ifdef GHCJS_FAST_WEAK
113+isEmpty = js_isEmpty
114+foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time
115+#else
116+isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)
117+#endif
118+
119+{-# INLINE traverse #-}
120+-- | Visit every node in the given list. If new nodes are appended during the
121+-- traversal, they will not be visited. Every live node that was in the list
122+-- when the traversal began will be visited exactly once; however, no guarantee
123+-- is made about the order of the traversal.
124+traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
125+#ifdef GHCJS_FAST_WEAK
126+traverse wb f = do
127+ let go cursor = when (not $ js_isNull cursor) $ do
128+ val <- liftIO $ js_getTicketValue cursor
129+ f $ unsafeFromRawJSVal val
130+ go =<< liftIO (js_getNext (FastWeakBagTicket cursor))
131+ go =<< liftIO (js_getInitial wb)
132+foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
133+foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal
134+--TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag
135+foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
136+#else
137+traverse (FastWeakBag _ children) f = {-# SCC "traverse" #-} do
138+ cs <- liftIO $ readIORef children
139+ forM_ cs $ \c -> do
140+ ma <- liftIO $ deRefWeak c
141+ mapM_ f ma
142+#endif
143+
144+-- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times
145+-- on the same 'FastWeakBagTicket'.
146+{-# INLINE remove #-}
147+remove :: FastWeakBagTicket a -> IO ()
148+#ifdef GHCJS_FAST_WEAK
149+remove = js_remove
150+foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here
151+#else
152+remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w
153+#endif
154+--TODO: Should 'remove' also drop the reference to the item?
155+
156+--TODO: can/should we provide a null FastWeakBagTicket?
src/Data/Functor/Misc.hs+7−4
@@ -6,10 +6,14 @@
66{-# LANGUAGE GADTs #-}
77{-# LANGUAGE LambdaCase #-}
88{-# LANGUAGE MultiParamTypeClasses #-}
9+{-# LANGUAGE PatternSynonyms #-}
910{-# LANGUAGE PolyKinds #-}
1011{-# LANGUAGE RankNTypes #-}
1112{-# LANGUAGE ScopedTypeVariables #-}
1213{-# LANGUAGE StandaloneDeriving #-}
14+#ifdef USE_REFLEX_OPTIMIZER
15+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
16+#endif
1317-- | This module provides types and functions with no particular theme, but
1418-- which are relevant to the use of 'Functor'-based datastructures like
1519-- 'Data.Dependent.Map.DMap'.
@@ -37,19 +41,18 @@ module Data.Functor.Misc
3741 ) where
3842
3943import Control.Applicative ((<$>))
44+import Control.Monad.Identity
4045import Data.Dependent.Map (DMap)
4146import qualified Data.Dependent.Map as DMap
4247import Data.Dependent.Sum
43−import Data.Functor.Identity
4448import Data.GADT.Compare
4549import Data.GADT.Show
4650import Data.IntMap (IntMap)
4751import qualified Data.IntMap as IntMap
4852import Data.Map (Map)
4953import qualified Data.Map as Map
50−import Data.Some (Some, mkSome)
54+import Data.Some (Some(Some))
5155import Data.These
52−import Data.Type.Equality ((:~:)(Refl))
5356import Data.Typeable hiding (Refl)
5457
5558--------------------------------------------------------------------------------
@@ -116,7 +119,7 @@ intMapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=
116119-- | Convert a 'DMap' to a regular 'Map' by forgetting the types associated with
117120-- the keys, using a function to remove the wrapping 'Functor'
118121weakenDMapWith :: (forall a. v a -> v') -> DMap k v -> Map (Some k) v'
119−weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (mkSome k, f v)) . DMap.toAscList
122+weakenDMapWith f = Map.fromDistinctAscList . map (\(k :=> v) -> (Some k, f v)) . DMap.toAscList
120123
121124--------------------------------------------------------------------------------
122125-- WrapArg
src/Data/Map/Misc.hsnew file+71
@@ -0,0 +1,71 @@
1+{-# LANGUAGE LambdaCase #-}
2+-- | Additional functions for manipulating 'Map's.
3+module Data.Map.Misc
4+ (
5+ -- * Working with Maps
6+ diffMapNoEq
7+ , diffMap
8+ , applyMap
9+ , mapPartitionEithers
10+ , applyMapKeysSet
11+ ) where
12+
13+import Data.Align
14+import Data.Map (Map)
15+import qualified Data.Map as Map
16+import Data.Maybe
17+import Data.Set (Set)
18+import qualified Data.Set as Set
19+import Data.These
20+
21+-- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new@ respectively. @Just@ represents an association present in @new@ and @Nothing@
22+-- represents an association only present in @old@ but no longer present in @new@.
23+--
24+-- Similar to 'diffMap' but doesn't require 'Eq' on the values, thus can't tell if a value has changed or not.
25+diffMapNoEq :: (Ord k) => Map k v -> Map k v -> Map k (Maybe v)
26+diffMapNoEq olds news = flip Map.mapMaybe (align olds news) $ \case
27+ This _ -> Just Nothing
28+ These _ new -> Just $ Just new
29+ That new -> Just $ Just new
30+
31+-- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new respectively. @Just@ represents an association present in @new@ and either not
32+-- present in @old@ or where the value has changed. @Nothing@ represents an association only present in @old@ but no longer present in @new@.
33+--
34+-- See also 'diffMapNoEq' for a similar but weaker version which does not require 'Eq' on the values but thus can't indicated a value not changing between
35+-- @old@ and @new@ with @Nothing@.
36+diffMap :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (Maybe v)
37+diffMap olds news = flip Map.mapMaybe (align olds news) $ \case
38+ This _ -> Just Nothing
39+ These old new
40+ | old == new -> Nothing
41+ | otherwise -> Just $ Just new
42+ That new -> Just $ Just new
43+
44+-- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new map from the given input @'Map' k v@.
45+--
46+-- See also 'Reflex.Patch.Map' and 'Reflex.Patch.MapWithMove'.
47+applyMap :: Ord k => Map k (Maybe v) -> Map k v -> Map k v
48+applyMap patch old = insertions `Map.union` (old `Map.difference` deletions)
49+ where (deletions, insertions) = Map.mapEither maybeToEither patch
50+ maybeToEither = \case
51+ Nothing -> Left ()
52+ Just r -> Right r
53+
54+-- |Split a @'Map' k (Either a b)@ into @Map k a@ and @Map k b@, equivalent to @'Map.mapEither' id@
55+{-# DEPRECATED mapPartitionEithers "Use 'mapEither' instead" #-}
56+mapPartitionEithers :: Map k (Either a b) -> (Map k a, Map k b)
57+mapPartitionEithers = Map.mapEither id
58+
59+-- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new @'Set' k@ from the given input set.
60+--
61+-- Equivalent to:
62+--
63+-- @
64+-- applyMapKeysSet patch ('Map.keysSet' m) == 'Map.keysSet' ('applyMap' patch m)
65+-- @
66+--
67+-- but avoids the intervening @Map@ and needs no values.
68+applyMapKeysSet :: Ord k => Map k (Maybe v) -> Set k -> Set k
69+applyMapKeysSet patch old = Map.keysSet insertions `Set.union` (old `Set.difference` Map.keysSet deletions)
70+ where (insertions, deletions) = Map.partition isJust patch
71+
src/Data/Monoid/DecidablyEmpty.hsdeleted−115
@@ -1,115 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DefaultSignatures #-}
3−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4−{-# LANGUAGE StandaloneDeriving #-}
5−{-# LANGUAGE TypeOperators #-}
6−
7−-- TODO upstream somwhere else?
8−module Data.Monoid.DecidablyEmpty where
9−
10−import Data.Functor.Identity
11−import Data.Functor.Const
12−import Data.Monoid
13−import Data.Maybe (isNothing)
14−#if MIN_VERSION_base(4,11,0)
15−import Data.Ord
16−#endif
17−import Data.Proxy
18−import Data.Semigroup hiding (First, Last)
19−#if MIN_VERSION_base(4,12,0)
20−import GHC.Generics
21−#endif
22−
23−import qualified Data.IntSet as IntSet
24−import qualified Data.IntMap as IntMap
25−import qualified Data.Map as Map
26−import qualified Data.Sequence as Seq
27−import qualified Data.Set as Set
28−
29−import Data.GADT.Compare
30−import qualified Data.Dependent.Map as DMap
31−
32−-- | A 'DecidablyEmpty' is one where it can be computed whether or not an
33−-- arbitrary value is 'mempty'.
34−--
35−-- By using this class rather than 'Eq', we avoid unnecessary constraining the
36−-- contents of 'Functor's. This makes it possible to efficiently combine and/or
37−-- nest patch maps with 'Eq'-lacking values (e.g. functions) at the leaves.
38−class Monoid a => DecidablyEmpty a where
39− isEmpty :: a -> Bool
40− default isEmpty :: Eq a => a -> Bool
41− isEmpty = (==) mempty
42−
43−-- base
44−
45−instance DecidablyEmpty Ordering
46−instance DecidablyEmpty ()
47−instance DecidablyEmpty Any
48−instance DecidablyEmpty All
49−-- instance DecidablyEmpty Lifetime
50−-- instance DecidablyEmpty Event
51−instance DecidablyEmpty [a] where
52− isEmpty = null
53−instance
54−#if MIN_VERSION_base(4,11,0)
55− Semigroup a
56−#else
57− Monoid a
58−#endif
59− => DecidablyEmpty (Maybe a) where
60− isEmpty = isNothing
61−deriving instance (Num a, DecidablyEmpty a) => DecidablyEmpty (Product a)
62−deriving instance (DecidablyEmpty a, Num a) => DecidablyEmpty (Sum a)
63−deriving instance DecidablyEmpty a => DecidablyEmpty (Dual a)
64−instance DecidablyEmpty (First a) where
65− isEmpty (First a) = isNothing a
66−instance DecidablyEmpty (Last a) where
67− isEmpty (Last a) = isNothing a
68−deriving instance DecidablyEmpty a => DecidablyEmpty (Identity a)
69−instance Semigroup a => DecidablyEmpty (Option a) where
70− isEmpty (Option a) = isNothing a
71−deriving instance DecidablyEmpty m => DecidablyEmpty (WrappedMonoid m)
72−instance (Ord a, Bounded a) => DecidablyEmpty (Max a)
73−instance (Ord a, Bounded a) => DecidablyEmpty (Min a)
74−instance DecidablyEmpty (Proxy s)
75−deriving instance DecidablyEmpty a => DecidablyEmpty (Const a b)
76−#if MIN_VERSION_base(4,11,0)
77−deriving instance DecidablyEmpty a => DecidablyEmpty (Down a)
78−#endif
79−#if MIN_VERSION_base(4,12,0)
80−deriving instance DecidablyEmpty p => DecidablyEmpty (Par1 p)
81−instance DecidablyEmpty (U1 p)
82−deriving instance DecidablyEmpty (f p) => DecidablyEmpty (Rec1 f p)
83−deriving instance DecidablyEmpty (f p) => DecidablyEmpty (M1 i c f p)
84−deriving instance DecidablyEmpty c => DecidablyEmpty (K1 i c p)
85−instance (DecidablyEmpty (f p), DecidablyEmpty (g p)) => DecidablyEmpty ((f :*: g) p) where
86− isEmpty (x :*: y) = isEmpty x && isEmpty y
87−deriving instance DecidablyEmpty (f (g p)) => DecidablyEmpty ((f :.: g) p)
88−#endif
89−
90−instance (DecidablyEmpty a, DecidablyEmpty b) => DecidablyEmpty (a, b) where
91− isEmpty (a, b) = isEmpty a && isEmpty b
92−instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c) => DecidablyEmpty (a, b, c) where
93− isEmpty (a, b, c) = isEmpty a && isEmpty b && isEmpty c
94−instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d) => DecidablyEmpty (a, b, c, d) where
95− isEmpty (a, b, c, d) = isEmpty a && isEmpty b && isEmpty c && isEmpty d
96−instance (DecidablyEmpty a, DecidablyEmpty b, DecidablyEmpty c, DecidablyEmpty d, DecidablyEmpty e) => DecidablyEmpty (a, b, c, d, e) where
97− isEmpty (a, b, c, d, e) = isEmpty a && isEmpty b && isEmpty c && isEmpty d && isEmpty e
98−
99−-- containers
100−
101−instance DecidablyEmpty IntSet.IntSet where
102− isEmpty = IntSet.null
103−instance DecidablyEmpty (IntMap.IntMap v) where
104− isEmpty = IntMap.null
105−instance Ord k => DecidablyEmpty (Map.Map k v) where
106− isEmpty = Map.null
107−instance DecidablyEmpty (Seq.Seq v) where
108− isEmpty = Seq.null
109−instance Ord k => DecidablyEmpty (Set.Set k) where
110− isEmpty = Set.null
111−
112−-- dependent-map
113−
114−instance GCompare k => DecidablyEmpty (DMap.DMap k v) where
115− isEmpty = DMap.null
src/Data/Patch.hsdeleted−95
@@ -1,95 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3−{-# LANGUAGE StandaloneDeriving #-}
4−{-# LANGUAGE TypeFamilies #-}
5−{-# LANGUAGE TypeOperators #-}
6−-- |
7−-- Module:
8−-- Data.Patch
9−-- Description:
10−-- This module defines the 'Patch' class.
11−module Data.Patch
12− ( module Data.Patch
13− , module X
14− ) where
15−
16−import Control.Applicative
17−import Data.Functor.Const (Const (..))
18−import Data.Functor.Identity
19−import Data.Map.Monoidal (MonoidalMap)
20−import Data.Proxy
21−#if !MIN_VERSION_base(4,11,0)
22−import Data.Semigroup (Semigroup (..))
23−#endif
24−import GHC.Generics
25−
26−import Data.Semigroup.Additive as X
27−import Data.Patch.Class as X
28−import Data.Patch.DMap as X hiding (getDeletions)
29−import Data.Patch.DMapWithMove as X
30− ( PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove
31− , patchDMapWithMoveToPatchMapWithMoveWith
32− , traversePatchDMapWithMoveWithKey, unPatchDMapWithMove
33− , unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith
34− )
35−import Data.Patch.IntMap as X hiding (getDeletions)
36−import Data.Patch.Map as X
37−import Data.Patch.MapWithMove as X
38− ( PatchMapWithMove, patchMapWithMoveNewElements
39− , patchMapWithMoveNewElementsMap, unPatchMapWithMove
40− , unsafePatchMapWithMove
41− )
42−
43−-- | A 'Group' is a 'Monoid' where every element has an inverse.
44−class (Semigroup q, Monoid q) => Group q where
45− negateG :: q -> q
46− (~~) :: q -> q -> q
47− r ~~ s = r <> negateG s
48−
49−-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
50−newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
51−
52−instance Additive p => Patch (AdditivePatch p) where
53− type PatchTarget (AdditivePatch p) = p
54− apply (AdditivePatch p) q = Just $ p <> q
55−
56−instance (Ord k, Group q) => Group (MonoidalMap k q) where
57− negateG = fmap negateG
58−
59−-- | Trivial group.
60−instance Group () where
61− negateG _ = ()
62− _ ~~ _ = ()
63−
64−-- | Product group. A Pair of groups gives rise to a group
65−instance (Group a, Group b) => Group (a, b) where
66− negateG (a, b) = (negateG a, negateG b)
67− (a, b) ~~ (c, d) = (a ~~ c, b ~~ d)
68−
69−-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
70−-- Base does not define Monoid (Compose f g a) so this is the best we can
71−-- really do for functor composition.
72−instance Group (f (g a)) => Group ((f :.: g) a) where
73− negateG (Comp1 xs) = Comp1 (negateG xs)
74− Comp1 xs ~~ Comp1 ys = Comp1 (xs ~~ ys)
75−
76−-- | Product of groups, Functor style.
77−instance (Group (f a), Group (g a)) => Group ((f :*: g) a) where
78− negateG (a :*: b) = negateG a :*: negateG b
79− (a :*: b) ~~ (c :*: d) = (a ~~ c) :*: (b ~~ d)
80−
81−-- | Trivial group, Functor style
82−instance Group (Proxy x) where
83− negateG _ = Proxy
84− _ ~~ _ = Proxy
85−
86−-- | Const lifts groups into a functor.
87−deriving instance Group a => Group (Const a x)
88−
89−-- | Identity lifts groups pointwise (at only one point)
90−deriving instance Group a => Group (Identity a)
91−
92−-- | Functions lift groups pointwise.
93−instance Group b => Group (a -> b) where
94− negateG f = negateG . f
95− (~~) = liftA2 (~~)
src/Data/Patch/MapWithMove.hsdeleted−312
@@ -1,312 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveTraversable #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE PatternGuards #-}
9−{-# LANGUAGE PatternSynonyms #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE StandaloneDeriving #-}
12−{-# LANGUAGE TemplateHaskell #-}
13−{-# LANGUAGE TypeApplications #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE ViewPatterns #-}
16−
17−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
18−-- another
19−module Data.Patch.MapWithMove
20− ( PatchMapWithMove
21− ( PatchMapWithMove
22− , unPatchMapWithMove
23− , ..
24− )
25− , patchMapWithMove
26− , patchMapWithMoveInsertAll
27− , insertMapKey
28− , moveMapKey
29− , swapMapKey
30− , deleteMapKey
31− , unsafePatchMapWithMove
32− , patchMapWithMoveNewElements
33− , patchMapWithMoveNewElementsMap
34− , patchThatSortsMapWith
35− , patchThatChangesAndSortsMapWith
36− , patchThatChangesMap
37−
38− -- * Node Info
39− , NodeInfo
40− ( NodeInfo
41− , _nodeInfo_to
42− , _nodeInfo_from
43− , ..
44− )
45− , bitraverseNodeInfo
46− , nodeInfoMapFrom
47− , nodeInfoMapMFrom
48− , nodeInfoSetTo
49−
50− -- * From
51− , From
52− ( From_Insert
53− , From_Delete
54− , From_Move
55− , ..
56− )
57− , bitraverseFrom
58−
59− -- * To
60− , To
61− ) where
62−
63−import Data.Coerce
64−import Data.Kind (Type)
65−import Data.Patch.Class
66−import Data.Patch.MapWithPatchingMove (PatchMapWithPatchingMove(..), To)
67−import qualified Data.Patch.MapWithPatchingMove as PM -- already a transparent synonym
68−
69−import Control.Lens
70−import Data.List
71−import Data.Map (Map)
72−import qualified Data.Map as Map
73−import Data.Proxy
74−#if !MIN_VERSION_base(4,11,0)
75−import Data.Semigroup (Semigroup (..))
76−#endif
77−import Data.Traversable (foldMapDefault)
78−
79−-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
80−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
81−-- and vice versa. There should never be any unpaired From/To keys.
82−newtype PatchMapWithMove k (v :: Type) = PatchMapWithMove'
83− { -- | Extract the underlying 'PatchMapWithPatchingMove k (Proxy v)'
84− unPatchMapWithMove' :: PatchMapWithPatchingMove k (Proxy v)
85− }
86− deriving ( Show, Read, Eq, Ord
87−-- Haddock cannot handle documentation here before GHC 8.6
88− ,
89−#if __GLASGOW_HASKELL__ >= 806
90− -- | Compose patches having the same effect as applying the
91− -- patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p .
92− -- 'applyAlways' q@
93−#endif
94− Semigroup
95− , Monoid
96− )
97−
98−pattern Coerce :: Coercible a b => a -> b
99−pattern Coerce x <- (coerce -> x)
100− where Coerce x = coerce x
101−
102−{-# COMPLETE PatchMapWithMove #-}
103−pattern PatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
104−-- | Extract the representation of the 'PatchMapWithMove' as a map of
105−-- 'NodeInfo'.
106−unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
107−pattern PatchMapWithMove { unPatchMapWithMove } = PatchMapWithMove' (PatchMapWithPatchingMove (Coerce unPatchMapWithMove))
108−
109−_PatchMapWithMove
110− :: Iso
111− (PatchMapWithMove k0 v0)
112− (PatchMapWithMove k1 v1)
113− (Map k0 (NodeInfo k0 v0))
114− (Map k1 (NodeInfo k1 v1))
115−_PatchMapWithMove = iso unPatchMapWithMove PatchMapWithMove
116−
117−instance Functor (PatchMapWithMove k) where
118− fmap f = runIdentity . traverse (Identity . f)
119−
120−instance Foldable (PatchMapWithMove k) where
121− foldMap = foldMapDefault
122−
123−instance Traversable (PatchMapWithMove k) where
124− traverse =
125− _PatchMapWithMove .
126− traverse .
127− traverse
128−
129−instance FunctorWithIndex k (PatchMapWithMove k)
130−instance FoldableWithIndex k (PatchMapWithMove k)
131−instance TraversableWithIndex k (PatchMapWithMove k) where
132− itraverse = itraversed . Indexed
133− itraversed =
134− _PatchMapWithMove .>
135− itraversed <.
136− traverse
137−
138−-- | Create a 'PatchMapWithMove', validating it
139−patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
140−patchMapWithMove = fmap PatchMapWithMove' . PM.patchMapWithPatchingMove . coerce
141−
142−-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
143−patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
144−patchMapWithMoveInsertAll = PatchMapWithMove' . PM.patchMapWithPatchingMoveInsertAll
145−
146−-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
147−insertMapKey :: k -> v -> PatchMapWithMove k v
148−insertMapKey k v = PatchMapWithMove' $ PM.insertMapKey k v
149−
150−-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
151−--
152−-- @
153−-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
154−-- @
155−moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
156−moveMapKey src dst = PatchMapWithMove' $ PM.moveMapKey src dst
157−
158−-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
159−--
160−-- @
161−-- let aMay = Map.lookup a map
162−-- bMay = Map.lookup b map
163−-- in maybe id (Map.insert a) (bMay <> aMay)
164−-- . maybe id (Map.insert b) (aMay <> bMay)
165−-- . Map.delete a . Map.delete b $ map
166−-- @
167−swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
168−swapMapKey src dst = PatchMapWithMove' $ PM.swapMapKey src dst
169−
170−-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
171−deleteMapKey :: k -> PatchMapWithMove k v
172−deleteMapKey = PatchMapWithMove' . PM.deleteMapKey
173−
174−-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
175−--
176−-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
177−unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
178−unsafePatchMapWithMove = coerce PM.unsafePatchMapWithPatchingMove
179−
180−-- | Apply the insertions, deletions, and moves to a given 'Map'
181−instance Ord k => Patch (PatchMapWithMove k v) where
182− type PatchTarget (PatchMapWithMove k v) = Map k v
183− apply (PatchMapWithMove' p) = apply p
184−
185−-- | Returns all the new elements that will be added to the 'Map'.
186−patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
187−patchMapWithMoveNewElements = PM.patchMapWithPatchingMoveNewElements . unPatchMapWithMove'
188−
189−-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
190−patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
191−patchMapWithMoveNewElementsMap = PM.patchMapWithPatchingMoveNewElementsMap . unPatchMapWithMove'
192−
193−-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
194−-- its values using the given ordering function. The set keys of the 'Map' is
195−-- not changed.
196−patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
197−patchThatSortsMapWith cmp = PatchMapWithMove' . PM.patchThatSortsMapWith cmp
198−
199−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
200−-- will produce a 'Map' with the same values as the second 'Map' but with the
201−-- values sorted with the given ordering function.
202−patchThatChangesAndSortsMapWith :: (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
203−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
204− where newList = Map.toList newByIndexUnsorted
205− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
206−
207−-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
208−-- will produce the second 'Map'.
209−patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
210−patchThatChangesMap oldByIndex newByIndex = PatchMapWithMove' $
211− PM.patchThatChangesMap oldByIndex newByIndex
212−
213−--
214−-- NodeInfo
215−--
216−
217−-- | Holds the information about each key: where its new value should come from,
218−-- and where its old value should go to
219−newtype NodeInfo k (v :: Type) = NodeInfo' { unNodeInfo' :: PM.NodeInfo k (Proxy v) }
220−
221−deriving instance (Show k, Show p) => Show (NodeInfo k p)
222−deriving instance (Read k, Read p) => Read (NodeInfo k p)
223−deriving instance (Eq k, Eq p) => Eq (NodeInfo k p)
224−deriving instance (Ord k, Ord p) => Ord (NodeInfo k p)
225−
226−{-# COMPLETE NodeInfo #-}
227−pattern NodeInfo :: To k -> From k v -> NodeInfo k v
228−_nodeInfo_to :: NodeInfo k v -> To k
229−_nodeInfo_from :: NodeInfo k v -> From k v
230−pattern NodeInfo { _nodeInfo_to, _nodeInfo_from } = NodeInfo'
231− PM.NodeInfo
232− { PM._nodeInfo_to = _nodeInfo_to
233− , PM._nodeInfo_from = Coerce _nodeInfo_from
234− }
235−
236−_NodeInfo
237− :: Iso
238− (NodeInfo k0 v0)
239− (NodeInfo k1 v1)
240− (PM.NodeInfo k0 (Proxy v0))
241− (PM.NodeInfo k1 (Proxy v1))
242−_NodeInfo = iso unNodeInfo' NodeInfo'
243−
244−instance Functor (NodeInfo k) where
245− fmap f = runIdentity . traverse (Identity . f)
246−
247−instance Foldable (NodeInfo k) where
248− foldMap = foldMapDefault
249−
250−instance Traversable (NodeInfo k) where
251− traverse = bitraverseNodeInfo pure
252−
253−bitraverseNodeInfo
254− :: Applicative f
255− => (k0 -> f k1)
256− -> (v0 -> f v1)
257− -> NodeInfo k0 v0 -> f (NodeInfo k1 v1)
258−bitraverseNodeInfo fk fv = fmap NodeInfo'
259− . PM.bitraverseNodeInfo fk (\ ~Proxy -> pure Proxy) fv
260− . coerce
261−
262−-- | Change the 'From' value of a 'NodeInfo'
263−nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
264−nodeInfoMapFrom f = coerce $ PM.nodeInfoMapFrom (unFrom' . f . From')
265−
266−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
267−-- 'Applicative', 'Monad', etc.) action to get the new value
268−nodeInfoMapMFrom
269− :: Functor f
270− => (From k v -> f (From k v))
271− -> NodeInfo k v -> f (NodeInfo k v)
272−nodeInfoMapMFrom f = fmap NodeInfo'
273− . PM.nodeInfoMapMFrom (fmap unFrom' . f . From')
274− . coerce
275−
276−-- | Set the 'To' field of a 'NodeInfo'
277−nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
278−nodeInfoSetTo = coerce . PM.nodeInfoSetTo
279−
280−--
281−-- From
282−--
283−
284−-- | Describe how a key's new value should be produced
285−newtype From k (v :: Type) = From' { unFrom' :: PM.From k (Proxy v) }
286−
287−{-# COMPLETE From_Insert, From_Delete, From_Move #-}
288−
289−-- | Insert the given value here
290−pattern From_Insert :: v -> From k v
291−pattern From_Insert v = From' (PM.From_Insert v)
292−
293−-- | Delete the existing value, if any, from here
294−pattern From_Delete :: From k v
295−pattern From_Delete = From' PM.From_Delete
296−
297−-- | Move the value here from the given key
298−pattern From_Move :: k -> From k v
299−pattern From_Move k = From' (PM.From_Move k Proxy)
300−
301−bitraverseFrom
302− :: Applicative f
303− => (k0 -> f k1)
304− -> (v0 -> f v1)
305− -> From k0 v0 -> f (From k1 v1)
306−bitraverseFrom fk fv = fmap From'
307− . PM.bitraverseFrom fk (\ ~Proxy -> pure Proxy) fv
308− . coerce
309−
310−makeWrapped ''PatchMapWithMove
311−makeWrapped ''NodeInfo
312−makeWrapped ''From
src/Data/Patch/MapWithPatchingMove.hsdeleted−432
@@ -1,432 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE PatternGuards #-}
8−{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE StandaloneDeriving #-}
10−{-# LANGUAGE TemplateHaskell #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE UndecidableInstances #-}
13−
14−-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15−-- another
16−module Data.Patch.MapWithPatchingMove
17− ( PatchMapWithPatchingMove (..)
18− , patchMapWithPatchingMove
19− , patchMapWithPatchingMoveInsertAll
20− , insertMapKey
21− , moveMapKey
22− , swapMapKey
23− , deleteMapKey
24− , unsafePatchMapWithPatchingMove
25− , patchMapWithPatchingMoveNewElements
26− , patchMapWithPatchingMoveNewElementsMap
27− , patchThatSortsMapWith
28− , patchThatChangesAndSortsMapWith
29− , patchThatChangesMap
30−
31− -- * Node Info
32− , NodeInfo (..)
33− , bitraverseNodeInfo
34− , nodeInfoMapFrom
35− , nodeInfoMapMFrom
36− , nodeInfoSetTo
37−
38− -- * From
39− , From(..)
40− , bitraverseFrom
41−
42− -- * To
43− , To
44−
45− -- TODO internals module
46− , Fixup (..)
47− ) where
48−
49−import Data.Patch.Class
50−
51−import Control.Lens hiding (from, to)
52−import Control.Lens.TH (makeWrapped)
53−import Data.Align (align)
54−import Data.Foldable (toList)
55−import Data.Function
56−import Data.List
57−import Data.Map (Map)
58−import qualified Data.Map as Map
59−import Data.Maybe
60−#if !MIN_VERSION_base(4,11,0)
61−import Data.Semigroup (Semigroup (..))
62−#endif
63−import Data.Monoid.DecidablyEmpty
64−import Data.Set (Set)
65−import qualified Data.Set as Set
66−import Data.These (These (..))
67−
68−-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
69−-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
70−-- and vice versa. There should never be any unpaired From/To keys.
71−newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
72− { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
73− unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
74− }
75−
76−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
77−deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
78−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
79−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
80−
81−deriving instance ( Ord k
82−#if !MIN_VERSION_base(4,11,0)
83− , Semigroup p
84−#endif
85− , DecidablyEmpty p
86− , Patch p
87− ) => DecidablyEmpty (PatchMapWithPatchingMove k p)
88−
89−-- | Create a 'PatchMapWithPatchingMove', validating it
90−patchMapWithPatchingMove
91− :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
92−patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
93− where valid = forwardLinks == backwardLinks
94− forwardLinks = Map.mapMaybe _nodeInfo_to m
95− backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
96− case _nodeInfo_from p of
97− From_Move from _ -> Just (from, to)
98− _ -> Nothing
99−
100−-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
101−patchMapWithPatchingMoveInsertAll
102− :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
103−patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
104− { _nodeInfo_from = From_Insert v
105− , _nodeInfo_to = Nothing
106− }
107−
108−-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
109−insertMapKey
110− :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
111−insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
112−
113−-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
114−--
115−-- @
116−-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
117−-- @
118−moveMapKey
119− :: ( DecidablyEmpty p
120−#if !MIN_VERSION_base(4,11,0)
121− , Semigroup p
122−#endif
123− , Patch p
124− )
125− => Ord k => k -> k -> PatchMapWithPatchingMove k p
126−moveMapKey src dst
127− | src == dst = mempty
128− | otherwise =
129− PatchMapWithPatchingMove $ Map.fromList
130− [ (dst, NodeInfo (From_Move src mempty) Nothing)
131− , (src, NodeInfo From_Delete (Just dst))
132− ]
133−
134−-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
135−--
136−-- @
137−-- let aMay = Map.lookup a map
138−-- bMay = Map.lookup b map
139−-- in maybe id (Map.insert a) (bMay <> aMay)
140−-- . maybe id (Map.insert b) (aMay <> bMay)
141−-- . Map.delete a . Map.delete b $ map
142−-- @
143−swapMapKey
144− :: ( DecidablyEmpty p
145−#if !MIN_VERSION_base(4,11,0)
146− , Semigroup p
147−#endif
148− , Patch p
149− )
150− => Ord k => k -> k -> PatchMapWithPatchingMove k p
151−swapMapKey src dst
152− | src == dst = mempty
153− | otherwise =
154− PatchMapWithPatchingMove $ Map.fromList
155− [ (dst, NodeInfo (From_Move src mempty) (Just src))
156− , (src, NodeInfo (From_Move dst mempty) (Just dst))
157− ]
158−
159−-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160−-- the mapping, equivalent to 'Map.delete'.
161−deleteMapKey
162− :: k -> PatchMapWithPatchingMove k v
163−deleteMapKey k = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo From_Delete Nothing
164−
165−-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithPatchingMove' k v@, without checking any invariants.
166−--
167−-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithPatchingMove' are preserved; they will not be checked.
168−unsafePatchMapWithPatchingMove
169− :: Map k (NodeInfo k p) -> PatchMapWithPatchingMove k p
170−unsafePatchMapWithPatchingMove = PatchMapWithPatchingMove
171−
172−-- | Apply the insertions, deletions, and moves to a given 'Map'
173−instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
174− type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
175− -- TODO: return Nothing sometimes
176− -- Note: the strict application here is critical to ensuring that incremental
177− -- merges don't hold onto all their prerequisite events forever; can we make
178− -- this more robust?
179− apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
180− where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
181− From_Insert v -> Just v
182− From_Move k p -> applyAlways p <$> Map.lookup k old
183− From_Delete -> Nothing
184− deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
185− From_Delete -> Just ()
186− _ -> Nothing
187−
188−-- | Returns all the new elements that will be added to the 'Map'
189−patchMapWithPatchingMoveNewElements
190− :: PatchMapWithPatchingMove k p -> [PatchTarget p]
191−patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
192−
193−-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
194−patchMapWithPatchingMoveNewElementsMap
195− :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
196−patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
197− where f ni = case _nodeInfo_from ni of
198− From_Insert v -> Just v
199− From_Move _ _ -> Nothing
200− From_Delete -> Nothing
201−
202−-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
203−-- its values using the given ordering function. The set keys of the 'Map' is
204−-- not changed.
205−patchThatSortsMapWith
206− :: (Ord k, Monoid p)
207− => (PatchTarget p -> PatchTarget p -> Ordering)
208− -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
209−patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
210− where unsorted = Map.toList m
211− sorted = sortBy (cmp `on` snd) unsorted
212− f (to, _) (from, _) = if to == from then Nothing else
213− Just (from, to)
214− reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
215− g (to, _) (from, _) = if to == from then Nothing else
216− let Just movingTo = Map.lookup from reverseMapping
217− in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
218−
219−-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
220−-- will produce a 'Map' with the same values as the second 'Map' but with the
221−-- values sorted with the given ordering function.
222−patchThatChangesAndSortsMapWith
223− :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
224− => (PatchTarget p -> PatchTarget p -> Ordering)
225− -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
226−patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
227− where newList = Map.toList newByIndexUnsorted
228− newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
229−
230−-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
231−-- will produce the second 'Map'.
232−-- Note: this will never produce a patch on a value.
233−patchThatChangesMap
234− :: forall k p
235− . (Ord k, Ord (PatchTarget p), Monoid p)
236− => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
237−patchThatChangesMap oldByIndex newByIndex = patch
238− where invert :: Map k (PatchTarget p) -> Map (PatchTarget p) (Set k)
239− invert = Map.fromListWith (<>) . fmap (\(k, v) -> (v, Set.singleton k)) . Map.toList
240− -- In the places where we use unionDistinct, a non-distinct key indicates a bug in this function
241− unionDistinct :: forall k' v'. Ord k' => Map k' v' -> Map k' v' -> Map k' v'
242− unionDistinct = Map.unionWith (error "patchThatChangesMap: non-distinct keys")
243− unionPairDistinct :: (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k)) -> (Map k (From k v), Map k (To k))
244− unionPairDistinct (oldFroms, oldTos) (newFroms, newTos) = (unionDistinct oldFroms newFroms, unionDistinct oldTos newTos)
245− -- Generate patch info for a single value
246− -- Keys that are found in both the old and new sets will not be patched
247− -- Keys that are found in only the old set will be moved to a new position if any are available; otherwise they will be deleted
248− -- Keys that are found in only the new set will be populated by moving an old key if any are available; otherwise they will be inserted
249− patchSingleValue :: PatchTarget p -> Set k -> Set k -> (Map k (From k p), Map k (To k))
250− patchSingleValue v oldKeys newKeys = foldl' unionPairDistinct mempty $ align (toList $ oldKeys `Set.difference` newKeys) (toList $ newKeys `Set.difference` oldKeys) <&> \case
251− This oldK -> (mempty, Map.singleton oldK Nothing) -- There's nowhere for this value to go, so we know we are deleting it
252− That newK -> (Map.singleton newK $ From_Insert v, mempty) -- There's nowhere fo this value to come from, so we know we are inserting it
253− These oldK newK -> (Map.singleton newK $ From_Move oldK mempty, Map.singleton oldK $ Just newK)
254− -- Run patchSingleValue on a These. Missing old or new sets are considered empty
255− patchSingleValueThese :: PatchTarget p -> These (Set k) (Set k) -> (Map k (From k p), Map k (To k))
256− patchSingleValueThese v = \case
257− This oldKeys -> patchSingleValue v oldKeys mempty
258− That newKeys -> patchSingleValue v mempty newKeys
259− These oldKeys newKeys -> patchSingleValue v oldKeys newKeys
260− -- Generate froms and tos for all values, then merge them together
261− (froms, tos) = foldl' unionPairDistinct mempty $ Map.mapWithKey patchSingleValueThese $ align (invert oldByIndex) (invert newByIndex)
262− patch = unsafePatchMapWithPatchingMove $ align froms tos <&> \case
263− This from -> NodeInfo from Nothing -- Since we don't have a 'to' record for this key, that must mean it isn't being moved anywhere, so it should be deleted.
264− That to -> NodeInfo From_Delete to -- Since we don't have a 'from' record for this key, it must be getting deleted
265− These from to -> NodeInfo from to
266−
267−--
268−-- NodeInfo
269−--
270−
271−-- | Holds the information about each key: where its new value should come from,
272−-- and where its old value should go to
273−data NodeInfo k p = NodeInfo
274− { _nodeInfo_from :: !(From k p)
275− -- ^ Where do we get the new value for this key?
276− , _nodeInfo_to :: !(To k)
277− -- ^ If the old value is being kept (i.e. moved rather than deleted or
278− -- replaced), where is it going?
279− }
280−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
281−deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
282−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
283−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
284−
285−-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
286−-- the type families here, this doesn't it any bi- or tri-traversal class.
287−bitraverseNodeInfo
288− :: Applicative f
289− => (k0 -> f k1)
290− -> (p0 -> f p1)
291− -> (PatchTarget p0 -> f (PatchTarget p1))
292− -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
293−bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
294− <$> bitraverseFrom fk fp fpt from
295− <*> traverse fk to
296−
297−-- | Change the 'From' value of a 'NodeInfo'
298−nodeInfoMapFrom
299− :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
300−nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
301−
302−-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
303−-- 'Applicative', 'Monad', etc.) action to get the new value
304−nodeInfoMapMFrom
305− :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
306−nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
307−
308−-- | Set the 'To' field of a 'NodeInfo'
309−nodeInfoSetTo
310− :: To k -> NodeInfo k v -> NodeInfo k v
311−nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
312−
313−--
314−-- From
315−--
316−
317−-- | Describe how a key's new value should be produced
318−data From k p
319− = From_Insert (PatchTarget p) -- ^ Insert the given value here
320− | From_Delete -- ^ Delete the existing value, if any, from here
321− | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
322−
323−deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
324−deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
325−deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
326−deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
327−
328−-- | Traverse the 'From' over the key, patch, and patch target. Because of
329−-- the type families here, this doesn't it any bi- or tri-traversal class.
330−bitraverseFrom
331− :: Applicative f
332− => (k0 -> f k1)
333− -> (p0 -> f p1)
334− -> (PatchTarget p0 -> f (PatchTarget p1))
335− -> From k0 p0 -> f (From k1 p1)
336−bitraverseFrom fk fp fpt = \case
337− From_Insert pt -> From_Insert <$> fpt pt
338− From_Delete -> pure From_Delete
339− From_Move k p -> From_Move <$> fk k <*> fp p
340−
341−--
342−-- To
343−--
344−
345−-- | Describe where a key's old value will go. If this is 'Just', that means
346−-- the key's old value will be moved to the given other key; if it is 'Nothing',
347−-- that means it will be deleted.
348−type To = Maybe
349−
350−--
351−-- Fixup
352−--
353−
354−-- | Helper data structure used for composing patches using the monoid instance.
355−data Fixup k v
356− = Fixup_Delete
357− | Fixup_Update (These (From k v) (To k))
358−
359−-- | Compose patches having the same effect as applying the patches in turn:
360−-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
361−instance ( Ord k
362−#if !MIN_VERSION_base(4,11,0)
363− , Semigroup p
364−#endif
365− , DecidablyEmpty p
366− , Patch p
367− ) => Semigroup (PatchMapWithPatchingMove k p) where
368− PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
369− where
370− connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
371− h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
372− h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
373− (Just toAfter, From_Move fromBefore p)
374− | fromBefore == toAfter && isEmpty p
375− -> [(toAfter, Fixup_Delete)]
376− | otherwise
377− -> [ (toAfter, Fixup_Update (This editBefore))
378− , (fromBefore, Fixup_Update (That mToAfter))
379− ]
380− (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
381− (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
382− (Nothing, _) -> []
383− mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
384− mergeFixups _ (Fixup_Update a) (Fixup_Update b)
385− | This x <- a, That y <- b
386− = Fixup_Update $ These x y
387− | That y <- a, This x <- b
388− = Fixup_Update $ These x y
389− mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
390− fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
391− combineNodeInfos _ nia nib = NodeInfo
392− { _nodeInfo_from = _nodeInfo_from nia
393− , _nodeInfo_to = _nodeInfo_to nib
394− }
395− applyFixup _ ni = \case
396− Fixup_Delete -> Nothing
397− Fixup_Update u -> Just $ NodeInfo
398− { _nodeInfo_from = case _nodeInfo_from ni of
399− f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
400− Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
401− Just (From_Insert v) -> From_Insert $ applyAlways p' v
402− Just From_Delete -> From_Delete
403− Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
404− _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
405− , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
406− }
407− m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
408− getHere :: These a b -> Maybe a
409− getHere = \case
410− This a -> Just a
411− These a _ -> Just a
412− That _ -> Nothing
413− getThere :: These a b -> Maybe b
414− getThere = \case
415− This _ -> Nothing
416− These _ b -> Just b
417− That b -> Just b
418−
419−--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
420−-- | Compose patches having the same effect as applying the patches in turn:
421−-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
422−instance ( Ord k
423−#if !MIN_VERSION_base(4,11,0)
424− , Semigroup p
425−#endif
426− , DecidablyEmpty p
427− , Patch p
428− ) => Monoid (PatchMapWithPatchingMove k p) where
429− mempty = PatchMapWithPatchingMove mempty
430− mappend = (<>)
431−
432−makeWrapped ''PatchMapWithPatchingMove
src/Data/Semigroup/Additive.hsdeleted−54
@@ -1,54 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE TypeOperators #-}
3−{-# LANGUAGE TypeFamilies #-}
4−-- |
5−-- Module:
6−-- Data.Semigroup.Additive
7−-- Description:
8−-- This module defines a class for commutative semigroups, until it is moved
9−-- to another library.
10−module Data.Semigroup.Additive
11− ( Additive
12− ) where
13−
14−import Data.Functor.Const (Const (..))
15−import Data.Functor.Identity
16−import Data.Proxy
17−#if !MIN_VERSION_base(4,12,0)
18−-- for :*: and :.: semigroup instances
19−import Data.Orphans ()
20−#endif
21−#if !MIN_VERSION_base(4,11,0)
22−import Data.Semigroup (Semigroup (..))
23−#endif
24−import GHC.Generics
25−
26−-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
27−class Semigroup q => Additive q where
28−
29−-- | Trivial additive semigroup.
30−instance Additive ()
31−
32−-- | Product additive semigroup.
33−-- A Pair of additive semigroups gives rise to a additive semigroup
34−instance (Additive a, Additive b) => Additive (a, b)
35−
36−-- See https://gitlab.haskell.org/ghc/ghc/issues/11135#note_111802 for the reason Compose is not also provided.
37−-- Base does not define Monoid (Compose f g a) so this is the best we can
38−-- really do for functor composition.
39−instance Additive (f (g a)) => Additive ((f :.: g) a)
40−
41−-- | Product of additive semigroups, Functor style.
42−instance (Additive (f a), Additive (g a)) => Additive ((f :*: g) a)
43−
44−-- | Trivial additive semigroup, Functor style
45−instance Additive (Proxy x)
46−
47−-- | Const lifts additive semigroups into a functor.
48−instance Additive a => Additive (Const a x)
49−
50−-- | Identity lifts additive semigroups pointwise (at only one point)
51−instance Additive a => Additive (Identity a)
52−
53−-- | Functions lift additive semigroups pointwise.
54−instance Additive b => Additive (a -> b)
src/Data/WeakBag.hsnew file+121
@@ -0,0 +1,121 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ExistentialQuantification #-}
4+#ifdef USE_REFLEX_OPTIMIZER
5+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
6+#endif
7+-- | This module defines the 'WeakBag' type, which represents a mutable
8+-- collection of items that does not cause the items to be retained in memory.
9+-- This is useful for situations where a value needs to be inspected or modified
10+-- if it is still alive, but can be ignored if it is dead.
11+module Data.WeakBag
12+ ( WeakBag
13+ , WeakBagTicket
14+ , empty
15+ , singleton
16+ , insert
17+ , traverse
18+ , remove
19+ -- * Internal functions
20+ -- These will not always be available.
21+ , _weakBag_children --TODO: Don't export this
22+ ) where
23+
24+import Prelude hiding (traverse)
25+
26+import Control.Exception
27+import Control.Monad
28+import Control.Monad.IO.Class
29+import Data.IntMap.Strict (IntMap)
30+import qualified Data.IntMap.Strict as IntMap
31+import Data.IORef
32+import System.Mem.Weak
33+
34+-- | A 'WeakBag' holds a set of values of type @/a/@, but does not retain them -
35+-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
36+-- alive, the 'WeakBag' will continue to refer to them.
37+data WeakBag a = WeakBag
38+ { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
39+ , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ The items referenced by the WeakBag
40+ }
41+
42+-- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned. If
43+-- the caller retains the ticket, the item is guranteed to stay in memory (and
44+-- thus in the 'WeakBag'). The ticket can also be used to remove the item from
45+-- the 'WeakBag' prematurely (i.e. while it is still alive), using 'remove'.
46+data WeakBagTicket = forall a. WeakBagTicket
47+ { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
48+ , _weakBagTicket_item :: {-# NOUNPACK #-} !a
49+ }
50+
51+-- | Insert an item into a 'WeakBag'.
52+{-# INLINE insert #-}
53+insert :: a -- ^ The item
54+ -> WeakBag a -- ^ The 'WeakBag' to insert into
55+ -> IORef (Weak b) -- ^ An arbitrary value to be used in the following
56+ -- callback
57+ -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed
58+ -- (whether automatically by the item being garbage
59+ -- collected or manually via 'remove')
60+ -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item
61+ -- is retained and allows the item to be removed.
62+insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do
63+ a' <- evaluate a
64+ wbRef' <- evaluate wbRef
65+ myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
66+ let cleanup = do
67+ wb <- readIORef wbRef'
68+ mb <- deRefWeak wb
69+ forM_ mb $ \b -> do
70+ csWithoutMe <- atomicModifyIORef children $ \cs ->
71+ let !csWithoutMe = IntMap.delete myId cs
72+ in (csWithoutMe, csWithoutMe)
73+ when (IntMap.null csWithoutMe) $ finalizer b
74+ wa <- mkWeakPtr a' $ Just cleanup
75+ atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
76+ return $ WeakBagTicket
77+ { _weakBagTicket_weakItem = wa
78+ , _weakBagTicket_item = a'
79+ }
80+
81+-- | Create an empty 'WeakBag'.
82+{-# INLINE empty #-}
83+empty :: IO (WeakBag a)
84+empty = {-# SCC "empty" #-} do
85+ nextId <- newIORef 1
86+ children <- newIORef IntMap.empty
87+ let bag = WeakBag
88+ { _weakBag_nextId = nextId
89+ , _weakBag_children = children
90+ }
91+ return bag
92+
93+-- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with
94+-- 'empty', then using 'insert'.
95+{-# INLINE singleton #-}
96+singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
97+singleton a wbRef finalizer = {-# SCC "singleton" #-} do
98+ bag <- empty
99+ ticket <- insert a bag wbRef finalizer
100+ return (bag, ticket)
101+
102+{-# INLINE traverse #-}
103+-- | Visit every node in the given list. If new nodes are appended during the
104+-- traversal, they will not be visited. Every live node that was in the list
105+-- when the traversal began will be visited exactly once; however, no guarantee
106+-- is made about the order of the traversal.
107+traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
108+traverse (WeakBag _ children) f = {-# SCC "traverse" #-} do
109+ cs <- liftIO $ readIORef children
110+ forM_ cs $ \c -> do
111+ ma <- liftIO $ deRefWeak c
112+ mapM_ f ma
113+
114+-- | Remove an item from the 'WeakBag'; does nothing if invoked multiple times
115+-- on the same 'WeakBagTicket'.
116+{-# INLINE remove #-}
117+remove :: WeakBagTicket -> IO ()
118+remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w
119+--TODO: Should 'remove' also drop the reference to the item?
120+
121+--TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hsnew file+35
@@ -0,0 +1,35 @@
1+{-# LANGUAGE CPP #-}
2+-- | This module exports all of the commonly-used functionality of Reflex; if
3+-- you are just getting started with Reflex, this is probably what you want.
4+module Reflex
5+ ( module X
6+ ) where
7+
8+import Reflex.Class as X
9+import Reflex.Adjustable.Class as X
10+import Reflex.BehaviorWriter.Base as X
11+import Reflex.BehaviorWriter.Class as X
12+import Reflex.Collection as X
13+import Reflex.Dynamic as X
14+import Reflex.EventWriter.Base as X
15+import Reflex.EventWriter.Class as X
16+#ifdef USE_TEMPLATE_HASKELL
17+import Reflex.Dynamic.TH as X
18+#endif
19+import Reflex.Dynamic.Uniq as X
20+import Reflex.DynamicWriter.Base as X
21+import Reflex.DynamicWriter.Class as X
22+import Reflex.NotReady.Class as X
23+import Reflex.PerformEvent.Base as X
24+import Reflex.PerformEvent.Class as X
25+import Reflex.PostBuild.Base as X
26+import Reflex.PostBuild.Class as X
27+import Reflex.Profiled as X
28+import Reflex.Query.Base as X
29+import Reflex.Query.Class as X
30+import Reflex.Requester.Base as X
31+import Reflex.Requester.Class as X
32+import Reflex.Spider as X
33+import Reflex.Time as X
34+import Reflex.TriggerEvent.Base as X
35+import Reflex.TriggerEvent.Class as X
src/Reflex/Adjustable/Class.hsnew file+139
@@ -0,0 +1,139 @@
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.hsnew file+202
@@ -0,0 +1,202 @@
1+{-|
2+Module: Reflex.BehaviorWriter.Base
3+Description: Implementation of MonadBehaviorWriter
4+-}
5+{-# LANGUAGE CPP #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GADTs #-}
8+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE RankNTypes #-}
11+{-# LANGUAGE ScopedTypeVariables #-}
12+{-# LANGUAGE TypeFamilies #-}
13+{-# LANGUAGE UndecidableInstances #-}
14+{-# LANGUAGE StandaloneDeriving #-}
15+#ifdef USE_REFLEX_OPTIMIZER
16+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
17+#endif
18+module Reflex.BehaviorWriter.Base
19+ ( BehaviorWriterT (..)
20+ , runBehaviorWriterT
21+ , withBehaviorWriterT
22+ ) where
23+
24+import Control.Monad.Exception
25+import Control.Monad.Identity
26+import Control.Monad.IO.Class
27+import Control.Monad.Reader
28+import Control.Monad.Ref
29+import Control.Monad.State.Strict
30+import Data.Dependent.Map (DMap)
31+import qualified Data.Dependent.Map as DMap
32+import Data.Functor.Misc
33+import Data.IntMap (IntMap)
34+import qualified Data.IntMap as IntMap
35+import Data.Map (Map)
36+import qualified Data.Map as Map
37+import Data.Some (Some)
38+
39+import Reflex.Class
40+import Reflex.Adjustable.Class
41+import Reflex.BehaviorWriter.Class
42+import Reflex.Host.Class
43+import Reflex.PerformEvent.Class
44+import Reflex.PostBuild.Class
45+import Reflex.Query.Class
46+import Reflex.Requester.Class
47+import Reflex.TriggerEvent.Class
48+
49+-- | A basic implementation of 'MonadBehaviorWriter'.
50+newtype BehaviorWriterT t w m a = BehaviorWriterT { unBehaviorWriterT :: StateT [Behavior t w] m a }
51+ deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadAsyncException, MonadException) -- The list is kept in reverse order
52+
53+-- | Run a 'BehaviorWriterT' action. The behavior writer output will be provided
54+-- along with the result of the action.
55+runBehaviorWriterT :: (Monad m, Reflex t, Monoid w) => BehaviorWriterT t w m a -> m (a, Behavior t w)
56+runBehaviorWriterT (BehaviorWriterT a) = do
57+ (result, ws) <- runStateT a []
58+ return (result, mconcat $ reverse ws)
59+
60+-- | Map a function over the output of a 'BehaviorWriterT'.
61+withBehaviorWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m)
62+ => (w -> w')
63+ -> BehaviorWriterT t w m a
64+ -> BehaviorWriterT t w' m a
65+withBehaviorWriterT f dw = do
66+ (r, d) <- lift $ do
67+ (r, d) <- runBehaviorWriterT dw
68+ let d' = fmap f d
69+ return (r, d')
70+ tellBehavior d
71+ return r
72+
73+deriving instance MonadHold t m => MonadHold t (BehaviorWriterT t w m)
74+deriving instance MonadSample t m => MonadSample t (BehaviorWriterT t w m)
75+
76+instance MonadTrans (BehaviorWriterT t w) where
77+ lift = BehaviorWriterT . lift
78+
79+instance MonadRef m => MonadRef (BehaviorWriterT t w m) where
80+ type Ref (BehaviorWriterT t w m) = Ref m
81+ newRef = lift . newRef
82+ readRef = lift . readRef
83+ writeRef r = lift . writeRef r
84+
85+instance MonadAtomicRef m => MonadAtomicRef (BehaviorWriterT t w m) where
86+ atomicModifyRef r = lift . atomicModifyRef r
87+
88+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (BehaviorWriterT t w m) where
89+ newEventWithTrigger = lift . newEventWithTrigger
90+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
91+
92+instance (Monad m, Monoid w, Reflex t) => MonadBehaviorWriter t w (BehaviorWriterT t w m) where
93+ tellBehavior w = BehaviorWriterT $ modify (w :)
94+
95+instance MonadReader r m => MonadReader r (BehaviorWriterT t w m) where
96+ ask = lift ask
97+ local f (BehaviorWriterT a) = BehaviorWriterT $ mapStateT (local f) a
98+ reader = lift . reader
99+
100+instance PerformEvent t m => PerformEvent t (BehaviorWriterT t w m) where
101+ type Performable (BehaviorWriterT t w m) = Performable m
102+ performEvent_ = lift . performEvent_
103+ performEvent = lift . performEvent
104+
105+instance TriggerEvent t m => TriggerEvent t (BehaviorWriterT t w m) where
106+ newTriggerEvent = lift newTriggerEvent
107+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
108+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
109+
110+instance PostBuild t m => PostBuild t (BehaviorWriterT t w m) where
111+ getPostBuild = lift getPostBuild
112+
113+instance MonadState s m => MonadState s (BehaviorWriterT t w m) where
114+ get = lift get
115+ put = lift . put
116+
117+instance Requester t m => Requester t (BehaviorWriterT t w m) where
118+ type Request (BehaviorWriterT t w m) = Request m
119+ type Response (BehaviorWriterT t w m) = Response m
120+ requesting = lift . requesting
121+ requesting_ = lift . requesting_
122+
123+instance (MonadQuery t q m, Monad m) => MonadQuery t q (BehaviorWriterT t w m) where
124+ tellQueryIncremental = lift . tellQueryIncremental
125+ askQueryResult = lift askQueryResult
126+ queryIncremental = lift . queryIncremental
127+
128+instance (Adjustable t m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (BehaviorWriterT t w m) where
129+ runWithReplace a0 a' = do
130+ (result0, result') <- lift $ runWithReplace (runBehaviorWriterT a0) $ runBehaviorWriterT <$> a'
131+ tellBehavior . join =<< hold (snd result0) (snd <$> result')
132+ return (fst result0, fst <$> result')
133+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust
134+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith
135+
136+traverseIntMapWithKeyWithAdjustImpl
137+ :: forall t w v' p p' v m.
138+ ( PatchTarget (p' (Behavior t w)) ~ IntMap (Behavior t w)
139+ , Patch (p' (Behavior t w))
140+ , Monoid w
141+ , Reflex t
142+ , MonadHold t m
143+ , Functor p
144+ , p ~ p'
145+ )
146+ => ( (IntMap.Key -> v -> m (v', Behavior t w))
147+ -> IntMap v
148+ -> Event t (p v)
149+ -> m (IntMap (v', Behavior t w), Event t (p (v', Behavior t w)))
150+ )
151+ -> (IntMap.Key -> v -> BehaviorWriterT t w m v')
152+ -> IntMap v
153+ -> Event t (p v)
154+ -> BehaviorWriterT t w m (IntMap v', Event t (p v'))
155+traverseIntMapWithKeyWithAdjustImpl base f (dm0 :: IntMap v) dm' = do
156+ (result0, result') <- lift $ base (\k v -> runBehaviorWriterT $ f k v) dm0 dm'
157+ let liftedResult0 = fmap fst result0
158+ liftedResult' = fmap (fmap fst) result'
159+ liftedWritten0 :: IntMap (Behavior t w)
160+ liftedWritten0 = fmap snd result0
161+ liftedWritten' = fmap (fmap snd) result'
162+ i <- holdIncremental liftedWritten0 liftedWritten'
163+ tellBehavior $ pull $ do
164+ m <- sample $ currentIncremental i
165+ mconcat . IntMap.elems <$> traverse sample m
166+ return (liftedResult0, liftedResult')
167+
168+newtype BehaviorWriterTLoweredResult t w v a = BehaviorWriterTLoweredResult (v a, Behavior t w)
169+
170+traverseDMapWithKeyWithAdjustImpl
171+ :: forall t w k v' p p' v m.
172+ ( PatchTarget (p' (Some k) (Behavior t w)) ~ Map (Some k) (Behavior t w)
173+ , Patch (p' (Some k) (Behavior t w))
174+ , Monoid w
175+ , Reflex t
176+ , MonadHold t m
177+ )
178+ => ( (forall a. k a -> v a -> m (BehaviorWriterTLoweredResult t w v' a))
179+ -> DMap k v
180+ -> Event t (p k v)
181+ -> m (DMap k (BehaviorWriterTLoweredResult t w v'), Event t (p k (BehaviorWriterTLoweredResult t w v')))
182+ )
183+ -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> v' a) -> p k (BehaviorWriterTLoweredResult t w v') -> p k v')
184+ -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> Behavior t w) -> p k (BehaviorWriterTLoweredResult t w v') -> p' (Some k) (Behavior t w))
185+ -> (forall a. k a -> v a -> BehaviorWriterT t w m (v' a))
186+ -> DMap k v
187+ -> Event t (p k v)
188+ -> BehaviorWriterT t w m (DMap k v', Event t (p k v'))
189+traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith f (dm0 :: DMap k v) dm' = do
190+ (result0, result') <- lift $ base (\k v -> fmap BehaviorWriterTLoweredResult $ runBehaviorWriterT $ f k v) dm0 dm'
191+ let getValue (BehaviorWriterTLoweredResult (v, _)) = v
192+ getWritten (BehaviorWriterTLoweredResult (_, w)) = w
193+ liftedResult0 = DMap.map getValue result0
194+ liftedResult' = ffor result' $ mapPatch getValue
195+ liftedWritten0 :: Map (Some k) (Behavior t w)
196+ liftedWritten0 = weakenDMapWith getWritten result0
197+ liftedWritten' = ffor result' $ weakenPatchWith getWritten
198+ i <- holdIncremental liftedWritten0 liftedWritten'
199+ tellBehavior $ pull $ do
200+ m <- sample $ currentIncremental i
201+ mconcat . Map.elems <$> traverse sample m
202+ return (liftedResult0, liftedResult')
src/Reflex/BehaviorWriter/Class.hsnew file+25
@@ -0,0 +1,25 @@
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.hsnew file+1655
@@ -0,0 +1,1655 @@
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+ , MonadSample (..)
40+ , MonadHold (..)
41+ -- ** 'fan' related types
42+ , EventSelector (..)
43+ , EventSelectorG (..)
44+ , EventSelectorInt (..)
45+ -- * Convenience functions
46+ , constDyn
47+ , pushAlways
48+ -- ** Combining 'Event's
49+ , leftmost
50+ , merge
51+ , mergeIncremental
52+ , mergeIncrementalWithMove
53+ , mergeMap
54+ , mergeIntMap
55+ , mergeMapIncremental
56+ , mergeMapIncrementalWithMove
57+ , mergeIntMapIncremental
58+ , coincidencePatchMap
59+ , coincidencePatchMapWithMove
60+ , coincidencePatchIntMap
61+ , mergeList
62+ , mergeWith
63+ , difference
64+ , alignEventWithMaybe
65+ -- ** Breaking up 'Event's
66+ , splitE
67+ , fan
68+ , fanEither
69+ , fanThese
70+ , fanMap
71+ , dmapToThese
72+ , EitherTag (..)
73+ , eitherToDSum
74+ , dsumToEither
75+ , factorEvent
76+ , filterEventKey
77+ -- ** Collapsing 'Event . Event'
78+ , switchHold
79+ , switchHoldPromptly
80+ , switchHoldPromptOnly
81+ , switchHoldPromptOnlyIncremental
82+ -- ** Using 'Event's to sample 'Behavior's
83+ , tag
84+ , tagMaybe
85+ , attach
86+ , attachWith
87+ , attachWithMaybe
88+ -- ** Blocking an 'Event' based on a 'Behavior'
89+ , gate
90+ -- ** Combining 'Dynamic's
91+ , distributeDMapOverDynPure
92+ , distributeDMapOverDynPureG
93+ , distributeListOverDyn
94+ , distributeListOverDynWith
95+ , zipDyn
96+ , zipDynWith
97+ -- ** Accumulating state
98+ , Accumulator (..)
99+ , accumDyn
100+ , accumMDyn
101+ , accumMaybeDyn
102+ , accumMaybeMDyn
103+ , mapAccumDyn
104+ , mapAccumMDyn
105+ , mapAccumMaybeDyn
106+ , mapAccumMaybeMDyn
107+ , accumB
108+ , accumMB
109+ , accumMaybeB
110+ , accumMaybeMB
111+ , mapAccumB
112+ , mapAccumMB
113+ , mapAccumMaybeB
114+ , mapAccumMaybeMB
115+ , mapAccum_
116+ , mapAccumM_
117+ , mapAccumMaybe_
118+ , mapAccumMaybeM_
119+ , accumIncremental
120+ , accumMIncremental
121+ , accumMaybeIncremental
122+ , accumMaybeMIncremental
123+ , mapAccumIncremental
124+ , mapAccumMIncremental
125+ , mapAccumMaybeIncremental
126+ , mapAccumMaybeMIncremental
127+ , zipListWithEvent
128+ , numberOccurrences
129+ , numberOccurrencesFrom
130+ , numberOccurrencesFrom_
131+ , (<@>)
132+ , (<@)
133+ , tailE
134+ , headTailE
135+ , takeWhileE
136+ , takeWhileJustE
137+ , dropWhileE
138+ , takeDropWhileJustE
139+ , switcher
140+ -- * Debugging functions
141+ , traceEvent
142+ , traceEventWith
143+ -- * Unsafe functions
144+ , unsafeDynamic
145+ , unsafeMapIncremental
146+ -- * 'Filterable' convenience functions
147+ , FunctorMaybe -- fmapMaybe is purposely not exported from deprecated 'FunctorMaybe' and the new alias is exported instead
148+ , mapMaybe -- Re-exported for convenience
149+ , fmapMaybe
150+ , fforMaybe
151+ , ffilter
152+ , filterLeft
153+ , filterRight
154+ -- * Miscellaneous convenience functions
155+ , ffor
156+ , ffor2
157+ , ffor3
158+ -- * Deprecated functions
159+ , switchPromptly
160+ , switchPromptOnly
161+ -- * "Cheap" functions
162+ , fmapMaybeCheap
163+ , mapMaybeCheap
164+ , fmapCheap
165+ , fforCheap
166+ , fforMaybeCheap
167+ , pushAlwaysCheap
168+ , tagCheap
169+ , mergeWithCheap
170+ , mergeWithCheap'
171+ -- * Slow, but general, implementations
172+ , slowHeadE
173+ ) where
174+
175+#if defined(MIN_VERSION_semialign)
176+import Prelude hiding (zip, zipWith)
177+
178+#if MIN_VERSION_these(0,8,0)
179+import Data.These.Combinators (justThese)
180+#endif
181+#endif
182+
183+import Control.Applicative
184+import Control.Monad.Identity
185+import Control.Monad.Reader
186+import Control.Monad.State.Strict
187+import Control.Monad.Trans.Cont (ContT)
188+import Control.Monad.Trans.Except (ExceptT)
189+import Control.Monad.Trans.RWS (RWST)
190+import Control.Monad.Trans.Writer (WriterT)
191+import Data.Align
192+import Data.Bifunctor
193+import Data.Coerce
194+import Data.Default
195+import Data.Dependent.Map (DMap, DSum (..))
196+import qualified Data.Dependent.Map as DMap
197+import Data.Functor.Compose
198+import Data.Functor.Product
199+import Data.GADT.Compare (GEq (..), GCompare (..), (:~:) (..))
200+import Data.FastMutableIntMap (PatchIntMap)
201+import Data.Foldable
202+import Data.Functor.Bind
203+import Data.Functor.Misc
204+import Data.Functor.Plus
205+import Data.IntMap.Strict (IntMap)
206+import qualified Data.IntMap.Strict as IntMap
207+import Data.List.NonEmpty (NonEmpty (..))
208+import Data.Map (Map)
209+import Data.Semigroup (Semigroup, sconcat, stimes, (<>))
210+import Data.Some (Some(Some))
211+import Data.String
212+import Data.These
213+import Data.Type.Coercion
214+import Data.Witherable (Filterable(..))
215+import qualified Data.Witherable as W
216+import Reflex.FunctorMaybe (FunctorMaybe)
217+import qualified Reflex.FunctorMaybe
218+import Reflex.Patch
219+import qualified Reflex.Patch.MapWithMove as PatchMapWithMove
220+
221+import Debug.Trace (trace)
222+
223+-- | The 'Reflex' class contains all the primitive functionality needed for
224+-- Functional Reactive Programming (FRP). The @/t/@ type parameter indicates
225+-- which "timeline" is in use. Timelines are fully-independent FRP contexts,
226+-- and the type of the timeline determines the FRP engine to be used. For most
227+-- purposes, the 'Reflex.Spider' implementation is recommended.
228+class ( MonadHold t (PushM t)
229+ , MonadSample t (PullM t)
230+ , MonadFix (PushM t)
231+ , Functor (Dynamic t)
232+ , Applicative (Dynamic t) -- Necessary for GHC <= 7.8
233+ , Monad (Dynamic t)
234+ ) => Reflex t where
235+ -- | A container for a value that can change over time. 'Behavior's can be
236+ -- sampled at will, but it is not possible to be notified when they change
237+ data Behavior t :: * -> *
238+ -- | A stream of occurrences. During any given frame, an 'Event' is either
239+ -- occurring or not occurring; if it is occurring, it will contain a value of
240+ -- the given type (its "occurrence type")
241+ data Event t :: * -> *
242+ -- | A container for a value that can change over time and allows
243+ -- notifications on changes. Basically a combination of a 'Behavior' and an
244+ -- 'Event', with a rule that the 'Behavior' will change if and only if the
245+ -- 'Event' fires.
246+ data Dynamic t :: * -> *
247+ -- | An 'Incremental' is a more general form of a 'Dynamic'.
248+ -- Instead of always fully replacing the value, only parts of it can be patched.
249+ -- This is only needed for performance critical code via `mergeIncremental` to make small
250+ -- changes to large values.
251+ data Incremental t :: * -> *
252+ -- | A monad for doing complex push-based calculations efficiently
253+ type PushM t :: * -> *
254+ -- | A monad for doing complex pull-based calculations efficiently
255+ type PullM t :: * -> *
256+ -- | An 'Event' with no occurrences
257+ never :: Event t a
258+ -- | Create a 'Behavior' that always has the given value
259+ 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
260+ -- | Create an 'Event' from another 'Event'; the provided function can sample
261+ -- 'Behavior's and hold 'Event's, and use the results to produce a occurring
262+ -- (Just) or non-occurring (Nothing) result
263+ push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
264+ -- | 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.
265+ pushCheap :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
266+ -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be
267+ -- recomputed whenever any of the read 'Behavior's changes
268+ pull :: PullM t a -> Behavior t a
269+ -- | Merge a collection of events; the resulting 'Event' will only occur if at
270+ -- least one input event is occurring, and will contain all of the input keys
271+ -- that are occurring simultaneously
272+
273+ --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
274+ mergeG :: GCompare k => (forall a. q a -> Event t (v a))
275+ -> DMap k q -> Event t (DMap k v)
276+
277+ -- | Efficiently fan-out an event to many destinations. You should save the
278+ -- result in a @let@-binding, and then repeatedly 'selectG' on the result to
279+ -- create child events
280+ fanG :: GCompare k => Event t (DMap k v) -> EventSelectorG t k v
281+
282+ -- | Create an 'Event' that will occur whenever the currently-selected input
283+ -- 'Event' occurs
284+ switch :: Behavior t (Event t a) -> Event t a
285+ -- | Create an 'Event' that will occur whenever the input event is occurring -- and its occurrence value, another 'Event', is also occurring
286+ coincidence :: Event t (Event t a) -> Event t a
287+ -- | Extract the 'Behavior' of a 'Dynamic'.
288+ current :: Dynamic t a -> Behavior t a
289+ -- | Extract the 'Event' of the 'Dynamic'.
290+ updated :: Dynamic t a -> Event t a
291+ -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
292+ -- recent firing of the given 'Event', if any.
293+ unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
294+ -- | Create a new 'Incremental'. The given "PullM"'s value must always change
295+ -- in the same way that the accumulated application of patches would change
296+ -- that value.
297+ unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
298+ -- | Create a merge whose parents can change over time
299+ mergeIncrementalG :: GCompare k
300+ => (forall a. q a -> Event t (v a))
301+ -> Incremental t (PatchDMap k q)
302+ -> Event t (DMap k v)
303+ -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
304+ mergeIncrementalWithMoveG :: GCompare k
305+ => (forall a. q a -> Event t (v a))
306+ -> Incremental t (PatchDMapWithMove k q) -> Event t (DMap k v)
307+ -- | Extract the 'Behavior' component of an 'Incremental'
308+ currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
309+ -- | Extract the 'Event' component of an 'Incremental'
310+ updatedIncremental :: Patch p => Incremental t p -> Event t p
311+ -- | Convert an 'Incremental' to a 'Dynamic'
312+ incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
313+ -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
314+ -- occurrence type
315+ behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
316+ -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
317+ -- occurrence type
318+ eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
319+ -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
320+ -- occurrence type
321+ dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
322+ mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
323+ fanInt :: Event t (IntMap a) -> EventSelectorInt t a
324+
325+-- | Efficiently fan-out an event to many destinations. You should save the
326+-- result in a @let@-binding, and then repeatedly 'select' on the result to
327+-- create child events
328+fan :: forall t k. (Reflex t, GCompare k)
329+ => Event t (DMap k Identity) -> EventSelector t k
330+ --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
331+fan e = EventSelector (fixup (selectG (fanG e) :: k a -> Event t (Identity a)) :: forall a. k a -> Event t a)
332+ where
333+ fixup :: forall a. (k a -> Event t (Identity a)) -> k a -> Event t a
334+ fixup = case eventCoercion Coercion :: Coercion (Event t (Identity a)) (Event t a) of
335+ Coercion -> coerce
336+
337+--TODO: Specialize this so that we can take advantage of knowing that there's no changing going on
338+-- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple
339+-- keys simultaneously.
340+mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
341+mergeInt m = mergeIntIncremental $ unsafeBuildIncremental (return m) never
342+
343+-- | Coerce a 'Behavior' between representationally-equivalent value types
344+coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
345+coerceBehavior = coerceWith $ behaviorCoercion Coercion
346+
347+-- | Coerce an 'Event' between representationally-equivalent occurrence types
348+coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
349+coerceEvent = coerceWith $ eventCoercion Coercion
350+
351+-- | Coerce a 'Dynamic' between representationally-equivalent value types
352+coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
353+coerceDynamic = coerceWith $ dynamicCoercion Coercion
354+
355+-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
356+-- __must__ change when and only when the 'Event' fires, such that the
357+-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
358+-- if this is not the case, the resulting 'Dynamic' will behave
359+-- nondeterministically.
360+unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
361+unsafeDynamic = unsafeBuildDynamic . sample
362+
363+-- | Construct a 'Dynamic' value that never changes
364+constDyn :: Reflex t => a -> Dynamic t a
365+constDyn = pure
366+
367+instance (Reflex t, Default a) => Default (Dynamic t a) where
368+ def = pure def
369+
370+-- | 'MonadSample' designates monads that can read the current value of a
371+-- 'Behavior'. This includes both 'PullM' and 'PushM'.
372+class (Applicative m, Monad m) => MonadSample t m | m -> t where
373+ -- | Get the current value in the 'Behavior'
374+ sample :: Behavior t a -> m a
375+
376+-- | 'MonadHold' designates monads that can create new 'Behavior's based on
377+-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
378+-- is required to create any stateful computations with Reflex.
379+class MonadSample t m => MonadHold t m where
380+ -- | Create a new 'Behavior' whose value will initially be equal to the given
381+ -- value and will be updated whenever the given 'Event' occurs. The update
382+ -- takes effect immediately after the 'Event' occurs; if the occurrence that
383+ -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
384+ -- the 'Behavior', it will see the __old__ value of the 'Behavior', not the new
385+ -- one.
386+ hold :: a -> Event t a -> m (Behavior t a)
387+ default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)
388+ hold v0 = lift . hold v0
389+ -- | Create a 'Dynamic' value using the given initial value that changes every
390+ -- time the 'Event' occurs.
391+ holdDyn :: a -> Event t a -> m (Dynamic t a)
392+ default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)
393+ holdDyn v0 = lift . holdDyn v0
394+ -- | Create an 'Incremental' value using the given initial value that changes
395+ -- every time the 'Event' occurs.
396+ holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
397+ default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)
398+ holdIncremental v0 = lift . holdIncremental v0
399+ buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)
400+ {-
401+ default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)
402+ buildDynamic getV0 = lift . buildDynamic getV0
403+ -}
404+ -- | Create a new 'Event' that only occurs only once, on the first occurrence of
405+ -- the supplied 'Event'.
406+ headE :: Event t a -> m (Event t a)
407+
408+-- | Accumulate an 'Incremental' with the supplied initial value and the firings of the provided 'Event',
409+-- using the combining function to produce a patch.
410+accumIncremental
411+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
412+ => (PatchTarget p -> b -> p)
413+ -> PatchTarget p
414+ -> Event t b
415+ -> m (Incremental t p)
416+accumIncremental f = accumMaybeIncremental $ \v o -> Just $ f v o
417+
418+-- | Similar to 'accumIncremental' but the combining function runs in 'PushM'
419+accumMIncremental
420+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
421+ => (PatchTarget p -> b -> PushM t p)
422+ -> PatchTarget p
423+ -> Event t b
424+ -> m (Incremental t p)
425+accumMIncremental f = accumMaybeMIncremental $ \v o -> Just <$> f v o
426+
427+-- | Similar to 'accumIncremental' but allows filtering of updates (by dropping updates when the
428+-- combining function produces @Nothing@)
429+accumMaybeIncremental
430+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
431+ => (PatchTarget p -> b -> Maybe p)
432+ -> PatchTarget p
433+ -> Event t b
434+ -> m (Incremental t p)
435+accumMaybeIncremental f = accumMaybeMIncremental $ \v o -> return $ f v o
436+
437+-- | Similar to 'accumMaybeMIncremental' but the combining function runs in 'PushM'
438+accumMaybeMIncremental
439+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
440+ => (PatchTarget p -> b -> PushM t (Maybe p))
441+ -> PatchTarget p
442+ -> Event t b
443+ -> m (Incremental t p)
444+accumMaybeMIncremental f z e = do
445+ rec let e' = flip push e $ \o -> do
446+ v <- sample $ currentIncremental d'
447+ f v o
448+ d' <- holdIncremental z e'
449+ return d'
450+
451+-- | Accumulate an 'Incremental' by folding occurrences of an 'Event'
452+-- with a function that both accumulates and produces a value to fire
453+-- as an 'Event'. Returns both the accumulated value and the constructed
454+-- 'Event'.
455+mapAccumIncremental
456+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
457+ => (PatchTarget p -> b -> (p, c))
458+ -> PatchTarget p
459+ -> Event t b
460+ -> m (Incremental t p, Event t c)
461+mapAccumIncremental f = mapAccumMaybeIncremental $ \v o -> bimap Just Just $ f v o
462+
463+-- | Like 'mapAccumIncremental' but the combining function runs in 'PushM'
464+mapAccumMIncremental
465+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
466+ => (PatchTarget p -> b -> PushM t (p, c))
467+ -> PatchTarget p
468+ -> Event t b
469+ -> m (Incremental t p, Event t c)
470+mapAccumMIncremental f = mapAccumMaybeMIncremental $ \v o -> bimap Just Just <$> f v o
471+
472+-- | Accumulate an 'Incremental' by folding occurrences of an 'Event' with
473+-- a function that both optionally accumulates and optionally produces
474+-- a value to fire as a separate output 'Event'.
475+-- Note that because 'Nothing's are discarded in both cases, the output
476+-- 'Event' may fire even though the output 'Incremental' has not changed, and
477+-- the output 'Incremental' may update even when the output 'Event' is not firing.
478+mapAccumMaybeIncremental
479+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
480+ => (PatchTarget p -> b -> (Maybe p, Maybe c))
481+ -> PatchTarget p
482+ -> Event t b
483+ -> m (Incremental t p, Event t c)
484+mapAccumMaybeIncremental f = mapAccumMaybeMIncremental $ \v o -> return $ f v o
485+
486+-- | Like 'mapAccumMaybeIncremental' but the combining function is a 'PushM' action
487+mapAccumMaybeMIncremental
488+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
489+ => (PatchTarget p -> b -> PushM t (Maybe p, Maybe c))
490+ -> PatchTarget p
491+ -> Event t b
492+ -> m (Incremental t p, Event t c)
493+mapAccumMaybeMIncremental f z e = do
494+ rec let e' = flip push e $ \o -> do
495+ v <- sample $ currentIncremental d'
496+ result <- f v o
497+ return $ case result of
498+ (Nothing, Nothing) -> Nothing
499+ _ -> Just result
500+ d' <- holdIncremental z $ mapMaybe fst e'
501+ return (d', mapMaybe snd e')
502+
503+-- | A somewhat slow implementation of 'headE'
504+slowHeadE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
505+slowHeadE e = do
506+ rec be <- hold e $ fmapCheap (const never) e'
507+ let e' = switch be
508+ return e'
509+
510+-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
511+-- key. This is much more efficient than filtering for each key with
512+-- 'mapMaybe'.
513+newtype EventSelector t k = EventSelector
514+ { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
515+ -- determined by the type of the key, so this can be used to fan-out
516+ -- 'Event's whose sub-'Event's have different types.
517+ --
518+ -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
519+ -- (but equivalent to) using 'mapMaybe' to select only the relevant
520+ -- occurrences of an 'Event'.
521+ select :: forall a. k a -> Event t a
522+ }
523+
524+newtype EventSelectorG t k v = EventSelectorG
525+ { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
526+ -- determined by the type of the key, so this can be used to fan-out
527+ -- 'Event's whose sub-'Event's have different types.
528+ --
529+ -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
530+ -- (but equivalent to) using 'mapMaybe' to select only the relevant
531+ -- occurrences of an 'Event'.
532+ selectG :: forall a. k a -> Event t (v a)
533+ }
534+
535+-- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually
536+-- filtering by key.
537+newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }
538+
539+--------------------------------------------------------------------------------
540+-- Instances
541+--------------------------------------------------------------------------------
542+
543+instance MonadSample t m => MonadSample t (ReaderT r m) where
544+ sample = lift . sample
545+
546+instance MonadHold t m => MonadHold t (ReaderT r m) where
547+ hold a0 = lift . hold a0
548+ holdDyn a0 = lift . holdDyn a0
549+ holdIncremental a0 = lift . holdIncremental a0
550+ buildDynamic a0 = lift . buildDynamic a0
551+ headE = lift . headE
552+
553+instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
554+ sample = lift . sample
555+
556+instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
557+ hold a0 = lift . hold a0
558+ holdDyn a0 = lift . holdDyn a0
559+ holdIncremental a0 = lift . holdIncremental a0
560+ buildDynamic a0 = lift . buildDynamic a0
561+ headE = lift . headE
562+
563+instance MonadSample t m => MonadSample t (StateT s m) where
564+ sample = lift . sample
565+
566+instance MonadHold t m => MonadHold t (StateT s m) where
567+ hold a0 = lift . hold a0
568+ holdDyn a0 = lift . holdDyn a0
569+ holdIncremental a0 = lift . holdIncremental a0
570+ buildDynamic a0 = lift . buildDynamic a0
571+ headE = lift . headE
572+
573+instance MonadSample t m => MonadSample t (ExceptT e m) where
574+ sample = lift . sample
575+
576+instance MonadHold t m => MonadHold t (ExceptT e m) where
577+ hold a0 = lift . hold a0
578+ holdDyn a0 = lift . holdDyn a0
579+ holdIncremental a0 = lift . holdIncremental a0
580+ buildDynamic a0 = lift . buildDynamic a0
581+ headE = lift . headE
582+
583+instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
584+ sample = lift . sample
585+
586+instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
587+ hold a0 = lift . hold a0
588+ holdDyn a0 = lift . holdDyn a0
589+ holdIncremental a0 = lift . holdIncremental a0
590+ buildDynamic a0 = lift . buildDynamic a0
591+ headE = lift . headE
592+
593+instance MonadSample t m => MonadSample t (ContT r m) where
594+ sample = lift . sample
595+
596+instance MonadHold t m => MonadHold t (ContT r m) where
597+ hold a0 = lift . hold a0
598+ holdDyn a0 = lift . holdDyn a0
599+ holdIncremental a0 = lift . holdIncremental a0
600+ buildDynamic a0 = lift . buildDynamic a0
601+ headE = lift . headE
602+
603+--------------------------------------------------------------------------------
604+-- Convenience functions
605+--------------------------------------------------------------------------------
606+
607+-- | Create an 'Event' from another 'Event'. The provided function can sample
608+-- 'Behavior's and hold 'Event's.
609+pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
610+pushAlways f = push (fmap Just . f)
611+
612+-- | Flipped version of 'fmap'.
613+ffor :: Functor f => f a -> (a -> b) -> f b
614+ffor = flip fmap
615+
616+-- | Rotated version of 'liftA2'.
617+ffor2 :: Applicative f => f a -> f b -> (a -> b -> c) -> f c
618+ffor2 a b f = liftA2 f a b
619+
620+-- | Rotated version of 'liftA3'.
621+ffor3 :: Applicative f => f a -> f b -> f c -> (a -> b -> c -> d) -> f d
622+ffor3 a b c f = liftA3 f a b c
623+
624+instance Reflex t => Applicative (Behavior t) where
625+ pure = constant
626+ f <*> x = pull $ sample f `ap` sample x
627+ _ *> b = b
628+ a <* _ = a
629+
630+instance Reflex t => Apply (Behavior t) where
631+ (<.>) = (<*>)
632+
633+instance Reflex t => Bind (Behavior t) where
634+ (>>-) = (>>=)
635+
636+instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
637+ (/) = liftA2 (/)
638+ fromRational = pure . fromRational
639+ recip = fmap recip
640+
641+instance Reflex t => Functor (Behavior t) where
642+ fmap f = pull . fmap f . sample
643+
644+instance (Reflex t, IsString a) => IsString (Behavior t a) where
645+ fromString = pure . fromString
646+
647+instance Reflex t => Monad (Behavior t) where
648+ a >>= f = pull $ sample a >>= sample . f
649+ -- 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.
650+ return = constant
651+ fail = error "Monad (Behavior t) does not support fail"
652+
653+instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
654+ mempty = constant mempty
655+ mappend a b = pull $ liftM2 mappend (sample a) (sample b)
656+ mconcat = pull . fmap mconcat . mapM sample
657+
658+instance (Reflex t, Num a) => Num (Behavior t a) where
659+ (+) = liftA2 (+)
660+ (-) = liftA2 (-)
661+ (*) = liftA2 (*)
662+ abs = fmap abs
663+ fromInteger = pure . fromInteger
664+ negate = fmap negate
665+ signum = fmap signum
666+
667+instance (Num a, Reflex t) => Num (Dynamic t a) where
668+ (+) = liftA2 (+)
669+ (*) = liftA2 (*)
670+ abs = fmap abs
671+ signum = fmap signum
672+ fromInteger = pure . fromInteger
673+ negate = fmap negate
674+ (-) = liftA2 (-)
675+
676+instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
677+ a <> b = pull $ liftM2 (<>) (sample a) (sample b)
678+ sconcat = pull . fmap sconcat . mapM sample
679+ stimes n = fmap $ stimes n
680+
681+-- | Alias for 'mapMaybe'
682+fmapMaybe :: Filterable f => (a -> Maybe b) -> f a -> f b
683+fmapMaybe = mapMaybe
684+
685+-- | Flipped version of 'mapMaybe'.
686+fforMaybe :: Filterable f => f a -> (a -> Maybe b) -> f b
687+fforMaybe = flip mapMaybe
688+
689+-- | Filter 'f a' using the provided predicate.
690+ffilter :: Filterable f => (a -> Bool) -> f a -> f a
691+ffilter = W.filter
692+
693+-- | Filter 'Left's from 'f (Either a b)' into 'a'.
694+filterLeft :: Filterable f => f (Either a b) -> f a
695+filterLeft = mapMaybe (either Just (const Nothing))
696+
697+-- | Filter 'Right's from 'f (Either a b)' into 'b'.
698+filterRight :: Filterable f => f (Either a b) -> f b
699+filterRight = mapMaybe (either (const Nothing) Just)
700+
701+-- | Left-biased event union (prefers left event on simultaneous
702+-- occurrence).
703+instance Reflex t => Alt (Event t) where
704+ ev1 <!> ev2 = leftmost [ev1, ev2]
705+
706+-- | 'Event' intersection (convenient interface to 'coincidence').
707+instance Reflex t => Apply (Event t) where
708+ evf <.> evx = coincidence (fmap (<$> evx) evf)
709+
710+-- | 'Event' intersection (convenient interface to 'coincidence').
711+instance Reflex t => Bind (Event t) where
712+ evx >>- f = coincidence (f <$> evx)
713+ join = coincidence
714+
715+instance Reflex t => Functor (Event t) where
716+ {-# INLINE fmap #-}
717+ fmap f = mapMaybe $ Just . f
718+ {-# INLINE (<$) #-}
719+ x <$ e = fmapCheap (const x) e
720+
721+-- TODO Remove this instance
722+instance Reflex t => FunctorMaybe (Event t) where
723+ {-# INLINE fmapMaybe #-}
724+ fmapMaybe = mapMaybe
725+
726+instance Reflex t => Filterable (Event t) where
727+ {-# INLINE mapMaybe #-}
728+ mapMaybe f = push $ return . f
729+
730+-- | Never: @'zero' = 'never'@.
731+instance Reflex t => Plus (Event t) where
732+ zero = never
733+
734+-- | Replace each occurrence value of the 'Event' with the value of the
735+-- 'Behavior' at the time of that occurrence.
736+tag :: Reflex t => Behavior t b -> Event t a -> Event t b
737+tag b = pushAlways $ \_ -> sample b
738+
739+-- | Replace each occurrence value of the 'Event' with the value of the
740+-- 'Behavior' at that time; if it is 'Just', fire with the contained value; if
741+-- it is 'Nothing', drop the occurrence.
742+tagMaybe :: Reflex t => Behavior t (Maybe b) -> Event t a -> Event t b
743+tagMaybe b = push $ \_ -> sample b
744+
745+-- | Create a new 'Event' that combines occurrences of supplied 'Event' with the
746+-- current value of the 'Behavior'.
747+attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
748+attach = attachWith (,)
749+
750+-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
751+-- combining it with the current value of the 'Behavior'.
752+attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
753+attachWith f = attachWithMaybe $ \a b -> Just $ f a b
754+
755+-- | Create a new 'Event' by combining each occurrence with the current value of
756+-- the 'Behavior'. The occurrence is discarded if the combining function returns
757+-- Nothing
758+attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
759+attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
760+
761+-- | Create a new 'Event' that occurs on all but the first occurrence of the
762+-- supplied 'Event'.
763+tailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a)
764+tailE e = snd <$> headTailE e
765+
766+-- | Create a tuple of two 'Event's with the first one occurring only the first
767+-- time the supplied 'Event' occurs and the second occurring on all but the first
768+-- occurrence.
769+headTailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a, Event t a)
770+headTailE e = do
771+ eHead <- headE e
772+ be <- hold never $ fmap (const e) eHead
773+ return (eHead, switch be)
774+
775+-- | Take the streak of occurrences starting at the current time for which the
776+-- event returns 'True'.
777+--
778+-- Starting at the current time, fire all the occurrences of the 'Event' for
779+-- which the given predicate returns 'True'. When first 'False' is returned,
780+-- do not fire, and permanently stop firing, even if 'True' values would have
781+-- been encountered later.
782+takeWhileE
783+ :: forall t m a
784+ . (Reflex t, MonadFix m, MonadHold t m)
785+ => (a -> Bool)
786+ -> Event t a
787+ -> m (Event t a)
788+takeWhileE f = takeWhileJustE $ \v -> guard (f v) $> v
789+
790+-- | Take the streak of occurrences starting at the current time for which the
791+-- event returns 'Just b'.
792+--
793+-- Starting at the current time, fire all the occurrences of the 'Event' for
794+-- which the given predicate returns 'Just b'. When first 'Nothing' is returned,
795+-- do not fire, and permanently stop firing, even if 'Just b' values would have
796+-- been encountered later.
797+takeWhileJustE
798+ :: forall t m a b
799+ . (Reflex t, MonadFix m, MonadHold t m)
800+ => (a -> Maybe b)
801+ -> Event t a
802+ -> m (Event t b)
803+takeWhileJustE f e = do
804+ rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of
805+ Nothing -> Left never
806+ Just b -> Right b
807+ eFirstBad <- headE eBad
808+ e' <- switchHold e eFirstBad
809+ return eTrue
810+
811+-- | Drop the streak of occurrences starting at the current time for which the
812+-- event returns 'True'.
813+--
814+-- Starting at the current time, do not fire all the occurrences of the 'Event'
815+-- for which the given predicate returns 'True'. When 'False' is first
816+-- returned, do fire, and permanently continue firing, even if 'True' values
817+-- would have been encountered later.
818+dropWhileE
819+ :: forall t m a
820+ . (Reflex t, MonadFix m, MonadHold t m)
821+ => (a -> Bool)
822+ -> Event t a
823+ -> m (Event t a)
824+dropWhileE f e = snd <$> takeDropWhileJustE (\v -> guard (f v) $> v) e
825+
826+-- | Both take and drop the streak of occurrences starting at the current time
827+-- for which the event returns 'Just b'.
828+--
829+-- For the left event, starting at the current time, fire all the occurrences
830+-- of the 'Event' for which the given function returns 'Just b'. When
831+-- 'Nothing' is returned, do not fire, and permanently stop firing, even if
832+-- 'Just b' values would have been encountered later.
833+--
834+-- For the right event, do not fire until the first occurrence where the given
835+-- function returns 'Nothing', and fire that one and all subsequent
836+-- occurrences. Even if the function would have again returned 'Just b', keep
837+-- on firing.
838+takeDropWhileJustE
839+ :: forall t m a b
840+ . (Reflex t, MonadFix m, MonadHold t m)
841+ => (a -> Maybe b)
842+ -> Event t a
843+ -> m (Event t b, Event t a)
844+takeDropWhileJustE f e = do
845+ rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of
846+ Nothing -> Left ()
847+ Just b -> Right b
848+ eFirstBad <- headE eBad
849+ e' <- switchHold e (never <$ eFirstBad)
850+ eRest <- switchHoldPromptOnly never (e <$ eFirstBad)
851+ return (eGood, eRest)
852+
853+-- | Split the supplied 'Event' into two individual 'Event's occurring at the
854+-- same time with the respective values from the tuple.
855+splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
856+splitE e = (fmap fst e, fmap snd e)
857+
858+-- | Print the supplied 'String' and the value of the 'Event' on each
859+-- occurrence. This should /only/ be used for debugging.
860+--
861+-- Note: As with Debug.Trace.trace, the message will only be printed if the
862+-- 'Event' is actually used.
863+traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
864+traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
865+
866+-- | Print the output of the supplied function on each occurrence of the
867+-- 'Event'. This should /only/ be used for debugging.
868+--
869+-- Note: As with Debug.Trace.trace, the message will only be printed if the
870+-- 'Event' is actually used.
871+traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
872+traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
873+
874+instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
875+ (<>) = alignWith (mergeThese (<>))
876+ sconcat = fmap sconcat . mergeList . toList
877+ stimes n = fmap $ stimes n
878+
879+instance (Semigroup a, Reflex t) => Monoid (Event t a) where
880+ mempty = never
881+ mappend = (<>)
882+ mconcat = fmap sconcat . mergeList
883+
884+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
885+-- list occurs. If multiple occur at the same time they are folded from the left
886+-- with the given function.
887+{-# INLINE mergeWith #-}
888+mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
889+mergeWith = mergeWith' id
890+
891+{-# INLINE mergeWith' #-}
892+mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
893+mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)
894+ . mergeInt
895+ . IntMap.fromDistinctAscList
896+ $ zip [0 :: Int ..] es
897+
898+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
899+-- list occurs. If multiple occur at the same time the value is the value of the
900+-- leftmost event.
901+{-# INLINE leftmost #-}
902+leftmost :: Reflex t => [Event t a] -> Event t a
903+leftmost = mergeWith const
904+
905+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
906+-- list occurs and has a list of the values of all 'Event's occurring at that
907+-- time.
908+mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
909+mergeList [] = never
910+mergeList es = mergeWithFoldCheap' id es
911+
912+unsafeMapIncremental
913+ :: (Reflex t, Patch p, Patch p')
914+ => (PatchTarget p -> PatchTarget p')
915+ -> (p -> p')
916+ -> Incremental t p
917+ -> Incremental t p'
918+unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
919+
920+-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
921+-- occurs if at least one of them occurs and has a map of values of all 'Event's
922+-- occurring at that time.
923+mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
924+mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
925+
926+-- | Like 'mergeMap' but for 'IntMap'.
927+mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
928+mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap
929+
930+-- | Create a merge whose parents can change over time
931+mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a)
932+mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id)
933+
934+-- | Create a merge whose parents can change over time
935+mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
936+mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)
937+
938+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
939+mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a)
940+mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id)
941+
942+-- | Split the event into separate events for 'Left' and 'Right' values.
943+fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
944+fanEither e =
945+ let justLeft = either Just (const Nothing)
946+ justRight = either (const Nothing) Just
947+ in (mapMaybe justLeft e, mapMaybe justRight e)
948+
949+-- | Split the event into separate events for 'This' and 'That' values,
950+-- allowing them to fire simultaneously when the input value is 'These'.
951+fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
952+fanThese e =
953+ let this (This x) = Just x
954+ this (These x _) = Just x
955+ this _ = Nothing
956+ that (That y) = Just y
957+ that (These _ y) = Just y
958+ that _ = Nothing
959+ in (mapMaybe this e, mapMaybe that e)
960+
961+-- | Split the event into an 'EventSelector' that allows efficient selection of
962+-- the individual 'Event's.
963+fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
964+fanMap = fan . fmap mapToDMap
965+
966+-- | Switches to the new event whenever it receives one. Only the old event is
967+-- considered the moment a new one is switched in; the output event will fire at
968+-- that moment only if the old event does.
969+--
970+-- Because the simultaneous firing case is irrelevant, this function imposes
971+-- laxer "timing requirements" on the overall circuit, avoiding many potential
972+-- cyclic dependency / metastability failures. It's also more performant. Use
973+-- this rather than 'switchHoldPromptly' and 'switchHoldPromptOnly' unless you
974+-- are absolutely sure you need to act on the new event in the coincidental
975+-- case.
976+switchHold :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
977+switchHold ea0 eea = switch <$> hold ea0 eea
978+
979+-- | Switches to the new event whenever it receives one. Whenever a new event is
980+-- provided, if it is firing, its value will be the resulting event's value; if
981+-- it is not firing, but the old one is, the old one's value will be used.
982+--
983+-- 'switchHold', by always forwarding the old event the moment it is switched
984+-- out, avoids many potential cyclic dependency problems / metastability
985+-- problems. It's also more performant. Use it instead unless you are sure you
986+-- cannot.
987+switchHoldPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
988+switchHoldPromptly ea0 eea = do
989+ bea <- hold ea0 eea
990+ let eLag = switch bea
991+ eCoincidences = coincidence eea
992+ return $ leftmost [eCoincidences, eLag]
993+
994+-- | switches to a new event whenever it receives one. At the moment of
995+-- switching, the old event will be ignored if it fires, and the new one will be
996+-- used if it fires; this is the opposite of 'switch', which will use only the
997+-- old value.
998+--
999+-- 'switchHold', by always forwarding the old event the moment it is switched
1000+-- out, avoids many potential cyclic dependency problems / metastability
1001+-- problems. It's also more performant. Use it instead unless you are sure you
1002+-- cannot.
1003+switchHoldPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1004+switchHoldPromptOnly e0 e' = do
1005+ eLag <- switch <$> hold e0 e'
1006+ return $ coincidence $ leftmost [e', eLag <$ eLag]
1007+
1008+-- | When the given outer event fires, condense the inner events into the contained patch. Non-firing inner events will be replaced with deletions.
1009+coincidencePatchMap :: (Reflex t, Ord k) => Event t (PatchMap k (Event t v)) -> Event t (PatchMap k v)
1010+coincidencePatchMap e = fmapCheap PatchMap $ coincidence $ ffor e $ \(PatchMap m) -> mergeMap $ ffor m $ \case
1011+ Nothing -> fmapCheap (const Nothing) e
1012+ Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1013+
1014+-- | See 'coincidencePatchMap'
1015+coincidencePatchIntMap :: Reflex t => Event t (PatchIntMap (Event t v)) -> Event t (PatchIntMap v)
1016+coincidencePatchIntMap e = fmapCheap PatchIntMap $ coincidence $ ffor e $ \(PatchIntMap m) -> mergeIntMap $ ffor m $ \case
1017+ Nothing -> fmapCheap (const Nothing) e
1018+ Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1019+
1020+-- | See 'coincidencePatchMap'
1021+coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v)
1022+coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of
1023+ PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->
1024+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1025+ PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->
1026+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }
1027+ PatchMapWithMove.From_Insert ev -> leftmost
1028+ [ fforCheap ev $ \v ->
1029+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }
1030+ , fforCheap e $ \_ ->
1031+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1032+ ]
1033+
1034+-- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es
1035+-- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that
1036+-- fires with the patched value.
1037+switchHoldPromptOnlyIncremental
1038+ :: forall t m p pt w
1039+ . ( Reflex t
1040+ , MonadHold t m
1041+ , Patch (p (Event t w))
1042+ , PatchTarget (p (Event t w)) ~ pt (Event t w)
1043+ , Patch (p w)
1044+ , PatchTarget (p w) ~ pt w
1045+ , Monoid (pt w)
1046+ )
1047+ => (Incremental t (p (Event t w)) -> Event t (pt w))
1048+ -> (Event t (p (Event t w)) -> Event t (p w))
1049+ -> pt (Event t w)
1050+ -> Event t (p (Event t w))
1051+ -> m (Event t (pt w))
1052+switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch e0 e' = do
1053+ lag <- mergePatchIncremental <$> holdIncremental e0 e'
1054+ pure $ ffor (align lag (coincidencePatch e')) $ \case
1055+ This old -> old
1056+ That new -> new `applyAlways` mempty
1057+ These old new -> new `applyAlways` old
1058+
1059+instance Reflex t => Align (Event t) where
1060+ nil = never
1061+#if MIN_VERSION_these(0, 8, 0)
1062+instance Reflex t => Semialign (Event t) where
1063+#endif
1064+ align = alignEventWithMaybe Just
1065+
1066+#if defined(MIN_VERSION_semialign)
1067+ zip x y = mapMaybe justThese $ align x y
1068+#endif
1069+
1070+
1071+-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
1072+-- the 'Behavior' is true at the time of occurrence.
1073+gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
1074+gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
1075+
1076+-- | Create a new behavior given a starting behavior and switch to the behavior
1077+-- carried by the event when it fires.
1078+switcher :: (Reflex t, MonadHold t m)
1079+ => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
1080+switcher b eb = pull . (sample <=< sample) <$> hold b eb
1081+
1082+instance (Reflex t, IsString a) => IsString (Dynamic t a) where
1083+ fromString = pure . fromString
1084+
1085+-- | Combine two 'Dynamic's. The result will change whenever either (or both)
1086+-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
1087+zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
1088+zipDyn = zipDynWith (,)
1089+
1090+-- | Combine two 'Dynamic's with a combining function. The result will change
1091+-- whenever either (or both) input 'Dynamic' changes.
1092+-- More efficient than 'liftA2'.
1093+zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
1094+zipDynWith f da db =
1095+ let eab = align (updated da) (updated db)
1096+ ec = flip push eab $ \o -> do
1097+ (a, b) <- case o of
1098+ This a -> do
1099+ b <- sample $ current db
1100+ return (a, b)
1101+ That b -> do
1102+ a <- sample $ current da
1103+ return (a, b)
1104+ These a b -> return (a, b)
1105+ return $ Just $ f a b
1106+ in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
1107+
1108+instance (Reflex t, Semigroup a) => Semigroup (Dynamic t a) where
1109+ (<>) = zipDynWith (<>)
1110+ stimes n = fmap $ stimes n
1111+
1112+instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
1113+ mconcat = distributeListOverDynWith mconcat
1114+ mempty = constDyn mempty
1115+ mappend = zipDynWith mappend
1116+
1117+-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1118+-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1119+-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1120+distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
1121+distributeDMapOverDynPure = distributeDMapOverDynPureG coerceDynamic
1122+
1123+-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1124+-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1125+-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1126+distributeDMapOverDynPureG
1127+ :: forall t k q v. (Reflex t, GCompare k)
1128+ => (forall a. q a -> Dynamic t (v a))
1129+ -> DMap k q -> Dynamic t (DMap k v)
1130+distributeDMapOverDynPureG nt dm = case DMap.toList dm of
1131+ [] -> constDyn DMap.empty
1132+ [k :=> v] -> DMap.singleton k <$> nt v
1133+ _ ->
1134+ let getInitial = DMap.traverseWithKey (\_ -> sample . current . nt) dm
1135+ edmPre = mergeG getCompose $ DMap.map (Compose . updated . nt) dm
1136+ result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
1137+ olds <- sample $ current result
1138+ return $ DMap.unionWithKey (\_ _ new -> new) olds news
1139+ in result
1140+
1141+-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
1142+distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
1143+distributeListOverDyn = distributeListOverDynWith id
1144+
1145+-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
1146+distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
1147+distributeListOverDynWith f =
1148+ fmap (f . map fromDSum . DMap.toAscList) .
1149+ distributeDMapOverDynPure .
1150+ DMap.fromDistinctAscList .
1151+ zipWith toDSum [0..]
1152+ where
1153+ toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
1154+ toDSum k v = Const2 k :=> v
1155+ fromDSum :: DSum (Const2 Int a) Identity -> a
1156+ fromDSum (Const2 _ :=> Identity v) = v
1157+
1158+-- | Create a new 'Event' that occurs when the first supplied 'Event' occurs
1159+-- unless the second supplied 'Event' occurs simultaneously.
1160+difference :: Reflex t => Event t a -> Event t b -> Event t a
1161+difference = alignEventWithMaybe $ \case
1162+ This a -> Just a
1163+ _ -> Nothing
1164+
1165+-- | Zips two values by taking the union of their shapes and combining with the provided function.
1166+-- 'Nothing' values are dropped.
1167+alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c
1168+alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $
1169+ merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1170+
1171+-- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that
1172+-- matches the provided key.
1173+filterEventKey
1174+ :: forall t m k v a.
1175+ ( Reflex t
1176+ , MonadFix m
1177+ , MonadHold t m
1178+ , GEq k
1179+ )
1180+ => k a
1181+ -> Event t (DSum k v)
1182+ -> m (Event t (v a))
1183+filterEventKey k kv' = do
1184+ let f :: DSum k v -> Maybe (v a)
1185+ f (newK :=> newV) = case newK `geq` k of
1186+ Just Refl -> Just newV
1187+ Nothing -> Nothing
1188+ takeWhileJustE f kv'
1189+
1190+-- | "Factor" the input 'DSum' 'Event' to produce an 'Event' which
1191+-- fires when the 'DSum' key changes and contains both the value of the
1192+-- 'DSum' at switchover and an 'Event' of values produced by subsequent
1193+-- firings of the input 'Event' that do not change the 'DSum' key.
1194+factorEvent
1195+ :: forall t m k v a.
1196+ ( Reflex t
1197+ , MonadFix m
1198+ , MonadHold t m
1199+ , GEq k
1200+ )
1201+ => k a
1202+ -> Event t (DSum k v)
1203+ -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v))))
1204+factorEvent k0 kv' = do
1205+ key :: Behavior t (Some k) <- hold (Some k0) $ fmapCheap (\(k :=> _) -> Some k) kv'
1206+ let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case
1207+ Some oldKey -> case newKey `geq` oldKey of
1208+ Just Refl -> return Nothing
1209+ Nothing -> do
1210+ newInner <- filterEventKey newKey kv'
1211+ return $ Just $ newKey :=> Pair newVal (Compose newInner)
1212+ eInitial <- filterEventKey k0 kv'
1213+ return (eInitial, update)
1214+
1215+--------------------------------------------------------------------------------
1216+-- Accumulator
1217+--------------------------------------------------------------------------------
1218+
1219+-- | An 'Accumulator' type can be built by accumulating occurrences of an
1220+-- 'Event'.
1221+#if __GLASGOW_HASKELL__ < 802
1222+{-# WARNING accum "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1223+{-# WARNING accumM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1224+{-# WARNING accumMaybe "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1225+{-# WARNING accumMaybeM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1226+#endif
1227+class Reflex t => Accumulator t f | f -> t where
1228+ accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
1229+ accum f = accumMaybe $ \v o -> Just $ f v o
1230+ accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
1231+ accumM f = accumMaybeM $ \v o -> Just <$> f v o
1232+ accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
1233+ accumMaybe f = accumMaybeM $ \v o -> return $ f v o
1234+ accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
1235+ mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
1236+ mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
1237+ mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
1238+ mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
1239+ mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1240+ mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
1241+ mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1242+
1243+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1244+-- with the provided function. See 'foldDyn'.
1245+accumDyn
1246+ :: (Reflex t, MonadHold t m, MonadFix m)
1247+ => (a -> b -> a)
1248+ -> a
1249+ -> Event t b
1250+ -> m (Dynamic t a)
1251+accumDyn f = accumMaybeDyn $ \v o -> Just $ f v o
1252+
1253+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1254+-- with the provided 'PushM' action.
1255+accumMDyn
1256+ :: (Reflex t, MonadHold t m, MonadFix m)
1257+ => (a -> b -> PushM t a)
1258+ -> a
1259+ -> Event t b
1260+ -> m (Dynamic t a)
1261+accumMDyn f = accumMaybeMDyn $ \v o -> Just <$> f v o
1262+
1263+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1264+-- with the provided function, discarding 'Nothing' results.
1265+accumMaybeDyn
1266+ :: (Reflex t, MonadHold t m, MonadFix m)
1267+ => (a -> b -> Maybe a)
1268+ -> a
1269+ -> Event t b
1270+ -> m (Dynamic t a)
1271+accumMaybeDyn f = accumMaybeMDyn $ \v o -> return $ f v o
1272+
1273+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1274+-- with the provided 'PushM' action, discarding 'Nothing' results.
1275+accumMaybeMDyn
1276+ :: (Reflex t, MonadHold t m, MonadFix m)
1277+ => (a -> b -> PushM t (Maybe a))
1278+ -> a
1279+ -> Event t b
1280+ -> m (Dynamic t a)
1281+accumMaybeMDyn f z e = do
1282+ rec let e' = flip push e $ \o -> do
1283+ v <- sample $ current d'
1284+ f v o
1285+ d' <- holdDyn z e'
1286+ return d'
1287+
1288+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1289+-- with a function that both accumulates and produces a value to fire
1290+-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1291+mapAccumDyn
1292+ :: (Reflex t, MonadHold t m, MonadFix m)
1293+ => (a -> b -> (a, c))
1294+ -> a
1295+ -> Event t b
1296+ -> m (Dynamic t a, Event t c)
1297+mapAccumDyn f = mapAccumMaybeDyn $ \v o -> bimap Just Just $ f v o
1298+
1299+-- | Similar to 'mapAccumDyn' except that the combining function is a
1300+-- 'PushM' action.
1301+mapAccumMDyn
1302+ :: (Reflex t, MonadHold t m, MonadFix m)
1303+ => (a -> b -> PushM t (a, c))
1304+ -> a
1305+ -> Event t b
1306+ -> m (Dynamic t a, Event t c)
1307+mapAccumMDyn f = mapAccumMaybeMDyn $ \v o -> bimap Just Just <$> f v o
1308+
1309+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event' with
1310+-- a function that both optionally accumulates and optionally produces
1311+-- a value to fire as a separate output 'Event'.
1312+-- Note that because 'Nothing's are discarded in both cases, the output
1313+-- 'Event' may fire even though the output 'Dynamic' has not changed, and
1314+-- the output 'Dynamic' may update even when the output 'Event' is not firing.
1315+mapAccumMaybeDyn
1316+ :: (Reflex t, MonadHold t m, MonadFix m)
1317+ => (a -> b -> (Maybe a, Maybe c))
1318+ -> a
1319+ -> Event t b
1320+ -> m (Dynamic t a, Event t c)
1321+mapAccumMaybeDyn f = mapAccumMaybeMDyn $ \v o -> return $ f v o
1322+
1323+-- | Like 'mapAccumMaybeDyn' except that the combining function is a
1324+-- 'PushM' action.
1325+mapAccumMaybeMDyn
1326+ :: (Reflex t, MonadHold t m, MonadFix m)
1327+ => (a -> b -> PushM t (Maybe a, Maybe c))
1328+ -> a
1329+ -> Event t b
1330+ -> m (Dynamic t a, Event t c)
1331+mapAccumMaybeMDyn f z e = do
1332+ rec let e' = flip push e $ \o -> do
1333+ v <- sample $ current d'
1334+ result <- f v o
1335+ return $ case result of
1336+ (Nothing, Nothing) -> Nothing
1337+ _ -> Just result
1338+ d' <- holdDyn z $ mapMaybe fst e'
1339+ return (d', mapMaybe snd e')
1340+
1341+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1342+-- with the provided function.
1343+{-# INLINE accumB #-}
1344+accumB
1345+ :: (Reflex t, MonadHold t m, MonadFix m)
1346+ => (a -> b -> a)
1347+ -> a
1348+ -> Event t b
1349+ -> m (Behavior t a)
1350+accumB f = accumMaybeB $ \v o -> Just $ f v o
1351+
1352+-- | Like 'accumB' except that the combining function is a 'PushM' action.
1353+{-# INLINE accumMB #-}
1354+accumMB
1355+ :: (Reflex t, MonadHold t m, MonadFix m)
1356+ => (a -> b -> PushM t a)
1357+ -> a
1358+ -> Event t b
1359+ -> m (Behavior t a)
1360+accumMB f = accumMaybeMB $ \v o -> Just <$> f v o
1361+
1362+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1363+-- with the provided function, discarding 'Nothing' results.
1364+{-# INLINE accumMaybeB #-}
1365+accumMaybeB
1366+ :: (Reflex t, MonadHold t m, MonadFix m)
1367+ => (a -> b -> Maybe a)
1368+ -> a
1369+ -> Event t b
1370+ -> m (Behavior t a)
1371+accumMaybeB f = accumMaybeMB $ \v o -> return $ f v o
1372+
1373+-- | Like 'accumMaybeB' except that the combining function is a 'PushM' action.
1374+{-# INLINE accumMaybeMB #-}
1375+accumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (Behavior t a)
1376+accumMaybeMB f z e = do
1377+ rec let e' = flip push e $ \o -> do
1378+ v <- sample d'
1379+ f v o
1380+ d' <- hold z e'
1381+ return d'
1382+
1383+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1384+-- with a function that both accumulates and produces a value to fire
1385+-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1386+{-# INLINE mapAccumB #-}
1387+mapAccumB
1388+ :: (Reflex t, MonadHold t m, MonadFix m)
1389+ => (a -> b -> (a, c))
1390+ -> a
1391+ -> Event t b
1392+ -> m (Behavior t a, Event t c)
1393+mapAccumB f = mapAccumMaybeB $ \v o -> bimap Just Just $ f v o
1394+
1395+-- | Like 'mapAccumB' except that the combining function is a 'PushM' action.
1396+{-# INLINE mapAccumMB #-}
1397+mapAccumMB
1398+ :: (Reflex t, MonadHold t m, MonadFix m)
1399+ => (a -> b -> PushM t (a, c))
1400+ -> a
1401+ -> Event t b
1402+ -> m (Behavior t a, Event t c)
1403+mapAccumMB f = mapAccumMaybeMB $ \v o -> bimap Just Just <$> f v o
1404+
1405+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event' with
1406+-- a function that both optionally accumulates and optionally produces
1407+-- a value to fire as a separate output 'Event'. 'Nothing's are discarded.
1408+{-# INLINE mapAccumMaybeB #-}
1409+mapAccumMaybeB
1410+ :: (Reflex t, MonadHold t m, MonadFix m)
1411+ => (a -> b -> (Maybe a, Maybe c))
1412+ -> a
1413+ -> Event t b
1414+ -> m (Behavior t a, Event t c)
1415+mapAccumMaybeB f = mapAccumMaybeMB $ \v o -> return $ f v o
1416+
1417+-- | Like 'mapAccumMaybeB' except that the combining function is a 'PushM' action.
1418+{-# INLINE mapAccumMaybeMB #-}
1419+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)
1420+mapAccumMaybeMB f z e = do
1421+ rec let e' = flip push e $ \o -> do
1422+ v <- sample d'
1423+ result <- f v o
1424+ return $ case result of
1425+ (Nothing, Nothing) -> Nothing
1426+ _ -> Just result
1427+ d' <- hold z $ mapMaybe fst e'
1428+ return (d', mapMaybe snd e')
1429+
1430+-- | Accumulate occurrences of an 'Event', producing an output occurrence each
1431+-- time. Discard the underlying 'Accumulator'.
1432+{-# INLINE mapAccum_ #-}
1433+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)
1434+mapAccum_ f z e = do
1435+ (_, result) <- mapAccumB f z e
1436+ return result
1437+
1438+-- | Accumulate occurrences of an 'Event', possibly producing an output
1439+-- occurrence each time. Discard the underlying 'Accumulator'.
1440+{-# INLINE mapAccumMaybe_ #-}
1441+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)
1442+mapAccumMaybe_ f z e = do
1443+ (_, result) <- mapAccumMaybeB f z e
1444+ return result
1445+
1446+-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
1447+-- an output occurrence each time. Discard the underlying 'Accumulator'.
1448+{-# INLINE mapAccumM_ #-}
1449+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)
1450+mapAccumM_ f z e = do
1451+ (_, result) <- mapAccumMB f z e
1452+ return result
1453+
1454+-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
1455+-- producing an output occurrence each time. Discard the underlying
1456+-- 'Accumulator'.
1457+{-# INLINE mapAccumMaybeM_ #-}
1458+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)
1459+mapAccumMaybeM_ f z e = do
1460+ (_, result) <- mapAccumMaybeMB f z e
1461+ return result
1462+
1463+instance Reflex t => Accumulator t (Dynamic t) where
1464+ accumMaybeM = accumMaybeMDyn
1465+ mapAccumMaybeM = mapAccumMaybeMDyn
1466+
1467+instance Reflex t => Accumulator t (Behavior t) where
1468+ accumMaybeM = accumMaybeMB
1469+ mapAccumMaybeM = mapAccumMaybeMB
1470+
1471+instance Reflex t => Accumulator t (Event t) where
1472+ accumMaybeM f z e = updated <$> accumMaybeM f z e
1473+ mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
1474+
1475+-- | Create a new 'Event' by combining each occurrence with the next value of the
1476+-- list using the supplied function. If the list runs out of items, all
1477+-- subsequent 'Event' occurrences will be ignored.
1478+zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
1479+zipListWithEvent f l e = do
1480+ let f' a b = case a of
1481+ h:t -> (Just t, Just $ f h b)
1482+ _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
1483+ mapAccumMaybe_ f' l e
1484+
1485+-- | Assign a number to each occurrence of the given 'Event', starting from 0
1486+{-# INLINE numberOccurrences #-}
1487+numberOccurrences :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Event t (b, a))
1488+numberOccurrences = numberOccurrencesFrom 0
1489+
1490+-- | Assign a number to each occurrence of the given 'Event'
1491+{-# INLINE numberOccurrencesFrom #-}
1492+numberOccurrencesFrom :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t (b, a))
1493+numberOccurrencesFrom = mapAccum_ (\n a -> let !next = n + 1 in (next, (n, a)))
1494+
1495+-- | Assign a number to each occurrence of the given 'Event'; discard the occurrences' values
1496+{-# INLINE numberOccurrencesFrom_ #-}
1497+numberOccurrencesFrom_ :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t b)
1498+numberOccurrencesFrom_ = mapAccum_ (\n _ -> let !next = n + 1 in (next, n))
1499+
1500+-- | This is used to sample the value of a 'Behavior' using an 'Event'.
1501+--
1502+-- The '<@>' operator is intended to be used in conjunction with
1503+-- the 'Applicative' instance for 'Behavior'.
1504+--
1505+-- This is useful when we want to combine the values of one 'Event' and
1506+-- the value of several 'Behavior's at the time the 'Event' is firing.
1507+--
1508+-- If we have:
1509+--
1510+-- > f :: a -> b -> c -> d
1511+-- > b1 :: Behavior t a
1512+-- > b2 :: Behavior t b
1513+-- > e :: Event t c
1514+--
1515+-- then we can do:
1516+--
1517+-- > f <$> b1 <*> b2 <@> e :: Event t d
1518+--
1519+-- in order to apply the function 'f' to the relevant values.
1520+--
1521+-- The alternative would be something like:
1522+--
1523+-- > attachWith (\(x1, x2) y -> f x1 x2 y) ((,) <$> b1 <*> b2) e :: Event t d
1524+--
1525+-- or a variation involing a custom data type to hold the combination of
1526+-- 'Behavior's even when that combination might only ever be used by 'f'.
1527+--
1528+-- A more suggestive example might be:
1529+--
1530+-- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)
1531+--
1532+(<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b
1533+(<@>) b = push $ \x -> do
1534+ f <- sample b
1535+ return . Just . f $ x
1536+infixl 4 <@>
1537+
1538+-- | An version of '<@>' that does not use the value of the 'Event'.
1539+--
1540+-- Alternatively, it is 'tag' in operator form.
1541+--
1542+-- This is useful when we want to combine the values of several
1543+-- 'Behavior's at particular points in time using an 'Applicative'
1544+-- style syntax.
1545+--
1546+-- If we have:
1547+--
1548+-- > g :: a -> b -> d
1549+-- > b1 :: Behavior t a
1550+-- > b2 :: Behavior t b
1551+-- > e :: Event t c
1552+--
1553+-- where 'e' is firing at the points in time of interest.
1554+--
1555+-- Then we can use '<@':
1556+--
1557+-- > g <$> b1 <*> b2 <@ e :: Event t d
1558+--
1559+-- to combine the values of 'b1' and 'b2' at each of those points of time,
1560+-- with the function 'g' being used to combine the values.
1561+--
1562+-- This is the same as '<@>' except that the 'Event' is being used only
1563+-- to act as a trigger.
1564+(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b
1565+(<@) = tag
1566+infixl 4 <@
1567+
1568+------------------
1569+-- Cheap Functions
1570+------------------
1571+
1572+-- | A "cheap" version of 'pushAlways'. See the performance note on 'pushCheap'.
1573+{-# INLINE pushAlwaysCheap #-}
1574+pushAlwaysCheap :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
1575+pushAlwaysCheap f = pushCheap (fmap Just . f)
1576+
1577+-- | A "cheap" version of 'mapMaybe'. See the performance note on 'pushCheap'.
1578+{-# INLINE mapMaybeCheap #-}
1579+mapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1580+mapMaybeCheap f = pushCheap $ return . f
1581+
1582+-- | An alias for 'mapMaybeCheap'
1583+{-# INLINE fmapMaybeCheap #-}
1584+fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1585+fmapMaybeCheap = mapMaybeCheap
1586+
1587+
1588+-- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'.
1589+{-# INLINE fforMaybeCheap #-}
1590+fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b
1591+fforMaybeCheap = flip mapMaybeCheap
1592+
1593+-- | A "cheap" version of 'ffor'. See the performance note on 'pushCheap'.
1594+{-# INLINE fforCheap #-}
1595+fforCheap :: Reflex t => Event t a -> (a -> b) -> Event t b
1596+fforCheap = flip fmapCheap
1597+
1598+-- | A "cheap" version of 'fmap'. See the performance note on 'pushCheap'.
1599+{-# INLINE fmapCheap #-}
1600+fmapCheap :: Reflex t => (a -> b) -> Event t a -> Event t b
1601+fmapCheap f = pushCheap $ return . Just . f
1602+
1603+-- | A "cheap" version of 'tag'. See the performance note on 'pushCheap'.
1604+{-# INLINE tagCheap #-}
1605+tagCheap :: Reflex t => Behavior t b -> Event t a -> Event t b
1606+tagCheap b = pushAlwaysCheap $ \_ -> sample b
1607+
1608+-- | Merge a collection of events; the resulting 'Event' will only occur if at
1609+-- least one input event is occurring, and will contain all of the input keys
1610+-- that are occurring simultaneously
1611+merge :: (Reflex t, GCompare k) => DMap k (Event t) -> Event t (DMap k Identity)
1612+merge = mergeG coerceEvent
1613+{-# INLINE merge #-}
1614+
1615+-- | Create a merge whose parents can change over time
1616+mergeIncremental :: (Reflex t, GCompare k)
1617+ => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
1618+mergeIncremental = mergeIncrementalG coerceEvent
1619+
1620+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
1621+mergeIncrementalWithMove :: (Reflex t, GCompare k)
1622+ => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity)
1623+mergeIncrementalWithMove = mergeIncrementalWithMoveG coerceEvent
1624+
1625+-- | A "cheap" version of 'mergeWithCheap'. See the performance note on 'pushCheap'.
1626+{-# INLINE mergeWithCheap #-}
1627+mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
1628+mergeWithCheap = mergeWithCheap' id
1629+
1630+-- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'.
1631+{-# INLINE mergeWithCheap' #-}
1632+mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
1633+mergeWithCheap' f g = mergeWithFoldCheap' $ foldl1 g . fmap f
1634+
1635+-- | A "cheap" version of 'mergeWithFoldCheap''. See the performance note on 'pushCheap'.
1636+{-# INLINE mergeWithFoldCheap' #-}
1637+mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b
1638+mergeWithFoldCheap' f es =
1639+ fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)
1640+ . mergeInt
1641+ . IntMap.fromDistinctAscList
1642+ $ zip [0 :: Int ..] es
1643+
1644+--------------------------------------------------------------------------------
1645+-- Deprecated functions
1646+--------------------------------------------------------------------------------
1647+
1648+{-# 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'. " #-}
1649+-- | See 'switchHoldPromptly'
1650+switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1651+switchPromptly = switchHoldPromptly
1652+{-# 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'. " #-}
1653+-- | See 'switchHoldPromptOnly'
1654+switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1655+switchPromptOnly = switchHoldPromptOnly
src/Reflex/Collection.hsnew file+222
@@ -0,0 +1,222 @@
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+#if defined(MIN_VERSION_semialign)
31+import Prelude hiding (zip, zipWith)
32+#endif
33+
34+import Control.Monad.Identity
35+import Data.Align
36+import Data.Functor.Misc
37+import Data.Map (Map)
38+import qualified Data.Map as Map
39+import Data.Map.Misc
40+import Data.These
41+
42+import Reflex.Class
43+import Reflex.Adjustable.Class
44+import Reflex.Dynamic
45+import Reflex.PostBuild.Class
46+
47+-- | Create a set of widgets based on the provided 'Map'. When the
48+-- input 'Event' fires, remove widgets for keys with the value 'Nothing'
49+-- and add/replace widgets for keys with 'Just' values.
50+listHoldWithKey
51+ :: forall t m k v a
52+ . (Ord k, Adjustable t m, MonadHold t m)
53+ => Map k v
54+ -> Event t (Map k (Maybe v))
55+ -> (k -> v -> m a)
56+ -> m (Dynamic t (Map k a))
57+listHoldWithKey m0 m' f = do
58+ let dm0 = mapWithFunctorToDMap $ Map.mapWithKey f m0
59+ dm' = fmap
60+ (PatchDMap . mapWithFunctorToDMap . Map.mapWithKey
61+ (\k v -> ComposeMaybe $ fmap (f k) v)
62+ )
63+ m'
64+ (a0, a') <- sequenceDMapWithAdjust dm0 dm'
65+
66+ --TODO: Move the dmapToMap to the righthand side so it doesn't get
67+ --fully redone every time
68+ fmap dmapToMap . incrementalToDynamic <$> holdIncremental a0 a'
69+
70+--TODO: Something better than Dynamic t (Map k v) - we want something
71+--where the Events carry diffs, not the whole value
72+listWithKey
73+ :: forall t k v m a
74+ . (Ord k, Adjustable t m, PostBuild t m, MonadFix m, MonadHold t m)
75+ => Dynamic t (Map k v)
76+ -> (k -> Dynamic t v -> m a)
77+ -> m (Dynamic t (Map k a))
78+listWithKey vals mkChild = do
79+ postBuild <- getPostBuild
80+ let childValChangedSelector = fanMap $ updated vals
81+
82+ -- We keep track of changes to children values in the mkChild
83+ -- function we pass to listHoldWithKey The other changes we need
84+ -- to keep track of are child insertions and
85+ -- deletions. diffOnlyKeyChanges keeps track of insertions and
86+ -- deletions but ignores value changes, since they're already
87+ -- accounted for.
88+ diffOnlyKeyChanges olds news =
89+ flip Map.mapMaybe (align olds news) $ \case
90+ This _ -> Just Nothing
91+ These _ _ -> Nothing
92+ That new -> Just $ Just new
93+ rec sentVals :: Dynamic t (Map k v) <- foldDyn applyMap Map.empty changeVals
94+ let changeVals :: Event t (Map k (Maybe v))
95+ changeVals =
96+ attachWith diffOnlyKeyChanges (current sentVals) $ leftmost
97+ [ updated vals
98+
99+ -- TODO: This should probably be added to the
100+ -- attachWith, not to the updated; if we were using
101+ -- diffMap instead of diffMapNoEq, I think it might not
102+ -- work
103+ , tag (current vals) postBuild
104+ ]
105+ listHoldWithKey Map.empty changeVals $ \k v ->
106+ mkChild k =<< holdDyn v (select childValChangedSelector $ Const2 k)
107+
108+-- | Display the given map of items (in key order) using the builder
109+-- function provided, and update it with the given event. 'Nothing'
110+-- update entries will delete the corresponding children, and 'Just'
111+-- entries will create them if they do not exist or send an update
112+-- event to them if they do.
113+listWithKeyShallowDiff
114+ :: (Ord k, Adjustable t m, MonadFix m, MonadHold t m)
115+ => Map k v
116+ -> Event t (Map k (Maybe v))
117+ -> (k -> v -> Event t v -> m a)
118+ -> m (Dynamic t (Map k a))
119+listWithKeyShallowDiff initialVals valsChanged mkChild = do
120+ let childValChangedSelector = fanMap $ fmap (Map.mapMaybe id) valsChanged
121+ sentVals <- foldDyn applyMap (void initialVals) $ fmap (fmap void) valsChanged
122+ let relevantPatch patch _ = case patch of
123+
124+ -- Even if we let a Nothing through when the element doesn't
125+ -- already exist, this doesn't cause a problem because it is
126+ -- ignored
127+ Nothing -> Just Nothing
128+
129+ -- We don't want to let spurious re-creations of items through
130+ Just _ -> Nothing
131+ listHoldWithKey
132+ initialVals
133+ (attachWith (flip (Map.differenceWith relevantPatch))
134+ (current sentVals)
135+ valsChanged
136+ )
137+ $ \k v -> mkChild k v $ select childValChangedSelector $ Const2 k
138+
139+--TODO: Something better than Dynamic t (Map k v) - we want something
140+--where the Events carry diffs, not the whole value
141+-- | Create a dynamically-changing set of Event-valued widgets. This
142+-- is like 'listWithKey', specialized for widgets returning @/Event t a/@.
143+-- 'listWithKey' would return @/Dynamic t (Map k (Event t a))/@ in
144+-- this scenario, but 'listViewWithKey' flattens this to
145+-- @/Event t (Map k a)/@ via 'switch'.
146+listViewWithKey
147+ :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
148+ => Dynamic t (Map k v)
149+ -> (k -> Dynamic t v -> m (Event t a))
150+ -> m (Event t (Map k a))
151+listViewWithKey vals mkChild =
152+ switch . fmap mergeMap <$> listViewWithKey' vals mkChild
153+
154+listViewWithKey'
155+ :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
156+ => Dynamic t (Map k v)
157+ -> (k -> Dynamic t v -> m a)
158+ -> m (Behavior t (Map k a))
159+listViewWithKey' vals mkChild = current <$> listWithKey vals mkChild
160+
161+-- | Create a dynamically-changing set of widgets, one of which is
162+-- selected at any time.
163+selectViewListWithKey
164+ :: forall t m k v a
165+ . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
166+ => Dynamic t k
167+ -- ^ Current selection key
168+ -> Dynamic t (Map k v)
169+ -- ^ Dynamic key/value map
170+ -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
171+ -- ^ Function to create a widget for a given key from Dynamic value
172+ -- and Dynamic Bool indicating if this widget is currently selected
173+ -> m (Event t (k, a))
174+ -- ^ Event that fires when any child's return Event fires. Contains
175+ -- key of an arbitrary firing widget.
176+selectViewListWithKey selection vals mkChild = do
177+ -- For good performance, this value must be shared across all children
178+ let selectionDemux = demux selection
179+ selectChild <- listWithKey vals $ \k v -> do
180+ let selected = demuxed selectionDemux k
181+ selectSelf <- mkChild k v selected
182+ return $ fmap ((,) k) selectSelf
183+ return $ switchPromptlyDyn $ leftmost . Map.elems <$> selectChild
184+
185+-- | Like 'selectViewListWithKey' but discards the value of the list
186+-- item widget's output 'Event'.
187+selectViewListWithKey_
188+ :: forall t m k v a
189+ . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
190+ => Dynamic t k
191+ -- ^ Current selection key
192+ -> Dynamic t (Map k v)
193+ -- ^ Dynamic key/value map
194+ -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
195+ -- ^ Function to create a widget for a given key from Dynamic value
196+ -- and Dynamic Bool indicating if this widget is currently selected
197+ -> m (Event t k)
198+ -- ^ Event that fires when any child's return Event fires. Contains
199+ -- key of an arbitrary firing widget.
200+selectViewListWithKey_ selection vals mkChild =
201+ fmap fst <$> selectViewListWithKey selection vals mkChild
202+
203+-- | Create a dynamically-changing set of widgets from a Dynamic
204+-- key/value map. Unlike the 'withKey' variants, the child widgets
205+-- are insensitive to which key they're associated with.
206+list
207+ :: (Ord k, Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
208+ => Dynamic t (Map k v)
209+ -> (Dynamic t v -> m a)
210+ -> m (Dynamic t (Map k a))
211+list dm mkChild = listWithKey dm (\_ dv -> mkChild dv)
212+
213+-- | Create a dynamically-changing set of widgets from a Dynamic list.
214+simpleList
215+ :: (Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
216+ => Dynamic t [v]
217+ -> (Dynamic t v -> m a)
218+ -> m (Dynamic t [a])
219+simpleList xs mkChild =
220+ fmap (fmap (map snd . Map.toList)) $ flip list mkChild $ fmap
221+ (Map.fromList . zip [(1 :: Int) ..])
222+ xs
src/Reflex/Dynamic.hsnew file+530
@@ -0,0 +1,530 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE LambdaCase #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE NoMonomorphismRestriction #-}
9+{-# LANGUAGE PolyKinds #-}
10+{-# LANGUAGE RankNTypes #-}
11+{-# LANGUAGE RecursiveDo #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE StandaloneDeriving #-}
14+{-# LANGUAGE TypeFamilies #-}
15+{-# LANGUAGE TypeOperators #-}
16+{-# LANGUAGE UndecidableInstances #-}
17+#ifdef USE_REFLEX_OPTIMIZER
18+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
19+#endif
20+-- |
21+-- Module:
22+-- Reflex.Dynamic
23+-- Description:
24+-- This module contains various functions for working with 'Dynamic' values.
25+-- 'Dynamic' and its primitives have been moved to the 'Reflex' class.
26+module Reflex.Dynamic
27+ ( -- * Basics
28+ Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update
29+ , current
30+ , updated
31+ , holdDyn
32+ , mapDynM
33+ , forDynM
34+ , constDyn
35+ , count
36+ , toggle
37+ , switchDyn
38+ , switchPromptlyDyn
39+ , tagPromptlyDyn
40+ , attachPromptlyDyn
41+ , attachPromptlyDynWith
42+ , attachPromptlyDynWithMaybe
43+ , maybeDyn
44+ , eitherDyn
45+ , factorDyn
46+ , scanDyn
47+ , scanDynMaybe
48+ , holdUniqDyn
49+ , holdUniqDynBy
50+ , improvingMaybe
51+ , foldDyn
52+ , foldDynM
53+ , foldDynMaybe
54+ , foldDynMaybeM
55+ , joinDynThroughMap
56+ , traceDyn
57+ , traceDynWith
58+ , splitDynPure
59+ , distributeMapOverDynPure
60+ , distributeDMapOverDynPure
61+ , distributeListOverDynPure
62+ , Demux
63+ , demux
64+ , demuxed
65+ -- * Miscellaneous
66+ -- Things that probably aren't very useful:
67+ , HList (..)
68+ , FHList (..)
69+ , collectDynPure
70+ , RebuildSortedHList (..)
71+ , IsHList (..)
72+ , AllAreFunctors (..)
73+ , HListPtr (..)
74+ , distributeFHListOverDynPure
75+ -- * Unsafe
76+ , unsafeDynamic
77+ ) where
78+
79+import Data.Functor.Compose
80+import Data.Functor.Misc
81+import Reflex.Class
82+
83+import Control.Monad
84+import Control.Monad.Fix
85+import Control.Monad.Identity
86+import Data.Align
87+import Data.Dependent.Map (DMap)
88+import qualified Data.Dependent.Map as DMap
89+import Data.Dependent.Sum (DSum (..))
90+import Data.GADT.Compare ((:~:) (..), GCompare (..), GEq (..), GOrdering (..))
91+import Data.Map (Map)
92+import Data.Maybe
93+import Data.Monoid ((<>))
94+import Data.These
95+
96+import Debug.Trace
97+
98+-- | Map a sampling function over a 'Dynamic'.
99+mapDynM :: forall t m a b. (Reflex t, MonadHold t m) => (forall m'. MonadSample t m' => a -> m' b) -> Dynamic t a -> m (Dynamic t b)
100+mapDynM f d = buildDynamic (f =<< sample (current d)) $ pushAlways f (updated d)
101+
102+-- | Flipped version of 'mapDynM'
103+forDynM :: forall t m a b. (Reflex t, MonadHold t m) => Dynamic t a -> (forall m'. MonadSample t m' => a -> m' b) -> m (Dynamic t b)
104+forDynM d f = mapDynM f d
105+
106+-- | Create a new 'Dynamic' that only signals changes if the values actually
107+-- changed.
108+holdUniqDyn :: (Reflex t, MonadHold t m, MonadFix m, Eq a) => Dynamic t a -> m (Dynamic t a)
109+holdUniqDyn = holdUniqDynBy (==)
110+
111+-- | Create a new 'Dynamic' that changes only when the underlying 'Dynamic'
112+-- changes and the given function returns 'False' when given both the old and
113+-- the new values.
114+holdUniqDynBy :: (Reflex t, MonadHold t m, MonadFix m) => (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
115+holdUniqDynBy eq = scanDynMaybe id (\new old -> if new `eq` old then Nothing else Just new)
116+
117+-- | @/Dynamic Maybe/@ that can only update from @/Nothing/@ to @/Just/@ or @/Just/@ to @/Just/@ (i.e., cannot revert to @/Nothing/@)
118+improvingMaybe :: (Reflex t, MonadHold t m, MonadFix m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe a))
119+improvingMaybe = scanDynMaybe id (\new _ -> if isJust new then Just new else Nothing)
120+
121+-- | Create a 'Dynamic' that accumulates values from another 'Dynamic'. This
122+-- function does not force its input 'Dynamic' until the output 'Dynamic' is
123+-- forced.
124+scanDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> b) -> Dynamic t a -> m (Dynamic t b)
125+scanDyn z f = scanDynMaybe z (\a b -> Just $ f a b)
126+
127+-- | Like 'scanDyn', but the the accumulator function may decline to update the
128+-- result 'Dynamic''s value.
129+scanDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> Maybe b) -> Dynamic t a -> m (Dynamic t b)
130+scanDynMaybe z f d = do
131+ rec d' <- buildDynamic (z <$> sample (current d)) $ flip push (updated d) $ \a -> do
132+ b <- sample $ current d'
133+ return $ f a b
134+ return d'
135+
136+-- | Create a 'Dynamic' using the initial value and change it each time the
137+-- 'Event' occurs using a folding function on the previous value and the value
138+-- of the 'Event'.
139+foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b)
140+foldDyn = accumDyn . flip
141+
142+-- | Like 'foldDyn', but the combining function is a 'PushM' action, so it
143+-- can 'sample' existing 'Behaviors' and 'hold' new ones.
144+foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b)
145+foldDynM = accumMDyn . flip
146+
147+-- | Create a 'Dynamic' using the provided initial value and change it each time
148+-- the provided 'Event' occurs, using a function to combine the old value with
149+-- the 'Event''s value. If the function returns 'Nothing', the value is not
150+-- changed; this is distinct from returning 'Just' the old value, since the
151+-- 'Dynamic''s 'updated' 'Event' will fire in the 'Just' case, and will not fire
152+-- in the 'Nothing' case.
153+foldDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> Maybe b) -> b -> Event t a -> m (Dynamic t b)
154+foldDynMaybe = accumMaybeDyn . flip
155+
156+-- | Like 'foldDynMaybe', but the combining function is a 'PushM' action, so it
157+-- can 'sample' existing 'Behaviors' and 'hold' new ones.
158+foldDynMaybeM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe b)) -> b -> Event t a -> m (Dynamic t b)
159+foldDynMaybeM = accumMaybeMDyn . flip
160+
161+-- | Create a new 'Dynamic' that counts the occurrences of the 'Event'.
162+count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)
163+count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e
164+
165+-- | Create a new 'Dynamic' using the initial value that flips its
166+-- value every time the 'Event' occurs.
167+toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool)
168+toggle = foldDyn (const not)
169+
170+-- | Switches to the new 'Event' whenever it receives one. Only the old event is
171+-- considered the moment a new one is switched in; the output event will fire at
172+-- that moment if only if the old event does.
173+--
174+-- Prefer this to 'switchPromptlyDyn' where possible. The lack of doing double
175+-- work when the outer and (new) inner fires means this imposes fewer "timing
176+-- requirements" and thus is far more easy to use without introducing fresh
177+-- failure cases. 'switchDyn' is also more performant.
178+switchDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
179+switchDyn d = switch (current d)
180+
181+-- | Switches to the new 'Event' whenever it receives one. Switching occurs
182+-- __before__ the inner 'Event' fires - so if the 'Dynamic' changes and both the
183+-- old and new inner Events fire simultaneously, the output will fire with the
184+-- value of the __new__ 'Event'.
185+--
186+-- Prefer 'switchDyn' to this where possible. The timing requirements that
187+-- switching before imposes are likely to bring down your app unless you are
188+-- very careful. 'switchDyn' is also more performant.
189+switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
190+switchPromptlyDyn de =
191+ let eLag = switch $ current de
192+ eCoincidences = coincidence $ updated de
193+ in leftmost [eCoincidences, eLag]
194+
195+-- | Split a 'Dynamic' pair into a pair of 'Dynamic's
196+splitDynPure :: Reflex t => Dynamic t (a, b) -> (Dynamic t a, Dynamic t b)
197+splitDynPure d = (fmap fst d, fmap snd d)
198+
199+-- | Convert a 'Map' with 'Dynamic' elements into a 'Dynamic' of a 'Map' with
200+-- non-'Dynamic' elements.
201+distributeMapOverDynPure :: (Reflex t, Ord k) => Map k (Dynamic t v) -> Dynamic t (Map k v)
202+distributeMapOverDynPure = fmap dmapToMap . distributeDMapOverDynPure . mapWithFunctorToDMap
203+
204+-- | Convert a list with 'Dynamic' elements into a 'Dynamic' of a list with
205+-- non-'Dynamic' elements, preserving the order of the elements.
206+{-# DEPRECATED distributeListOverDynPure "Use 'distributeListOverDyn' instead" #-}
207+distributeListOverDynPure :: Reflex t => [Dynamic t v] -> Dynamic t [v]
208+distributeListOverDynPure = distributeListOverDyn
209+
210+--TODO: Generalize this to functors other than Maps
211+-- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic'
212+-- with the current values of the 'Dynamic's in a map.
213+joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)
214+joinDynThroughMap = (distributeMapOverDynPure =<<)
215+
216+-- | Print the value of the 'Dynamic' when it is first read and on each
217+-- subsequent change that is observed (as 'traceEvent'), prefixed with the
218+-- provided string. This should /only/ be used for debugging.
219+--
220+-- Note: Just like Debug.Trace.trace, the value will only be shown if something
221+-- else in the system is depending on it.
222+traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a
223+traceDyn s = traceDynWith $ \x -> s <> ": " <> show x
224+
225+-- | Print the result of applying the provided function to the value
226+-- of the 'Dynamic' when it is first read and on each subsequent change
227+-- that is observed (as 'traceEvent'). This should /only/ be used for
228+-- debugging.
229+--
230+-- Note: Just like Debug.Trace.trace, the value will only be shown if something
231+-- else in the system is depending on it.
232+traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a
233+traceDynWith f d =
234+ let e' = traceEventWith f $ updated d
235+ getV0 = do
236+ x <- sample $ current d
237+ trace (f x) $ return x
238+ in unsafeBuildDynamic getV0 e'
239+
240+-- | Replace the value of the 'Event' with the current value of the 'Dynamic'
241+-- each time the 'Event' occurs.
242+--
243+-- Note: @/tagPromptlyDyn d e/@ differs from @/tag (current d) e/@ in the case that @/e/@ is firing
244+-- at the same time that @/d/@ is changing. With @/tagPromptlyDyn d e/@, the __new__ value of @/d/@
245+-- will replace the value of @/e/@, whereas with @/tag (current d) e/@, the __old__ value
246+-- will be used, since the 'Behavior' won't be updated until the end of the frame.
247+-- Additionally, this means that the output 'Event' may not be used to directly change
248+-- the input 'Dynamic', because that would mean its value depends on itself. __When creating__
249+-- __cyclic data flows, generally @/tag (current d) e/@ is preferred.__
250+tagPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
251+tagPromptlyDyn = attachPromptlyDynWith const
252+
253+-- | Attach the current value of the 'Dynamic' to the value of the
254+-- 'Event' each time it occurs.
255+--
256+-- Note: @/attachPromptlyDyn d/@ is not the same as @/attach (current d)/@. See 'tagPromptlyDyn' for details.
257+attachPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
258+attachPromptlyDyn = attachPromptlyDynWith (,)
259+
260+-- | Combine the current value of the 'Dynamic' with the value of the
261+-- 'Event' each time it occurs.
262+--
263+-- Note: @/attachPromptlyDynWith f d/@ is not the same as @/attachWith f (current d)/@. See 'tagPromptlyDyn' for details.
264+attachPromptlyDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
265+attachPromptlyDynWith f = attachPromptlyDynWithMaybe $ \a b -> Just $ f a b
266+
267+-- | Create a new 'Event' by combining the value at each occurrence with the
268+-- current value of the 'Dynamic' value and possibly filtering if the combining
269+-- function returns 'Nothing'.
270+--
271+-- Note: @/attachPromptlyDynWithMaybe f d/@ is not the same as @/attachWithMaybe f (current d)/@. See 'tagPromptlyDyn' for details.
272+attachPromptlyDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
273+attachPromptlyDynWithMaybe f d e =
274+ let e' = attach (current d) e
275+ in fforMaybe (align e' $ updated d) $ \case
276+ This (a, b) -> f a b -- Only the tagging event is firing, so use that
277+ These (_, b) a -> f a b -- Both events are firing, so use the newer value
278+ That _ -> Nothing -- The tagging event isn't firing, so don't fire
279+
280+-- | Factor a @/Dynamic t (Maybe a)/@ into a @/Dynamic t (Maybe (Dynamic t a))/@,
281+-- such that the outer 'Dynamic' is updated only when the "Maybe"'s constructor
282+-- chages from 'Nothing' to 'Just' or vice-versa. Whenever the constructor
283+-- becomes 'Just', an inner 'Dynamic' will be provided, whose value will track
284+-- the 'a' inside the 'Just'; when the constructor becomes 'Nothing', the
285+-- existing inner 'Dynamic' will become constant, and will not change when the
286+-- outer constructor changes back to 'Nothing'.
287+maybeDyn :: forall t a m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe (Dynamic t a)))
288+maybeDyn = fmap (fmap unpack) . eitherDyn . fmap pack
289+ where pack = \case
290+ Nothing -> Left ()
291+ Just a -> Right a
292+ unpack = \case
293+ Left _ -> Nothing
294+ Right a -> Just a
295+
296+-- | Turns a 'Dynamic t (Either a b)' into a 'Dynamic t (Either (Dynamic t a) (Dynamic t b))' such that
297+-- the outer 'Dynamic' is updated only when the 'Either' constructor changes (e.g., from 'Left' to 'Right').
298+eitherDyn :: forall t a b m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Either a b) -> m (Dynamic t (Either (Dynamic t a) (Dynamic t b)))
299+eitherDyn = fmap (fmap unpack) . factorDyn . fmap eitherToDSum
300+ where unpack :: DSum (EitherTag a b) (Compose (Dynamic t) Identity) -> Either (Dynamic t a) (Dynamic t b)
301+ unpack = \case
302+ LeftTag :=> Compose a -> Left $ coerceDynamic a
303+ RightTag :=> Compose b -> Right $ coerceDynamic b
304+
305+-- | Factor a 'Dynamic t DSum' into a 'Dynamic' 'DSum' containing nested 'Dynamic' values.
306+-- The outer 'Dynamic' updates only when the key of the 'DSum' changes, while the update of the inner
307+-- 'Dynamic' represents updates within the current key.
308+factorDyn :: forall t m k v. (Reflex t, MonadHold t m, GEq k)
309+ => Dynamic t (DSum k v) -> m (Dynamic t (DSum k (Compose (Dynamic t) v)))
310+factorDyn d = buildDynamic (sample (current d) >>= holdKey) update where
311+ update :: Event t (DSum k (Compose (Dynamic t) v))
312+ update = flip push (updated d) $ \(newKey :=> newVal) -> do
313+ (oldKey :=> _) <- sample (current d)
314+ case newKey `geq` oldKey of
315+ Just Refl -> return Nothing
316+ Nothing -> Just <$> holdKey (newKey :=> newVal)
317+
318+ holdKey (k :=> v) = do
319+ inner' <- filterEventKey k (updated d)
320+ inner <- holdDyn v inner'
321+ return $ k :=> Compose inner
322+
323+--------------------------------------------------------------------------------
324+-- Demux
325+--------------------------------------------------------------------------------
326+
327+-- | Represents a time changing value together with an 'EventSelector' that can
328+-- efficiently detect when the underlying 'Dynamic' has a particular value.
329+-- This is useful for representing data like the current selection of a long
330+-- list.
331+--
332+-- Semantically,
333+--
334+-- > demuxed (demux d) k === fmap (== k) d
335+--
336+-- However, when getDemuxed is used multiple times, the complexity is only
337+-- /O(log(n))/, rather than /O(n)/ for fmap.
338+data Demux t k = Demux { demuxValue :: Behavior t k
339+ , demuxSelector :: EventSelector t (Const2 k Bool)
340+ }
341+
342+-- | Demultiplex an input value to a 'Demux' with many outputs. At any given
343+-- time, whichever output is indicated by the given 'Dynamic' will be 'True'.
344+demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k
345+demux k = Demux (current k)
346+ (fan $ attachWith (\k0 k1 -> if k0 == k1
347+ then DMap.empty
348+ else DMap.fromList [Const2 k0 :=> Identity False,
349+ Const2 k1 :=> Identity True])
350+ (current k) (updated k))
351+
352+-- | Select a particular output of the 'Demux'; this is equivalent to (but much
353+-- faster than) mapping over the original 'Dynamic' and checking whether it is
354+-- equal to the given key.
355+demuxed :: (Reflex t, Eq k) => Demux t k -> k -> Dynamic t Bool
356+demuxed d k =
357+ let e = select (demuxSelector d) (Const2 k)
358+ in unsafeBuildDynamic (fmap (==k) $ sample $ demuxValue d) e
359+
360+--------------------------------------------------------------------------------
361+-- collectDyn
362+--------------------------------------------------------------------------------
363+
364+--TODO: This whole section is badly in need of cleanup
365+
366+-- | A heterogeneous list whose type and length are fixed statically. This is
367+-- reproduced from the 'HList' package due to integration issues, and because
368+-- very little other functionality from that library is needed.
369+data HList (l::[*]) where
370+ HNil :: HList '[]
371+ HCons :: e -> HList l -> HList (e ': l)
372+
373+infixr 2 `HCons`
374+
375+type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
376+type instance HRevApp '[] l = l
377+type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
378+
379+hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
380+hRevApp HNil l = l
381+hRevApp (HCons x l) l' = hRevApp l (HCons x l')
382+
383+hReverse :: HList l -> HList (HRevApp l '[])
384+hReverse l = hRevApp l HNil
385+
386+hBuild :: (HBuild' '[] r) => r
387+hBuild = hBuild' HNil
388+
389+class HBuild' l r where
390+ hBuild' :: HList l -> r
391+
392+instance (l' ~ HRevApp l '[])
393+ => HBuild' l (HList l') where
394+ hBuild' = hReverse
395+
396+instance HBuild' (a ': l) r
397+ => HBuild' l (a->r) where
398+ hBuild' l x = hBuild' (HCons x l)
399+
400+-- | Like 'HList', but with a functor wrapping each element.
401+data FHList f l where
402+ FHNil :: FHList f '[]
403+ FHCons :: f e -> FHList f l -> FHList f (e ': l)
404+
405+instance GEq (HListPtr l) where
406+ HHeadPtr `geq` HHeadPtr = Just Refl
407+ HHeadPtr `geq` HTailPtr _ = Nothing
408+ HTailPtr _ `geq` HHeadPtr = Nothing
409+ HTailPtr a `geq` HTailPtr b = a `geq` b
410+
411+instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dmapTo*HList will break
412+ HHeadPtr `gcompare` HHeadPtr = GEQ
413+ HHeadPtr `gcompare` HTailPtr _ = GLT
414+ HTailPtr _ `gcompare` HHeadPtr = GGT
415+ HTailPtr a `gcompare` HTailPtr b = a `gcompare` b
416+
417+-- | A typed index into a typed heterogeneous list.
418+data HListPtr l a where
419+ HHeadPtr :: HListPtr (h ': t) h
420+ HTailPtr :: HListPtr t a -> HListPtr (h ': t) a
421+
422+deriving instance Eq (HListPtr l a)
423+deriving instance Ord (HListPtr l a)
424+
425+fhlistToDMap :: forall (f :: * -> *) l. FHList f l -> DMap (HListPtr l) f
426+fhlistToDMap = DMap.fromList . go
427+ where go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]
428+ go = \case
429+ FHNil -> []
430+ FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)
431+
432+-- | This class allows 'HList's and 'FHlist's to be built from regular lists;
433+-- they must be contiguous and sorted.
434+class RebuildSortedHList l where
435+ rebuildSortedFHList :: [DSum (HListPtr l) f] -> FHList f l
436+ rebuildSortedHList :: [DSum (HListPtr l) Identity] -> HList l
437+
438+instance RebuildSortedHList '[] where
439+ rebuildSortedFHList l = case l of
440+ [] -> FHNil
441+ _ : _ -> error "rebuildSortedFHList{'[]}: empty list expected"
442+ rebuildSortedHList l = case l of
443+ [] -> HNil
444+ _ : _ -> error "rebuildSortedHList{'[]}: empty list expected"
445+
446+instance RebuildSortedHList t => RebuildSortedHList (h ': t) where
447+ rebuildSortedFHList l = case l of
448+ ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
449+ _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected"
450+ rebuildSortedHList l = case l of
451+ ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
452+ _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected"
453+
454+dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) Identity -> HList l
455+dmapToHList = rebuildSortedHList . DMap.toList
456+
457+-- | Collect a hetereogeneous list whose elements are all 'Dynamic's into a
458+-- single 'Dynamic' whose value represents the current values of all of the
459+-- input 'Dynamic's.
460+distributeFHListOverDynPure :: (Reflex t, RebuildSortedHList l) => FHList (Dynamic t) l -> Dynamic t (HList l)
461+distributeFHListOverDynPure l = fmap dmapToHList $ distributeDMapOverDynPure $ fhlistToDMap l
462+
463+-- | Indicates that all elements in a type-level list are applications of the
464+-- same functor.
465+class AllAreFunctors (f :: a -> *) (l :: [a]) where
466+ type FunctorList f l :: [*]
467+ toFHList :: HList (FunctorList f l) -> FHList f l
468+ fromFHList :: FHList f l -> HList (FunctorList f l)
469+
470+instance AllAreFunctors f '[] where
471+ type FunctorList f '[] = '[]
472+ toFHList l = case l of
473+ HNil -> FHNil
474+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
475+ _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
476+#endif
477+ fromFHList FHNil = HNil
478+
479+instance AllAreFunctors f t => AllAreFunctors f (h ': t) where
480+ type FunctorList f (h ': t) = f h ': FunctorList f t
481+ toFHList l = case l of
482+ a `HCons` b -> a `FHCons` toFHList b
483+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
484+ _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
485+#endif
486+ fromFHList (a `FHCons` b) = a `HCons` fromFHList b
487+
488+-- | Convert a datastructure whose constituent parts are all 'Dynamic's into a
489+-- single 'Dynamic' whose value represents all the current values of the input's
490+-- constituent 'Dynamic's.
491+collectDynPure :: ( RebuildSortedHList (HListElems b)
492+ , IsHList a, IsHList b
493+ , AllAreFunctors (Dynamic t) (HListElems b)
494+ , Reflex t
495+ , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
496+ ) => a -> Dynamic t b
497+collectDynPure ds = fmap fromHList $ distributeFHListOverDynPure $ toFHList $ toHList ds
498+
499+-- | Poor man's 'Generic's for product types only.
500+class IsHList a where
501+ type HListElems a :: [*]
502+ toHList :: a -> HList (HListElems a)
503+ fromHList :: HList (HListElems a) -> a
504+
505+instance IsHList (a, b) where
506+ type HListElems (a, b) = [a, b]
507+ toHList (a, b) = hBuild a b
508+ fromHList l = case l of
509+ a `HCons` b `HCons` HNil -> (a, b)
510+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
511+ _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
512+#endif
513+
514+instance IsHList (a, b, c, d) where
515+ type HListElems (a, b, c, d) = [a, b, c, d]
516+ toHList (a, b, c, d) = hBuild a b c d
517+ fromHList l = case l of
518+ a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d)
519+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
520+ _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
521+#endif
522+
523+instance IsHList (a, b, c, d, e, f) where
524+ type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]
525+ toHList (a, b, c, d, e, f) = hBuild a b c d e f
526+ fromHList l = case l of
527+ a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f)
528+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
529+ _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
530+#endif
src/Reflex/Dynamic/TH.hsnew file+106
@@ -0,0 +1,106 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE EmptyDataDecls #-}
3+{-# LANGUAGE GADTs #-}
4+{-# LANGUAGE PatternGuards #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+{-# LANGUAGE TemplateHaskell #-}
7+{-# LANGUAGE TypeOperators #-}
8+#ifdef USE_REFLEX_OPTIMIZER
9+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10+#endif
11+-- | Template Haskell helper functions for building complex 'Dynamic' values.
12+module Reflex.Dynamic.TH
13+ ( qDynPure
14+ , unqDyn
15+ , mkDynPure
16+ ) where
17+
18+import Reflex.Dynamic
19+
20+import Control.Monad.State
21+import Data.Data
22+import Data.Generics
23+import Data.Monoid ((<>))
24+import qualified Language.Haskell.Exts as Hs
25+import qualified Language.Haskell.Meta.Syntax.Translate as Hs
26+import Language.Haskell.TH
27+import Language.Haskell.TH.Quote
28+import qualified Language.Haskell.TH.Syntax as TH
29+
30+-- | Quote a 'Dynamic' expression. Within the quoted expression, you can use
31+-- @$(unqDyn [| x |])@ to refer to any expression @x@ of type @Dynamic t a@; the
32+-- unquoted result will be of type @a@
33+qDynPure :: Q Exp -> Q Exp
34+qDynPure qe = do
35+ e <- qe
36+ let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d
37+ f d = case eqT of
38+ Just (Refl :: d :~: Exp)
39+ | AppE (VarE m) eInner <- d
40+ , m == 'unqMarker
41+ -> do n <- lift $ newName "dynamicQuotedExpressionVariable"
42+ modify ((n, eInner):)
43+ return $ VarE n
44+ _ -> gmapM f d
45+ (e', exprsReversed) <- runStateT (gmapM f e) []
46+ let exprs = reverse exprsReversed
47+ arg = foldr (\a b -> ConE 'FHCons `AppE` snd a `AppE` b) (ConE 'FHNil) exprs
48+ param = foldr (\a b -> ConP 'HCons [VarP (fst a), b]) (ConP 'HNil []) exprs
49+ [| $(return $ LamE [param] e') <$> distributeFHListOverDynPure $(return arg) |]
50+
51+-- | Antiquote a 'Dynamic' expression. This can /only/ be used inside of a
52+-- 'qDyn' quotation.
53+unqDyn :: Q Exp -> Q Exp
54+unqDyn e = [| unqMarker $e |]
55+
56+-- | This type represents an occurrence of unqDyn before it has been processed
57+-- by qDyn. If you see it in a type error, it probably means that unqDyn has
58+-- been used outside of a qDyn context.
59+data UnqDyn
60+
61+-- unqMarker must not be exported; it is used only as a way of smuggling data
62+-- from unqDyn to qDyn
63+
64+--TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery
65+unqMarker :: a -> UnqDyn
66+unqMarker = error "An unqDyn expression was used outside of a qDyn expression"
67+
68+-- | Create a 'Dynamic' value using other 'Dynamic's as inputs. The result is
69+-- sometimes more concise and readable than the equivalent 'Applicative'-based
70+-- expression. For example:
71+--
72+-- > [mkDyn| $x + $v * $t + 1/2 * $a * $t ^ 2 |]
73+--
74+-- would have a very cumbersome 'Applicative' encoding.
75+mkDynPure :: QuasiQuoter
76+mkDynPure = QuasiQuoter
77+ { quoteExp = mkDynExp
78+ , quotePat = error "mkDyn: pattern splices are not supported"
79+ , quoteType = error "mkDyn: type splices are not supported"
80+ , quoteDec = error "mkDyn: declaration splices are not supported"
81+ }
82+
83+mkDynExp :: String -> Q Exp
84+mkDynExp s = case Hs.parseExpWithMode Hs.defaultParseMode { Hs.extensions = [ Hs.EnableExtension Hs.TemplateHaskell ] } s of
85+ Hs.ParseFailed (Hs.SrcLoc _ l c) err -> fail $ "mkDyn:" <> show l <> ":" <> show c <> ": " <> err
86+ Hs.ParseOk e -> qDynPure $ return $ everywhere (id `extT` reinstateUnqDyn) $ Hs.toExp $ everywhere (id `extT` antiE) e
87+ where TH.Name (TH.OccName occName) (TH.NameG _ _ (TH.ModName modName)) = 'unqMarker
88+#if MIN_VERSION_haskell_src_exts(1,18,0)
89+ antiE :: Hs.Exp Hs.SrcSpanInfo -> Hs.Exp Hs.SrcSpanInfo
90+ antiE x = case x of
91+ Hs.SpliceExp l se ->
92+ Hs.App l (Hs.Var l $ Hs.Qual l (Hs.ModuleName l modName) (Hs.Ident l occName)) $ case se of
93+ Hs.IdSplice l2 v -> Hs.Var l2 $ Hs.UnQual l2 $ Hs.Ident l2 v
94+ Hs.ParenSplice _ ps -> ps
95+ _ -> x
96+#else
97+ antiE x = case x of
98+ Hs.SpliceExp se ->
99+ Hs.App (Hs.Var $ Hs.Qual (Hs.ModuleName modName) (Hs.Ident occName)) $ case se of
100+ Hs.IdSplice v -> Hs.Var $ Hs.UnQual $ Hs.Ident v
101+ Hs.ParenSplice ps -> ps
102+ _ -> x
103+#endif
104+ reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName')))
105+ | modName == modName' && occName == occName' = 'unqMarker
106+ reinstateUnqDyn x = x
src/Reflex/Dynamic/Uniq.hsnew file+105
@@ -0,0 +1,105 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE MagicHash #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+#ifdef USE_REFLEX_OPTIMIZER
6+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
7+#endif
8+-- | This module provides a variation of 'Dynamic' values that uses cheap
9+-- pointer equality checks to reduce the amount of signal propagation needed.
10+module Reflex.Dynamic.Uniq
11+ ( UniqDynamic
12+ , uniqDynamic
13+ , fromUniqDynamic
14+ , alreadyUniqDynamic
15+ ) where
16+
17+import Control.Applicative (Applicative (..))
18+import GHC.Exts
19+import Reflex.Class
20+
21+-- | A 'Dynamic' whose 'updated' 'Event' will never fire with the same value as
22+-- the 'current' 'Behavior''s contents. In order to maintain this constraint,
23+-- the value inside a 'UniqDynamic' is always evaluated to
24+-- <https://wiki.haskell.org/Weak_head_normal_form weak head normal form>.
25+--
26+-- Internally, 'UniqDynamic' uses pointer equality as a heuristic to avoid
27+-- unnecessary update propagation; this is much more efficient than performing
28+-- full comparisons. However, when the 'UniqDynamic' is converted back into a
29+-- regular 'Dynamic', a full comparison is performed.
30+newtype UniqDynamic t a = UniqDynamic { unUniqDynamic :: Dynamic t a }
31+
32+-- | Construct a 'UniqDynamic' by eliminating redundant updates from a 'Dynamic'.
33+uniqDynamic :: Reflex t => Dynamic t a -> UniqDynamic t a
34+uniqDynamic d = UniqDynamic $ unsafeBuildDynamic (sample $ current d) $ flip pushCheap (updated d) $ \new -> do
35+ old <- sample $ current d --TODO: Is it better to sample ourselves here?
36+ return $ unsafeJustChanged old new
37+
38+-- | Retrieve a normal 'Dynamic' from a 'UniqDynamic'. This will perform a
39+-- final check using the output type's 'Eq' instance to ensure deterministic
40+-- behavior.
41+--
42+-- WARNING: If used with a type whose 'Eq' instance is not law-abiding -
43+-- specifically, if there are cases where @x /= x@, 'fromUniqDynamic' may
44+-- eliminate more 'updated' occurrences than it should. For example, NaN values
45+-- of 'Double' and 'Float' are considered unequal to themselves by the 'Eq'
46+-- instance, but can be equal by pointer equality. This may cause 'UniqDynamic'
47+-- to lose changes from NaN to NaN.
48+fromUniqDynamic :: (Reflex t, Eq a) => UniqDynamic t a -> Dynamic t a
49+fromUniqDynamic (UniqDynamic d) = unsafeDynamic (current d) e'
50+ where
51+ -- Only consider values different if they fail both pointer equality /and/
52+ -- 'Eq' equality. This is to make things a bit more deterministic in the
53+ -- case of unlawful 'Eq' instances. However, it is still possible to
54+ -- achieve nondeterminism by constructing elements that are identical in
55+ -- value, unequal according to 'Eq', and nondeterministically equal or
56+ -- nonequal by pointer quality. I suspect that it is impossible to make the
57+ -- behavior deterministic in this case.
58+ superEq a b = a `unsafePtrEq` b || a == b
59+ e' = attachWithMaybe (\x x' -> if x' `superEq` x then Nothing else Just x') (current d) (updated d)
60+
61+-- | Create a UniqDynamic without uniqing it on creation. This will be slightly
62+-- faster than uniqDynamic when used with a Dynamic whose values are always (or
63+-- nearly always) different from its previous values; if used with a Dynamic
64+-- whose values do not change frequently, it may be much slower than uniqDynamic
65+alreadyUniqDynamic :: Dynamic t a -> UniqDynamic t a
66+alreadyUniqDynamic = UniqDynamic
67+
68+unsafePtrEq :: a -> a -> Bool
69+unsafePtrEq a b = case a `seq` b `seq` reallyUnsafePtrEquality# a b of
70+ 0# -> False
71+ _ -> True
72+
73+unsafeJustChanged :: a -> a -> Maybe a
74+unsafeJustChanged old new =
75+ if old `unsafePtrEq` new
76+ then Nothing
77+ else Just new
78+
79+instance Reflex t => Accumulator t (UniqDynamic t) where
80+ accumMaybeM f z e = do
81+ let f' old change = do
82+ mNew <- f old change
83+ return $ unsafeJustChanged old =<< mNew
84+ d <- accumMaybeMDyn f' z e
85+ return $ UniqDynamic d
86+ mapAccumMaybeM f z e = do
87+ let f' old change = do
88+ (mNew, output) <- f old change
89+ return (unsafeJustChanged old =<< mNew, output)
90+ (d, out) <- mapAccumMaybeMDyn f' z e
91+ return (UniqDynamic d, out)
92+
93+instance Reflex t => Functor (UniqDynamic t) where
94+ fmap f (UniqDynamic d) = uniqDynamic $ fmap f d
95+
96+instance Reflex t => Applicative (UniqDynamic t) where
97+ pure = UniqDynamic . constDyn
98+ UniqDynamic a <*> UniqDynamic b = uniqDynamic $ a <*> b
99+ _ *> b = b
100+ a <* _ = a
101+
102+instance Reflex t => Monad (UniqDynamic t) where
103+ UniqDynamic x >>= f = uniqDynamic $ x >>= unUniqDynamic . f
104+ _ >> b = b
105+ return = pure
src/Reflex/DynamicWriter.hsnew file+7
@@ -0,0 +1,7 @@
1+module Reflex.DynamicWriter
2+ {-# DEPRECATED "Use 'Reflex.DynamicWriter.Class' and 'Reflex.DynamicWrite.Base' instead, or just import 'Reflex'" #-}
3+ ( module X
4+ ) where
5+
6+import Reflex.DynamicWriter.Base as X
7+import Reflex.DynamicWriter.Class as X
src/Reflex/DynamicWriter/Base.hsnew file+237
@@ -0,0 +1,237 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE GADTs #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE RankNTypes #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE TupleSections #-}
10+{-# LANGUAGE TypeFamilies #-}
11+{-# LANGUAGE UndecidableInstances #-}
12+{-# LANGUAGE StandaloneDeriving #-}
13+#ifdef USE_REFLEX_OPTIMIZER
14+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15+#endif
16+module Reflex.DynamicWriter.Base
17+ ( DynamicWriterT (..)
18+ , runDynamicWriterT
19+ , withDynamicWriterT
20+ ) where
21+
22+import Control.Monad.Exception
23+import Control.Monad.Identity
24+import Control.Monad.IO.Class
25+import Control.Monad.Primitive
26+import Control.Monad.Reader
27+import Control.Monad.Ref
28+import Control.Monad.State.Strict
29+import Data.Align
30+import Data.Dependent.Map (DMap)
31+import qualified Data.Dependent.Map as DMap
32+import Data.FastMutableIntMap
33+import Data.Functor.Misc
34+import Data.IntMap (IntMap)
35+import qualified Data.IntMap as IntMap
36+import Data.Map (Map)
37+import qualified Data.Map as Map
38+import Data.Semigroup (Semigroup(..))
39+import Data.Some (Some)
40+import Data.These
41+
42+import Reflex.Adjustable.Class
43+import Reflex.Class
44+import Reflex.DynamicWriter.Class
45+import Reflex.EventWriter.Class (EventWriter, tellEvent)
46+import Reflex.Host.Class
47+import qualified Reflex.Patch.MapWithMove as MapWithMove
48+import Reflex.PerformEvent.Class
49+import Reflex.PostBuild.Class
50+import Reflex.Query.Class
51+import Reflex.Requester.Class
52+import Reflex.TriggerEvent.Class
53+
54+instance MonadTrans (DynamicWriterT t w) where
55+ lift = DynamicWriterT . lift
56+
57+mapIncrementalMapValues :: (Reflex t, Patch (p v), Patch (p v'), PatchTarget (p v) ~ f v, PatchTarget (p v') ~ f v', Functor p, Functor f) => (v -> v') -> Incremental t (p v) -> Incremental t (p v')
58+mapIncrementalMapValues f = unsafeMapIncremental (fmap f) (fmap f)
59+
60+mergeDynIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Dynamic t v)) -> Incremental t (PatchMap k v)
61+mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
62+ where changedValues = fmap (PatchMap . fmap Just) $ mergeMapIncremental $ mapIncrementalMapValues updated a
63+ addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m
64+
65+mergeIntMapDynIncremental :: Reflex t => Incremental t (PatchIntMap (Dynamic t v)) -> Incremental t (PatchIntMap v)
66+mergeIntMapDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
67+ where changedValues = fmap (PatchIntMap . fmap Just) $ mergeIntMapIncremental $ mapIncrementalMapValues updated a
68+ addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchIntMap m) -> PatchIntMap <$> mapM (mapM (sample . current)) m
69+
70+mergeDynIncrementalWithMove :: forall t k v. (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Dynamic t v)) -> Incremental t (PatchMapWithMove k v)
71+mergeDynIncrementalWithMove a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ alignWith f addedAndRemovedValues changedValues
72+ where changedValues = mergeMapIncrementalWithMove $ mapIncrementalMapValues updated a
73+ addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ fmap unsafePatchMapWithMove . mapM (mapM (sample . current)) . unPatchMapWithMove
74+ f :: These (PatchMapWithMove k v) (Map k v) -> PatchMapWithMove k v
75+ f x = unsafePatchMapWithMove $
76+ let (p, changed) = case x of
77+ This p_ -> (unPatchMapWithMove p_, mempty)
78+ That c -> (mempty, c)
79+ These p_ c -> (unPatchMapWithMove p_, c)
80+ (pWithNewVals, noLongerMoved) = flip runState [] $ forM p $ MapWithMove.nodeInfoMapMFrom $ \case
81+ MapWithMove.From_Insert v -> return $ MapWithMove.From_Insert v
82+ MapWithMove.From_Delete -> return MapWithMove.From_Delete
83+ MapWithMove.From_Move k -> case Map.lookup k changed of
84+ Nothing -> return $ MapWithMove.From_Move k
85+ Just v -> do
86+ modify (k:)
87+ return $ MapWithMove.From_Insert v
88+ noLongerMovedMap = Map.fromList $ fmap (, ()) noLongerMoved
89+ in Map.differenceWith (\e _ -> Just $ MapWithMove.nodeInfoSetTo Nothing e) pWithNewVals noLongerMovedMap --TODO: Check if any in the second map are not covered?
90+
91+-- | A basic implementation of 'DynamicWriter'.
92+newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT [Dynamic t w] m a }
93+ deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadAsyncException, MonadException) -- The list is kept in reverse order
94+
95+deriving instance MonadHold t m => MonadHold t (DynamicWriterT t w m)
96+deriving instance MonadSample t m => MonadSample t (DynamicWriterT t w m)
97+
98+
99+instance MonadRef m => MonadRef (DynamicWriterT t w m) where
100+ type Ref (DynamicWriterT t w m) = Ref m
101+ newRef = lift . newRef
102+ readRef = lift . readRef
103+ writeRef r = lift . writeRef r
104+
105+instance MonadAtomicRef m => MonadAtomicRef (DynamicWriterT t w m) where
106+ atomicModifyRef r = lift . atomicModifyRef r
107+
108+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DynamicWriterT t w m) where
109+ newEventWithTrigger = lift . newEventWithTrigger
110+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
111+
112+-- | Run a 'DynamicWriterT' action. The dynamic writer output will be provided
113+-- along with the result of the action.
114+runDynamicWriterT :: (MonadFix m, Reflex t, Monoid w) => DynamicWriterT t w m a -> m (a, Dynamic t w)
115+runDynamicWriterT (DynamicWriterT a) = do
116+ (result, ws) <- runStateT a []
117+ return (result, mconcat $ reverse ws)
118+
119+instance (Monad m, Monoid w, Reflex t) => DynamicWriter t w (DynamicWriterT t w m) where
120+ tellDyn w = DynamicWriterT $ modify (w :)
121+
122+instance MonadReader r m => MonadReader r (DynamicWriterT t w m) where
123+ ask = lift ask
124+ local f (DynamicWriterT a) = DynamicWriterT $ mapStateT (local f) a
125+ reader = lift . reader
126+
127+instance PerformEvent t m => PerformEvent t (DynamicWriterT t w m) where
128+ type Performable (DynamicWriterT t w m) = Performable m
129+ performEvent_ = lift . performEvent_
130+ performEvent = lift . performEvent
131+
132+instance TriggerEvent t m => TriggerEvent t (DynamicWriterT t w m) where
133+ newTriggerEvent = lift newTriggerEvent
134+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
135+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
136+
137+instance PostBuild t m => PostBuild t (DynamicWriterT t w m) where
138+ getPostBuild = lift getPostBuild
139+
140+instance MonadState s m => MonadState s (DynamicWriterT t w m) where
141+ get = lift get
142+ put = lift . put
143+
144+instance PrimMonad m => PrimMonad (DynamicWriterT t w m) where
145+ type PrimState (DynamicWriterT t w m) = PrimState m
146+ primitive = lift . primitive
147+
148+newtype DynamicWriterTLoweredResult t w v a = DynamicWriterTLoweredResult (v a, Dynamic t w)
149+
150+-- | When the execution of a 'DynamicWriterT' action is adjusted using
151+-- 'Adjustable', the 'Dynamic' output of that action will also be updated to
152+-- match.
153+instance (Adjustable t m, MonadFix m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (DynamicWriterT t w m) where
154+ runWithReplace a0 a' = do
155+ (result0, result') <- lift $ runWithReplace (runDynamicWriterT a0) $ runDynamicWriterT <$> a'
156+ tellDyn . join =<< holdDyn (snd result0) (snd <$> result')
157+ return (fst result0, fst <$> result')
158+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust mergeIntMapDynIncremental
159+ traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap weakenPatchDMapWith mergeDynIncremental
160+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeDynIncrementalWithMove
161+
162+traverseDMapWithKeyWithAdjustImpl :: forall t w k v' p p' v m. (PatchTarget (p' (Some k) (Dynamic t w)) ~ Map (Some k) (Dynamic t w), PatchTarget (p' (Some k) w) ~ Map (Some k) w, Patch (p' (Some k) w), Patch (p' (Some k) (Dynamic t w)), MonadFix m, Monoid w, Reflex t, MonadHold t m)
163+ => ( (forall a. k a -> v a -> m (DynamicWriterTLoweredResult t w v' a))
164+ -> DMap k v
165+ -> Event t (p k v)
166+ -> m (DMap k (DynamicWriterTLoweredResult t w v'), Event t (p k (DynamicWriterTLoweredResult t w v')))
167+ )
168+ -> ((forall a. DynamicWriterTLoweredResult t w v' a -> v' a) -> p k (DynamicWriterTLoweredResult t w v') -> p k v')
169+ -> ((forall a. DynamicWriterTLoweredResult t w v' a -> Dynamic t w) -> p k (DynamicWriterTLoweredResult t w v') -> p' (Some k) (Dynamic t w))
170+ -> (Incremental t (p' (Some k) (Dynamic t w)) -> Incremental t (p' (Some k) w))
171+ -> (forall a. k a -> v a -> DynamicWriterT t w m (v' a))
172+ -> DMap k v
173+ -> Event t (p k v)
174+ -> DynamicWriterT t w m (DMap k v', Event t (p k v'))
175+traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith mergeMyDynIncremental f (dm0 :: DMap k v) dm' = do
176+ (result0, result') <- lift $ base (\k v -> fmap DynamicWriterTLoweredResult $ runDynamicWriterT $ f k v) dm0 dm'
177+ let getValue (DynamicWriterTLoweredResult (v, _)) = v
178+ getWritten (DynamicWriterTLoweredResult (_, w)) = w
179+ liftedResult0 = DMap.map getValue result0
180+ liftedResult' = ffor result' $ mapPatch getValue
181+ liftedWritten0 :: Map (Some k) (Dynamic t w)
182+ liftedWritten0 = weakenDMapWith getWritten result0
183+ liftedWritten' = ffor result' $ weakenPatchWith getWritten
184+ --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
185+ i <- holdIncremental liftedWritten0 liftedWritten'
186+ tellDyn $ fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
187+ return (liftedResult0, liftedResult')
188+
189+traverseIntMapWithKeyWithAdjustImpl :: forall t w v' p p' v m. (PatchTarget (p' (Dynamic t w)) ~ IntMap (Dynamic t w), PatchTarget (p' w) ~ IntMap w, Patch (p' w), Patch (p' (Dynamic t w)), MonadFix m, Monoid w, Reflex t, MonadHold t m, Functor p, p ~ p')
190+ => ( (IntMap.Key -> v -> m (v', Dynamic t w))
191+ -> IntMap v
192+ -> Event t (p v)
193+ -> m (IntMap (v', Dynamic t w), Event t (p (v', Dynamic t w)))
194+ )
195+ -> (Incremental t (p' (Dynamic t w)) -> Incremental t (p' w))
196+ -> (IntMap.Key -> v -> DynamicWriterT t w m v')
197+ -> IntMap v
198+ -> Event t (p v)
199+ -> DynamicWriterT t w m (IntMap v', Event t (p v'))
200+traverseIntMapWithKeyWithAdjustImpl base mergeMyDynIncremental f (dm0 :: IntMap v) dm' = do
201+ (result0, result') <- lift $ base (\k v -> runDynamicWriterT $ f k v) dm0 dm'
202+ let liftedResult0 = fmap fst result0
203+ liftedResult' = fmap (fmap fst) result'
204+ liftedWritten0 :: IntMap (Dynamic t w)
205+ liftedWritten0 = fmap snd result0
206+ liftedWritten' = fmap (fmap snd) result'
207+ --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
208+ i <- holdIncremental liftedWritten0 liftedWritten'
209+ tellDyn $ fmap (mconcat . IntMap.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
210+ return (liftedResult0, liftedResult')
211+
212+-- | Map a function over the output of a 'DynamicWriterT'.
213+withDynamicWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m, MonadFix m)
214+ => (w -> w')
215+ -> DynamicWriterT t w m a
216+ -> DynamicWriterT t w' m a
217+withDynamicWriterT f dw = do
218+ (r, d) <- lift $ do
219+ (r, d) <- runDynamicWriterT dw
220+ let d' = fmap f d
221+ return (r, d')
222+ tellDyn d
223+ return r
224+
225+instance Requester t m => Requester t (DynamicWriterT t w m) where
226+ type Request (DynamicWriterT t w m) = Request m
227+ type Response (DynamicWriterT t w m) = Response m
228+ requesting = lift . requesting
229+ requesting_ = lift . requesting_
230+
231+instance (MonadQuery t q m, Monad m) => MonadQuery t q (DynamicWriterT t w m) where
232+ tellQueryIncremental = lift . tellQueryIncremental
233+ askQueryResult = lift askQueryResult
234+ queryIncremental = lift . queryIncremental
235+
236+instance EventWriter t w m => EventWriter t w (DynamicWriterT t v m) where
237+ tellEvent = lift . tellEvent
src/Reflex/DynamicWriter/Class.hsnew file+30
@@ -0,0 +1,30 @@
1+-- | This module defines the 'DynamicWriter' class.
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE FunctionalDependencies #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE UndecidableInstances #-}
8+#ifdef USE_REFLEX_OPTIMIZER
9+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
10+#endif
11+module Reflex.DynamicWriter.Class
12+ ( MonadDynamicWriter
13+ , DynamicWriter(..)
14+ ) where
15+
16+import Control.Monad.Reader (ReaderT, lift)
17+import Reflex.Class (Dynamic)
18+
19+{-# DEPRECATED MonadDynamicWriter "Use 'DynamicWriter' instead" #-}
20+-- | Type synonym for 'DynamicWriter'
21+type MonadDynamicWriter = DynamicWriter
22+
23+-- | 'MonadDynamicWriter' efficiently collects 'Dynamic' values using 'tellDyn'
24+-- and combines them monoidally to provide a 'Dynamic' result.
25+class (Monad m, Monoid w) => DynamicWriter t w m | m -> t w where
26+ tellDyn :: Dynamic t w -> m ()
27+
28+instance DynamicWriter t w m => DynamicWriter t w (ReaderT r m) where
29+ tellDyn = lift . tellDyn
30+
src/Reflex/EventWriter.hsnew file+7
@@ -0,0 +1,7 @@
1+module Reflex.EventWriter
2+ {-# DEPRECATED "Use 'Reflex.EventWriter.Class' and 'Reflex.EventWriter.Base' instead, or just import 'Reflex'" #-}
3+ ( module X
4+ ) where
5+
6+import Reflex.EventWriter.Base as X
7+import Reflex.EventWriter.Class as X
src/Reflex/EventWriter/Base.hsnew file+306
@@ -0,0 +1,306 @@
1+-- | This module provides 'EventWriterT', the standard implementation of
2+-- 'EventWriter'.
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE ExistentialQuantification #-}
5+{-# LANGUAGE FlexibleInstances #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE Rank2Types #-}
9+{-# LANGUAGE ScopedTypeVariables #-}
10+{-# LANGUAGE TypeFamilies #-}
11+{-# LANGUAGE TypeOperators #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+#ifdef USE_REFLEX_OPTIMIZER
14+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15+#endif
16+module Reflex.EventWriter.Base
17+ ( EventWriterT (..)
18+ , runEventWriterT
19+ , runWithReplaceEventWriterTWith
20+ , sequenceDMapWithAdjustEventWriterTWith
21+ , mapEventWriterT
22+ , withEventWriterT
23+ ) where
24+
25+import Reflex.Adjustable.Class
26+import Reflex.Class
27+import Reflex.EventWriter.Class (EventWriter, tellEvent)
28+import Reflex.DynamicWriter.Class (DynamicWriter, tellDyn)
29+import Reflex.Host.Class
30+import Reflex.PerformEvent.Class
31+import Reflex.PostBuild.Class
32+import Reflex.Query.Class
33+import Reflex.Requester.Class
34+import Reflex.TriggerEvent.Class
35+
36+import Control.Monad.Exception
37+import Control.Monad.Identity
38+import Control.Monad.Primitive
39+import Control.Monad.Reader
40+import Control.Monad.Ref
41+import Control.Monad.State.Strict
42+import Data.Dependent.Map (DMap, DSum (..))
43+import qualified Data.Dependent.Map as DMap
44+import Data.Functor.Compose
45+import Data.Functor.Misc
46+import Data.GADT.Compare (GCompare (..), GEq (..), GOrdering (..))
47+import Data.IntMap.Strict (IntMap)
48+import qualified Data.IntMap.Strict as IntMap
49+import Data.List.NonEmpty (NonEmpty (..))
50+import Data.Map (Map)
51+import qualified Data.Map as Map
52+import Data.Semigroup
53+import Data.Some (Some)
54+import Data.Tuple
55+import Data.Type.Equality
56+
57+import Unsafe.Coerce
58+
59+{-# DEPRECATED TellId "Do not construct this directly; use tellId instead" #-}
60+newtype TellId w x
61+ = TellId Int -- ^ WARNING: Do not construct this directly; use 'tellId' instead
62+ deriving (Show, Eq, Ord, Enum)
63+
64+tellId :: Int -> TellId w w
65+tellId = TellId
66+{-# INLINE tellId #-}
67+
68+tellIdRefl :: TellId w x -> w :~: x
69+tellIdRefl _ = unsafeCoerce Refl
70+
71+withTellIdRefl :: TellId w x -> (w ~ x => r) -> r
72+withTellIdRefl tid r = case tellIdRefl tid of
73+ Refl -> r
74+
75+instance GEq (TellId w) where
76+ a `geq` b =
77+ withTellIdRefl a $
78+ withTellIdRefl b $
79+ if a == b
80+ then Just Refl
81+ else Nothing
82+
83+instance GCompare (TellId w) where
84+ a `gcompare` b =
85+ withTellIdRefl a $
86+ withTellIdRefl b $
87+ case a `compare` b of
88+ LT -> GLT
89+ EQ -> GEQ
90+ GT -> GGT
91+
92+data EventWriterState t w = EventWriterState
93+ { _eventWriterState_nextId :: {-# UNPACK #-} !Int -- Always negative (and decreasing over time)
94+ , _eventWriterState_told :: ![DSum (TellId w) (Event t)] -- In increasing order
95+ }
96+
97+-- | A basic implementation of 'EventWriter'.
98+newtype EventWriterT t w m a = EventWriterT { unEventWriterT :: StateT (EventWriterState t w) m a }
99+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
100+
101+-- | Run a 'EventWriterT' action.
102+runEventWriterT :: forall t m w a. (Reflex t, Monad m, Semigroup w) => EventWriterT t w m a -> m (a, Event t w)
103+runEventWriterT (EventWriterT a) = do
104+ (result, requests) <- runStateT a $ EventWriterState (-1) []
105+ let combineResults :: DMap (TellId w) Identity -> w
106+ combineResults = sconcat
107+ . (\(h : t) -> h :| t) -- Unconditional; 'merge' guarantees that it will only fire with non-empty DMaps
108+ . DMap.foldlWithKey (\vs tid (Identity v) -> withTellIdRefl tid $ v : vs) [] -- This is where we finally reverse the DMap to get things in the correct order
109+ return (result, fmap combineResults $ merge $ DMap.fromDistinctAscList $ _eventWriterState_told requests) --TODO: We can probably make this fromDistinctAscList more efficient by knowing the length in advance, but this will require exposing internals of DMap; also converting it to use a strict list might help
110+
111+instance (Reflex t, Monad m, Semigroup w) => EventWriter t w (EventWriterT t w m) where
112+ tellEvent w = EventWriterT $ modify $ \old ->
113+ let myId = _eventWriterState_nextId old
114+ in EventWriterState
115+ { _eventWriterState_nextId = pred myId
116+ , _eventWriterState_told = (tellId myId :=> w) : _eventWriterState_told old
117+ }
118+
119+instance MonadTrans (EventWriterT t w) where
120+ lift = EventWriterT . lift
121+
122+instance MonadSample t m => MonadSample t (EventWriterT t w m) where
123+ sample = lift . sample
124+
125+instance MonadHold t m => MonadHold t (EventWriterT t w m) where
126+ {-# INLINABLE hold #-}
127+ hold v0 = lift . hold v0
128+ {-# INLINABLE holdDyn #-}
129+ holdDyn v0 = lift . holdDyn v0
130+ {-# INLINABLE holdIncremental #-}
131+ holdIncremental v0 = lift . holdIncremental v0
132+ {-# INLINABLE buildDynamic #-}
133+ buildDynamic a0 = lift . buildDynamic a0
134+ {-# INLINABLE headE #-}
135+ headE = lift . headE
136+
137+instance (Reflex t, Adjustable t m, MonadHold t m, Semigroup w) => Adjustable t (EventWriterT t w m) where
138+ runWithReplace = runWithReplaceEventWriterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
139+ traverseIntMapWithKeyWithAdjust = sequenceIntMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') mergeIntIncremental coincidencePatchIntMap
140+ traverseDMapWithKeyWithAdjust = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith mergeMapIncremental coincidencePatchMap
141+ traverseDMapWithKeyWithAdjustWithMove = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeMapIncrementalWithMove coincidencePatchMapWithMove
142+
143+instance Requester t m => Requester t (EventWriterT t w m) where
144+ type Request (EventWriterT t w m) = Request m
145+ type Response (EventWriterT t w m) = Response m
146+ requesting = lift . requesting
147+ requesting_ = lift . requesting_
148+
149+-- | Given a function like 'runWithReplace' for the underlying monad, implement
150+-- 'runWithReplace' for 'EventWriterT'. This is necessary when the underlying
151+-- monad doesn't have a 'Adjustable' instance or to override the default
152+-- 'Adjustable' behavior.
153+runWithReplaceEventWriterTWith :: forall m t w a b. (Reflex t, MonadHold t m, Semigroup w)
154+ => (forall a' b'. m a' -> Event t (m b') -> EventWriterT t w m (a', Event t b'))
155+ -> EventWriterT t w m a
156+ -> Event t (EventWriterT t w m b)
157+ -> EventWriterT t w m (a, Event t b)
158+runWithReplaceEventWriterTWith f a0 a' = do
159+ (result0, result') <- f (runEventWriterT a0) $ fmapCheap runEventWriterT a'
160+ tellEvent =<< switchHoldPromptOnly (snd result0) (fmapCheap snd result')
161+ return (fst result0, fmapCheap fst result')
162+
163+-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceIntMapWithAdjust'.
164+sequenceIntMapWithAdjustEventWriterTWith
165+ :: forall t m p w v v'
166+ . ( Reflex t
167+ , MonadHold t m
168+ , Semigroup w
169+ , Functor p
170+ , Patch (p (Event t w))
171+ , PatchTarget (p (Event t w)) ~ IntMap (Event t w)
172+ , Patch (p w)
173+ , PatchTarget (p w) ~ IntMap w
174+ )
175+ => ( (IntMap.Key -> v -> m (Event t w, v'))
176+ -> IntMap v
177+ -> Event t (p v)
178+ -> EventWriterT t w m (IntMap (Event t w, v'), Event t (p (Event t w, v')))
179+ )
180+ -> (Incremental t (p (Event t w)) -> Event t (PatchTarget (p w)))
181+ -> (Event t (p (Event t w)) -> Event t (p w))
182+ -> (IntMap.Key -> v -> EventWriterT t w m v')
183+ -> IntMap v
184+ -> Event t (p v)
185+ -> EventWriterT t w m (IntMap v', Event t (p v'))
186+sequenceIntMapWithAdjustEventWriterTWith base mergePatchIncremental coincidencePatch f dm0 dm' = do
187+ let f' :: IntMap.Key -> v -> m (Event t w, v')
188+ f' k v = swap <$> runEventWriterT (f k v)
189+ (children0, children') <- base f' dm0 dm'
190+ let result0 = fmap snd children0
191+ result' = fmapCheap (fmap snd) children'
192+ requests0 :: IntMap (Event t w)
193+ requests0 = fmap fst children0
194+ requests' :: Event t (p (Event t w))
195+ requests' = fmapCheap (fmap fst) children'
196+ e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
197+ tellEvent $ fforMaybeCheap e $ \m ->
198+ case IntMap.elems m of
199+ [] -> Nothing
200+ h : t -> Just $ sconcat $ h :| t
201+ return (result0, result')
202+
203+-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceDMapWithAdjust'.
204+sequenceDMapWithAdjustEventWriterTWith
205+ :: forall t m p p' w k v v'
206+ . ( Reflex t
207+ , MonadHold t m
208+ , Semigroup w
209+ , Patch (p' (Some k) (Event t w))
210+ , PatchTarget (p' (Some k) (Event t w)) ~ Map (Some k) (Event t w)
211+ , GCompare k
212+ , Patch (p' (Some k) w)
213+ , PatchTarget (p' (Some k) w) ~ Map (Some k) w
214+ )
215+ => ( (forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a))
216+ -> DMap k v
217+ -> Event t (p k v)
218+ -> EventWriterT t w m (DMap k (Compose ((,) (Event t w)) v'), Event t (p k (Compose ((,) (Event t w)) v')))
219+ )
220+ -> ((forall a. Compose ((,) (Event t w)) v' a -> v' a) -> p k (Compose ((,) (Event t w)) v') -> p k v')
221+ -> ((forall a. Compose ((,) (Event t w)) v' a -> Event t w) -> p k (Compose ((,) (Event t w)) v') -> p' (Some k) (Event t w))
222+ -> (Incremental t (p' (Some k) (Event t w)) -> Event t (PatchTarget (p' (Some k) w)))
223+ -> (Event t (p' (Some k) (Event t w)) -> Event t (p' (Some k) w))
224+ -> (forall a. k a -> v a -> EventWriterT t w m (v' a))
225+ -> DMap k v
226+ -> Event t (p k v)
227+ -> EventWriterT t w m (DMap k v', Event t (p k v'))
228+sequenceDMapWithAdjustEventWriterTWith base mapPatch weakenPatchWith mergePatchIncremental coincidencePatch f dm0 dm' = do
229+ let f' :: forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a)
230+ f' k v = Compose . swap <$> runEventWriterT (f k v)
231+ (children0, children') <- base f' dm0 dm'
232+ let result0 = DMap.map (snd . getCompose) children0
233+ result' = fforCheap children' $ mapPatch $ snd . getCompose
234+ requests0 :: Map (Some k) (Event t w)
235+ requests0 = weakenDMapWith (fst . getCompose) children0
236+ requests' :: Event t (p' (Some k) (Event t w))
237+ requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
238+ e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
239+ tellEvent $ fforMaybeCheap e $ \m ->
240+ case Map.elems m of
241+ [] -> Nothing
242+ h : t -> Just $ sconcat $ h :| t
243+ return (result0, result')
244+
245+instance PerformEvent t m => PerformEvent t (EventWriterT t w m) where
246+ type Performable (EventWriterT t w m) = Performable m
247+ performEvent_ = lift . performEvent_
248+ performEvent = lift . performEvent
249+
250+instance PostBuild t m => PostBuild t (EventWriterT t w m) where
251+ getPostBuild = lift getPostBuild
252+
253+instance TriggerEvent t m => TriggerEvent t (EventWriterT t w m) where
254+ newTriggerEvent = lift newTriggerEvent
255+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
256+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
257+
258+instance MonadReader r m => MonadReader r (EventWriterT t w m) where
259+ ask = lift ask
260+ local f (EventWriterT a) = EventWriterT $ mapStateT (local f) a
261+ reader = lift . reader
262+
263+instance MonadRef m => MonadRef (EventWriterT t w m) where
264+ type Ref (EventWriterT t w m) = Ref m
265+ newRef = lift . newRef
266+ readRef = lift . readRef
267+ writeRef r = lift . writeRef r
268+
269+instance MonadAtomicRef m => MonadAtomicRef (EventWriterT t w m) where
270+ atomicModifyRef r = lift . atomicModifyRef r
271+
272+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (EventWriterT t w m) where
273+ newEventWithTrigger = lift . newEventWithTrigger
274+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
275+
276+instance (MonadQuery t q m, Monad m) => MonadQuery t q (EventWriterT t w m) where
277+ tellQueryIncremental = lift . tellQueryIncremental
278+ askQueryResult = lift askQueryResult
279+ queryIncremental = lift . queryIncremental
280+
281+instance DynamicWriter t w m => DynamicWriter t w (EventWriterT t v m) where
282+ tellDyn = lift . tellDyn
283+
284+instance PrimMonad m => PrimMonad (EventWriterT t w m) where
285+ type PrimState (EventWriterT t w m) = PrimState m
286+ primitive = lift . primitive
287+
288+-- | Map a function over the output of a 'EventWriterT'.
289+withEventWriterT :: (Semigroup w, Semigroup w', Reflex t, MonadHold t m)
290+ => (w -> w')
291+ -> EventWriterT t w m a
292+ -> EventWriterT t w' m a
293+withEventWriterT f ew = do
294+ (r, e) <- lift $ do
295+ (r, e) <- runEventWriterT ew
296+ let e' = fmap f e
297+ return (r, e')
298+ tellEvent e
299+ return r
300+
301+-- | Change the monad underlying an EventWriterT
302+mapEventWriterT
303+ :: (forall x. m x -> n x)
304+ -> EventWriterT t w m a
305+ -> EventWriterT t w n a
306+mapEventWriterT f (EventWriterT a) = EventWriterT $ mapStateT f a
src/Reflex/EventWriter/Class.hsnew file+26
@@ -0,0 +1,26 @@
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.hsnew file+200
@@ -0,0 +1,200 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+#if GHCJS_FAST_WEAK
5+{-# LANGUAGE ForeignFunctionInterface #-}
6+{-# LANGUAGE JavaScriptFFI #-}
7+#endif
8+
9+-- |
10+-- Module:
11+-- Reflex.FastWeak
12+-- Description:
13+-- 'FastWeak' is a weak pointer to some value, and 'FastWeakTicket' ensures the value
14+-- referred to by a 'FastWeak' stays live while the ticket is held (live).
15+--
16+-- On GHC or GHCJS when not built with the @fast-weak@ cabal flag, 'FastWeak' is a wrapper
17+-- around the simple version of 'System.Mem.Weak.Weak' where the key and value are the same.
18+--
19+-- On GHCJS when built with the @fast-weak@ cabal flag, 'FastWeak' is implemented directly
20+-- in JS using @h$FastWeak@ and @h$FastWeakTicket@ which are a nonstandard part of the GHCJS RTS.
21+module Reflex.FastWeak
22+ ( FastWeakTicket
23+ , FastWeak
24+ , mkFastWeakTicket
25+ , getFastWeakTicketValue
26+ , getFastWeakTicketWeak
27+ , getFastWeakValue
28+ , getFastWeakTicket
29+ , emptyFastWeak
30+#ifdef GHCJS_FAST_WEAK
31+ --TODO: Move these elsewhere
32+ , unsafeFromRawJSVal
33+ , unsafeToRawJSVal
34+ , js_isNull
35+#endif
36+ ) where
37+
38+import GHC.Exts (Any)
39+import Unsafe.Coerce
40+
41+#ifdef GHCJS_FAST_WEAK
42+import GHCJS.Types
43+#else
44+import Control.Exception (evaluate)
45+import System.IO.Unsafe
46+import System.Mem.Weak
47+#endif
48+
49+
50+#ifdef GHCJS_FAST_WEAK
51+-- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'
52+-- can be used to get the referred to value without fear of @Nothing,
53+-- and 'getFastWeakTicketWeak' can be used to get the weak version.
54+--
55+-- Implemented by way of special support in the GHCJS RTS, @h$FastWeakTicket@.
56+newtype FastWeakTicket a = FastWeakTicket JSVal
57+
58+-- | A reference to some value which can be garbage collected if there are only
59+-- weak references to the value left.
60+--
61+-- 'getFastWeakValue' can be used to try and obtain a strong reference to the value.
62+--
63+-- The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using
64+-- 'getFastWeakTicket' if the value hasn't been collected yet.
65+--
66+-- Implemented by way of special support in the GHCJS RTS, @h$FastWeak@.
67+newtype FastWeak a = FastWeak JSVal
68+
69+-- Just designed to mirror JSVal, so that we can unsafeCoerce between the two
70+data Val a = Val { unVal :: a }
71+
72+-- | Coerce a JSVal that represents the heap object of a value of type @a@ into a value of type @a@
73+unsafeFromRawJSVal :: JSVal -> a
74+unsafeFromRawJSVal v = unVal (unsafeCoerce v)
75+
76+-- | Coerce a heap object of type @a@ into a 'JSVal' which represents that object.
77+unsafeToRawJSVal :: a -> JSVal
78+unsafeToRawJSVal v = unsafeCoerce (Val v)
79+#else
80+-- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'
81+-- can be used to get the referred to value without fear of @Nothing@,
82+-- and 'getFastWeakTicketWeak' can be used to get the weak version.
83+data FastWeakTicket a = FastWeakTicket
84+ { _fastWeakTicket_val :: !a
85+ , _fastWeakTicket_weak :: {-# UNPACK #-} !(Weak a)
86+ }
87+
88+-- | A reference to some value which can be garbage collected if there are only weak references to the value left.
89+--
90+-- 'getFastWeakValue' can be used to try and obtain a strong reference to the value.
91+--
92+-- The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using 'getFastWeakTicket'
93+-- if the value hasn't been collected yet.
94+--
95+-- Synonymous with 'Weak'.
96+type FastWeak a = Weak a
97+#endif
98+
99+-- | Return the @a@ kept alive by the given 'FastWeakTicket'.
100+--
101+-- This needs to be in IO so we know that we've relinquished the ticket.
102+getFastWeakTicketValue :: FastWeakTicket a -> IO a
103+#ifdef GHCJS_FAST_WEAK
104+getFastWeakTicketValue t = do
105+ v <- js_ticketVal t
106+ return $ unsafeFromRawJSVal v
107+
108+foreign import javascript unsafe "$r = $1.val;" js_ticketVal :: FastWeakTicket a -> IO JSVal
109+#else
110+getFastWeakTicketValue = return . _fastWeakTicket_val
111+#endif
112+
113+-- | Get the value referred to by a 'FastWeak' if it hasn't yet been collected,
114+-- or @Nothing@ if it has been collected.
115+getFastWeakValue :: FastWeak a -> IO (Maybe a)
116+#ifdef GHCJS_FAST_WEAK
117+getFastWeakValue w = do
118+ r <- js_weakVal w
119+ case js_isNull r of
120+ True -> return Nothing
121+ False -> return $ Just $ unsafeFromRawJSVal r
122+
123+foreign import javascript unsafe "$1 === null" js_isNull :: JSVal -> Bool
124+
125+foreign import javascript unsafe "$r = ($1.ticket === null) ? null : $1.ticket.val;" js_weakVal :: FastWeak a -> IO JSVal
126+#else
127+getFastWeakValue = deRefWeak
128+#endif
129+
130+-- | Try to create a 'FastWeakTicket' for the given 'FastWeak' which will ensure the value referred
131+-- remains alive. Returns @Just@ if the value hasn't been collected
132+-- and a ticket can therefore be obtained, @Nothing@ if it's been collected.
133+getFastWeakTicket :: forall a. FastWeak a -> IO (Maybe (FastWeakTicket a))
134+#ifdef GHCJS_FAST_WEAK
135+getFastWeakTicket w = do
136+ r <- js_weakTicket w
137+ case js_isNull r of
138+ True -> return Nothing
139+ False -> return $ Just $ FastWeakTicket r
140+
141+foreign import javascript unsafe "$r = $1.ticket;" js_weakTicket :: FastWeak a -> IO JSVal
142+#else
143+getFastWeakTicket w = do
144+ deRefWeak w >>= \case
145+ Nothing -> return Nothing
146+ Just v -> return $ Just $ FastWeakTicket
147+ { _fastWeakTicket_val = v
148+ , _fastWeakTicket_weak = w
149+ }
150+#endif
151+
152+-- | Create a 'FastWeakTicket' directly from a value, creating a 'FastWeak' in the process
153+-- which can be obtained with 'getFastWeakTicketValue'.
154+mkFastWeakTicket :: a -> IO (FastWeakTicket a)
155+-- I think it's fine if this is lazy - it'll retain the 'a', but so would the output; we just need to make sure it's forced before we start relying on the
156+-- associated FastWeak to actually be weak
157+#ifdef GHCJS_FAST_WEAK
158+mkFastWeakTicket v = js_fastWeakTicket (unsafeToRawJSVal v)
159+
160+foreign import javascript unsafe "$r = new h$FastWeakTicket($1);" js_fastWeakTicket :: JSVal -> IO (FastWeakTicket a)
161+#else
162+mkFastWeakTicket v = do
163+ v' <- evaluate v
164+ w <- mkWeakPtr v' Nothing
165+ return $ FastWeakTicket
166+ { _fastWeakTicket_val = v'
167+ , _fastWeakTicket_weak = w
168+ }
169+#endif
170+
171+-- | Demote a 'FastWeakTicket'; which ensures the value is alive, to a 'FastWeak' which doesn't.
172+-- Note that unless the ticket for the same 'FastWeak' is held in some other way
173+-- the value might be collected immediately.
174+getFastWeakTicketWeak :: FastWeakTicket a -> IO (FastWeak a)
175+-- Needs IO so that it can force the value - otherwise, could end up with a reference to the Ticket, which would retain the value
176+#ifdef GHCJS_FAST_WEAK
177+foreign import javascript unsafe "$r = $1.weak;" getFastWeakTicketWeak' :: FastWeakTicket a -> IO (FastWeak a)
178+{-# INLINE getFastWeakTicketWeak #-}
179+getFastWeakTicketWeak = getFastWeakTicketWeak'
180+#else
181+getFastWeakTicketWeak = return . _fastWeakTicket_weak
182+#endif
183+
184+-- | A weak reference that is always empty
185+emptyFastWeak :: FastWeak a
186+emptyFastWeak = unsafeCoerce w
187+ where w :: FastWeak Any
188+#ifdef GHCJS_FAST_WEAK
189+ w = js_emptyWeak
190+#else
191+ w = unsafePerformIO $ do
192+ w' <- mkWeakPtr undefined Nothing
193+ finalize w'
194+ return w'
195+#endif
196+{-# NOINLINE emptyFastWeak #-}
197+
198+#ifdef GHCJS_FAST_WEAK
199+foreign import javascript unsafe "$r = new h$FastWeak(null);" js_emptyWeak :: FastWeak Any
200+#endif
src/Reflex/FunctorMaybe.hsnew file+47
@@ -0,0 +1,47 @@
1+{-# LANGUAGE CPP #-}
2+#if MIN_VERSION_base(4,9,0)
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE StandaloneDeriving #-}
5+#endif
6+
7+-- |
8+-- Module:
9+-- Reflex.FunctorMaybe
10+-- Description:
11+-- This module defines the FunctorMaybe class, which extends Functors with the
12+-- ability to delete values.
13+module Reflex.FunctorMaybe
14+ ( FunctorMaybe (..)
15+ ) where
16+
17+import Data.IntMap (IntMap)
18+import Data.Map (Map)
19+#if MIN_VERSION_base(4,9,0)
20+import Data.Semigroup (Option(..))
21+#endif
22+import Data.Witherable
23+
24+--TODO: See if there's a better class in the standard libraries already
25+
26+-- | A class for values that combines filtering and mapping using 'Maybe'.
27+-- Morally, @'FunctorMaybe' ~ KleisliFunctor 'Maybe'@.
28+{-# DEPRECATED FunctorMaybe "Use 'Filterable' from Data.Witherable instead" #-}
29+class FunctorMaybe f where
30+ -- | Combined mapping and filtering function.
31+ fmapMaybe :: (a -> Maybe b) -> f a -> f b
32+
33+instance FunctorMaybe Maybe where
34+ fmapMaybe = mapMaybe
35+
36+#if MIN_VERSION_base(4,9,0)
37+deriving instance FunctorMaybe Option
38+#endif
39+
40+instance FunctorMaybe [] where
41+ fmapMaybe = mapMaybe
42+
43+instance FunctorMaybe (Map k) where
44+ fmapMaybe = mapMaybe
45+
46+instance FunctorMaybe IntMap where
47+ fmapMaybe = mapMaybe
src/Reflex/Host/Class.hsnew file+279
@@ -0,0 +1,279 @@
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.hsnew file+45
@@ -0,0 +1,45 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE MultiParamTypeClasses #-}
3+#ifdef USE_REFLEX_OPTIMIZER
4+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5+#endif
6+-- |
7+-- Module:
8+-- Reflex.Network
9+-- Description:
10+-- This module provides combinators for building FRP graphs/networks and modifying them dynamically.
11+module Reflex.Network
12+ ( networkView
13+ , networkHold
14+ , untilReady
15+ ) where
16+
17+import Reflex.Class
18+import Reflex.Adjustable.Class
19+import Reflex.NotReady.Class
20+import Reflex.PostBuild.Class
21+
22+-- | A 'Dynamic' "network": Takes a 'Dynamic' of network-creating actions and replaces the network whenever the 'Dynamic' updates.
23+-- The returned Event of network results fires when the 'Dynamic' updates.
24+-- Note: Often, the type 'a' is an Event, in which case the return value is an Event-of-Events, where the outer 'Event' fires
25+-- when switching networks. Such an 'Event' would typically be flattened (via 'switchPromptly').
26+networkView :: (NotReady t m, Adjustable t m, PostBuild t m) => Dynamic t (m a) -> m (Event t a)
27+networkView child = do
28+ postBuild <- getPostBuild
29+ let newChild = leftmost [updated child, tagCheap (current child) postBuild]
30+ snd <$> runWithReplace notReady newChild
31+
32+-- | Given an initial "network" and an 'Event' of network-creating actions, create a network that is recreated whenever the Event fires.
33+-- The returned Dynamic of network results occurs when the Event does.
34+-- Note: Often, the type 'a' is an Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
35+networkHold :: (Adjustable t m, MonadHold t m) => m a -> Event t (m a) -> m (Dynamic t a)
36+networkHold child0 newChild = do
37+ (result0, newResult) <- runWithReplace child0 newChild
38+ holdDyn result0 newResult
39+
40+-- | Render a placeholder network to be shown while another network is not yet
41+-- done building
42+untilReady :: (Adjustable t m, PostBuild t m) => m a -> m b -> m (a, Event t b)
43+untilReady a b = do
44+ postBuild <- getPostBuild
45+ runWithReplace a $ b <$ postBuild
src/Reflex/NotReady/Class.hsnew file+77
@@ -0,0 +1,77 @@
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.hsnew file+65
@@ -0,0 +1,65 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+-- |
5+-- Module:
6+-- Reflex.Optimizer
7+-- Description:
8+-- This module provides a GHC plugin designed to improve code that uses
9+-- Reflex. Currently, it just adds an INLINABLE pragma to any top-level
10+-- definition that doesn't have an explicit inlining pragma. In the future,
11+-- additional optimizations are likely to be added.
12+module Reflex.Optimizer
13+ ( plugin
14+ ) where
15+
16+#ifdef ghcjs_HOST_OS
17+import Plugins
18+#else
19+import Control.Arrow
20+import CoreMonad
21+import Data.String
22+import GhcPlugins
23+
24+#if MIN_VERSION_base(4,9,0)
25+import Prelude hiding ((<>))
26+#endif
27+
28+#endif
29+
30+#ifdef ghcjs_HOST_OS
31+
32+-- | The GHCJS build of Reflex.Optimizer just throws an error; instead, the version built with GHC should be used.
33+plugin :: Plugin
34+plugin = error "The GHCJS build of Reflex.Optimizer cannot be used. Instead, build with GHC and use the result with GHCJS."
35+
36+#else
37+
38+-- | The GHC plugin itself. See "GhcPlugins" for more details.
39+plugin :: Plugin
40+plugin = defaultPlugin { installCoreToDos = install }
41+
42+install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
43+install [] p = do
44+ liftIO $ putStrLn $ showSDocUnsafe $ ppr p
45+ let f = \case
46+ simpl@(CoreDoSimplify _ _) -> [CoreDoSpecialising, simpl]
47+ x -> [x]
48+ return $ makeInlinable : concatMap f p
49+install options@(_:_) p = do
50+ warnMsg $ "Reflex.Optimizer: ignoring " <> fromString (show $ length options) <> " command-line options"
51+ install [] p
52+
53+makeInlinable :: CoreToDo
54+makeInlinable = CoreDoPluginPass "MakeInlinable" $ \modGuts -> do
55+ let f v = setIdInfo v $ let i = idInfo v in
56+ setInlinePragInfo i $ let p = inlinePragInfo i in
57+ if isDefaultInlinePragma p
58+ then defaultInlinePragma { inl_inline = Inlinable }
59+ else p
60+ newBinds = flip map (mg_binds modGuts) $ \case
61+ NonRec b e -> NonRec (f b) e
62+ Rec bes -> Rec $ map (first f) bes
63+ return $ modGuts { mg_binds = newBinds }
64+
65+#endif
src/Reflex/Patch.hsnew file+46
@@ -0,0 +1,46 @@
1+{-# LANGUAGE TypeFamilies #-}
2+-- |
3+-- Module:
4+-- Reflex.Patch
5+-- Description:
6+-- This module defines the 'Patch' class, which is used by Reflex to manage
7+-- changes to 'Reflex.Class.Incremental' values.
8+module Reflex.Patch
9+ ( module Reflex.Patch
10+ , module X
11+ ) where
12+
13+import Reflex.Patch.Class as X
14+import Reflex.Patch.DMap as X hiding (getDeletions)
15+import Reflex.Patch.DMapWithMove as X (PatchDMapWithMove, const2PatchDMapWithMoveWith, mapPatchDMapWithMove,
16+ patchDMapWithMoveToPatchMapWithMoveWith,
17+ traversePatchDMapWithMoveWithKey, unPatchDMapWithMove,
18+ unsafePatchDMapWithMove, weakenPatchDMapWithMoveWith)
19+import Reflex.Patch.IntMap as X hiding (getDeletions)
20+import Reflex.Patch.Map as X
21+import Reflex.Patch.MapWithMove as X (PatchMapWithMove, patchMapWithMoveNewElements,
22+ patchMapWithMoveNewElementsMap, unPatchMapWithMove,
23+ unsafePatchMapWithMove)
24+import Data.Map.Monoidal (MonoidalMap)
25+import Data.Semigroup (Semigroup (..), (<>))
26+
27+-- | A 'Group' is a 'Monoid' where every element has an inverse.
28+class (Semigroup q, Monoid q) => Group q where
29+ negateG :: q -> q
30+ (~~) :: q -> q -> q
31+ r ~~ s = r <> negateG s
32+
33+-- | An 'Additive' 'Semigroup' is one where (<>) is commutative
34+class Semigroup q => Additive q where
35+
36+-- | The elements of an 'Additive' 'Semigroup' can be considered as patches of their own type.
37+newtype AdditivePatch p = AdditivePatch { unAdditivePatch :: p }
38+
39+instance Additive p => Patch (AdditivePatch p) where
40+ type PatchTarget (AdditivePatch p) = p
41+ apply (AdditivePatch p) q = Just $ p <> q
42+
43+instance (Ord k, Group q) => Group (MonoidalMap k q) where
44+ negateG = fmap negateG
45+
46+instance (Ord k, Additive q) => Additive (MonoidalMap k q)
src/Data/Patch/Class.hs → src/Reflex/Patch/Class.hsrenamed+3−14
@@ -1,23 +1,17 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ScopedTypeVariables #-}
31{-# LANGUAGE TypeFamilies #-}
42-- | The interface for types which represent changes made to other types
5−module Data.Patch.Class where
3+module Reflex.Patch.Class where
64
7−import Data.Functor.Identity
8−import Data.Kind (Type)
5+import Control.Monad.Identity
96import Data.Maybe
10−#if !MIN_VERSION_base(4,11,0)
117import Data.Semigroup (Semigroup(..))
12−#endif
13−import Data.Proxy
148
159-- | A 'Patch' type represents a kind of change made to a datastructure.
1610--
1711-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
1812-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
1913class Patch p where
20− type PatchTarget p :: Type
14+ type PatchTarget p :: *
2115 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
2216 -- 'Nothing'.
2317 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
@@ -31,11 +25,6 @@ instance Patch (Identity a) where
3125 type PatchTarget (Identity a) = a
3226 apply (Identity a) _ = Just a
3327
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−
3928-- | Like '(.)', but composes functions that return patches rather than
4029-- functions that return new values. The Semigroup instance for patches must
4130-- apply patches right-to-left, like '(.)'.
src/Data/Patch/DMap.hs → src/Reflex/Patch/DMap.hsrenamed+5−16
@@ -1,4 +1,3 @@
1−{-# LANGUAGE CPP #-}
21{-# LANGUAGE GeneralizedNewtypeDeriving #-}
32{-# LANGUAGE LambdaCase #-}
43{-# LANGUAGE PolyKinds #-}
@@ -6,26 +5,20 @@
65{-# LANGUAGE ScopedTypeVariables #-}
76{-# LANGUAGE StandaloneDeriving #-}
87{-# LANGUAGE TypeFamilies #-}
9−
108-- | 'Patch'es on 'DMap' that consist only of insertions (or overwrites) and deletions.
11−module Data.Patch.DMap where
9+module Reflex.Patch.DMap where
1210
13−import Data.Patch.Class
14−import Data.Patch.IntMap
15−import Data.Patch.Map
11+import Reflex.Patch.Class
12+import Reflex.Patch.IntMap
13+import Reflex.Patch.Map
1614
17−import Data.Dependent.Map (DMap)
18−import Data.Dependent.Sum (DSum (..))
19−import Data.GADT.Compare (GCompare (..))
15+import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
2016import qualified Data.Dependent.Map as DMap
2117import Data.Functor.Constant
2218import Data.Functor.Misc
2319import qualified Data.IntMap as IntMap
2420import qualified Data.Map as Map
25−import Data.Monoid.DecidablyEmpty
26−#if !MIN_VERSION_base(4,11,0)
2721import Data.Semigroup (Semigroup (..))
28−#endif
2922import Data.Some (Some)
3023
3124-- | A set of changes to a 'DMap'. Any element may be inserted/updated or deleted.
@@ -37,10 +30,6 @@ deriving instance GCompare k => Semigroup (PatchDMap k v)
3730
3831deriving instance GCompare k => Monoid (PatchDMap k v)
3932
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−
4433-- | Apply the insertions or deletions to a given 'DMap'.
4534instance GCompare k => Patch (PatchDMap k v) where
4635 type PatchTarget (PatchDMap k v) = DMap k v
src/Data/Patch/DMapWithMove.hs → src/Reflex/Patch/DMapWithMove.hsrenamed+12−20
@@ -13,28 +13,24 @@
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 Data.Patch.DMapWithMove where
16+module Reflex.Patch.DMapWithMove where
1717
18−import Data.Patch.Class
19−import Data.Patch.MapWithMove (PatchMapWithMove (..))
20−import qualified Data.Patch.MapWithMove as MapWithMove
18+import Reflex.Patch.Class
19+import Reflex.Patch.MapWithMove (PatchMapWithMove (..))
20+import qualified Reflex.Patch.MapWithMove as MapWithMove
2121
2222import Data.Constraint.Extras
23−import Data.Dependent.Map (DMap)
24−import Data.Dependent.Sum (DSum (..))
23+import Data.Dependent.Map (DMap, DSum (..), GCompare (..))
2524import qualified Data.Dependent.Map as DMap
2625import Data.Functor.Constant
2726import Data.Functor.Misc
2827import Data.Functor.Product
29−import Data.GADT.Compare (GEq (..), GCompare (..))
28+import Data.GADT.Compare (GEq (..))
3029import Data.GADT.Show (GShow, gshow)
3130import qualified Data.Map as Map
3231import Data.Maybe
33−import Data.Monoid.DecidablyEmpty
34−#if !MIN_VERSION_base(4,11,0)
35−import Data.Semigroup (Semigroup (..))
36−#endif
37−import Data.Some (Some, mkSome)
32+import Data.Semigroup (Semigroup (..), (<>))
33+import Data.Some (Some(Some))
3834import Data.These
3935
4036-- | Like 'PatchMapWithMove', but for 'DMap'. Each key carries a 'NodeInfo' which describes how it will be changed by the patch and connects move sources and
@@ -46,10 +42,6 @@ import Data.These
4642-- * A move should always be represented with both the destination key (as a 'From_Move') and the source key (as a @'ComposeMaybe' ('Just' destination)@)
4743newtype PatchDMapWithMove k v = PatchDMapWithMove (DMap k (NodeInfo k v))
4844
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−
5345-- |Structure which represents what changes apply to a particular key. @_nodeInfo_from@ specifies what happens to this key, and in particular what other key
5446-- the current key is moving from, while @_nodeInfo_to@ specifies what key the current key is moving to if involved in a move.
5547data NodeInfo k v a = NodeInfo
@@ -220,8 +212,8 @@ moveDMapKey src dst = case src `geq` dst of
220212-- @
221213-- let aMay = DMap.lookup a dmap
222214-- bMay = DMap.lookup b dmap
223−-- in maybe id (DMap.insert a) (bMay <> aMay)
224−-- . maybe id (DMap.insert b) (aMay <> bMay)
215+-- in maybe id (DMap.insert a) (bMay `mplus` aMay)
216+-- . maybe id (DMap.insert b) (aMay `mplus` bMay)
225217-- . DMap.delete a . DMap.delete b $ dmap
226218-- @
227219swapDMapKey :: GCompare k => k a -> k a -> PatchDMapWithMove k v
@@ -318,8 +310,8 @@ weakenPatchDMapWithMoveWith f (PatchDMapWithMove p) = PatchMapWithMove $ weakenD
318310 { MapWithMove._nodeInfo_from = case _nodeInfo_from ni of
319311 From_Insert v -> MapWithMove.From_Insert $ f v
320312 From_Delete -> MapWithMove.From_Delete
321− From_Move k -> MapWithMove.From_Move $ mkSome k
322− , MapWithMove._nodeInfo_to = mkSome <$> getComposeMaybe (_nodeInfo_to ni)
313+ From_Move k -> MapWithMove.From_Move $ Some k
314+ , MapWithMove._nodeInfo_to = Some <$> getComposeMaybe (_nodeInfo_to ni)
323315 }
324316
325317-- |"Weaken" a @'PatchDMapWithMove' (Const2 k a) v@ to a @'PatchMapWithMove' k v'@. Weaken is in scare quotes because the 'Const2' has already disabled any
src/Data/Patch/IntMap.hs → src/Reflex/Patch/IntMap.hsrenamed+14−31
@@ -1,41 +1,22 @@
1−{-# LANGUAGE CPP #-}
1+{-# LANGUAGE DeriveFoldable #-}
2+{-# LANGUAGE DeriveFunctor #-}
23{-# LANGUAGE DeriveTraversable #-}
3−{-# LANGUAGE FlexibleInstances #-}
44{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE StandaloneDeriving #-}
7−{-# LANGUAGE TemplateHaskell #-}
85{-# LANGUAGE TypeFamilies #-}
9−
106-- | Module containing 'PatchIntMap', a 'Patch' for 'IntMap' which allows for
117-- insert/update or delete of associations.
12−module Data.Patch.IntMap where
8+module Reflex.Patch.IntMap where
139
14−import Control.Lens
1510import Data.IntMap.Strict (IntMap)
1611import qualified Data.IntMap.Strict as IntMap
1712import Data.Maybe
18−import Data.Monoid.DecidablyEmpty
19−#if !MIN_VERSION_base(4,11,0)
20−import Data.Semigroup (Semigroup (..))
21−#endif
22−import Data.Patch.Class
13+import Data.Semigroup
14+import Reflex.Patch.Class
2315
2416-- | 'Patch' for 'IntMap' which represents insertion or deletion of keys in the mapping.
2517-- Internally represented by 'IntMap (Maybe a)', where @Just@ means insert/update
2618-- and @Nothing@ means delete.
27−newtype PatchIntMap a = PatchIntMap { unPatchIntMap :: IntMap (Maybe a) }
28− deriving ( Show, Read, Eq, Ord
29− , Functor, Foldable, Traversable
30− , Monoid, DecidablyEmpty
31− )
32−
33−-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
34−-- If the same key is modified by both patches, the one on the left will take
35−-- precedence.
36−deriving instance Semigroup (PatchIntMap v)
37−
38−makeWrapped ''PatchIntMap
19+newtype PatchIntMap a = PatchIntMap (IntMap (Maybe a)) deriving (Functor, Foldable, Traversable, Monoid)
3920
4021-- | Apply the insertions or deletions to a given 'IntMap'.
4122instance Patch (PatchIntMap a) where
@@ -45,11 +26,13 @@ instance Patch (PatchIntMap a) where
4526 adds = IntMap.mapMaybe id p
4627 in IntMap.union adds $ v `IntMap.difference` removes
4728
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
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
5336
5437-- | Map a function @Int -> a -> b@ over all @a@s in the given @'PatchIntMap' a@
5538-- (that is, all inserts/updates), producing a @PatchIntMap b@.
@@ -59,7 +42,7 @@ mapIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap $ IntMap.mapWithKey (\ k m
5942-- | Map an effectful function @Int -> a -> f b@ over all @a@s in the given @'PatchIntMap' a@
6043-- (that is, all inserts/updates), producing a @f (PatchIntMap b)@.
6144traverseIntMapPatchWithKey :: Applicative f => (Int -> a -> f b) -> PatchIntMap a -> f (PatchIntMap b)
62−traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (traverse . f) m
45+traverseIntMapPatchWithKey f (PatchIntMap m) = PatchIntMap <$> IntMap.traverseWithKey (\k mv -> traverse (f k) mv) m
6346
6447-- | Extract all @a@s inserted/updated by the given @'PatchIntMap' a@.
6548patchIntMapNewElements :: PatchIntMap a -> [a]
src/Data/Patch/Map.hs → src/Reflex/Patch/Map.hsrenamed+21−38
@@ -1,48 +1,21 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveTraversable #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
51{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE StandaloneDeriving #-}
8−{-# LANGUAGE TemplateHaskell #-}
92{-# LANGUAGE TypeFamilies #-}
10−
113-- | 'Patch'es on 'Map' that consist only of insertions (including overwrites)
124-- and deletions
13−module Data.Patch.Map where
5+module Reflex.Patch.Map where
146
15−import Data.Patch.Class
7+import Reflex.Patch.Class
168
17−import Control.Lens
189import Data.Map (Map)
1910import qualified Data.Map as Map
2011import Data.Maybe
21−import Data.Monoid.DecidablyEmpty
22−import Data.Semigroup (Semigroup (..), stimesIdempotentMonoid)
12+import Data.Semigroup
2313
2414-- | A set of changes to a 'Map'. Any element may be inserted/updated or
2515-- deleted. Insertions are represented as values wrapped in 'Just', while
2616-- deletions are represented as 'Nothing's
2717newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
28− deriving ( Show, Read, Eq, Ord
29− , Foldable, Traversable
30− , DecidablyEmpty
31− )
32−
33−-- | 'fmap'ping a 'PatchMap' will alter all of the values it will insert.
34−-- Deletions are unaffected.
35−deriving instance Functor (PatchMap k)
36−-- | The empty 'PatchMap' contains no insertions or deletions
37−deriving instance Ord k => Monoid (PatchMap k v)
38−
39−-- | @a <> b@ will apply the changes of @b@ and then apply the changes of @a@.
40−-- If the same key is modified by both patches, the one on the left will take
41−-- precedence.
42−instance Ord k => Semigroup (PatchMap k v) where
43− PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
44− -- PatchMap is idempotent, so stimes n is id for every n
45− stimes = stimesIdempotentMonoid
18+ deriving (Show, Read, Eq, Ord)
4619
4720-- | Apply the insertions or deletions to a given 'Map'.
4821instance Ord k => Patch (PatchMap k v) where
@@ -55,11 +28,23 @@ instance Ord k => Patch (PatchMap k v) where
5528 Nothing -> Just ()
5629 Just _ -> Nothing
5730
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
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
6348
6449-- | Returns all the new elements that will be added to the 'Map'
6550patchMapNewElements :: PatchMap k v -> [v]
@@ -68,5 +53,3 @@ patchMapNewElements (PatchMap p) = catMaybes $ Map.elems p
6853-- | Returns all the new elements that will be added to the 'Map'
6954patchMapNewElementsMap :: PatchMap k v -> Map k v
7055patchMapNewElementsMap (PatchMap p) = Map.mapMaybe id p
71−
72−makeWrapped ''PatchMap
src/Reflex/Patch/MapWithMove.hsnew file+270
@@ -0,0 +1,270 @@
1+{-# LANGUAGE DeriveFoldable #-}
2+{-# LANGUAGE DeriveFunctor #-}
3+{-# LANGUAGE DeriveTraversable #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE PatternGuards #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE TypeFamilies #-}
9+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
10+-- another
11+module Reflex.Patch.MapWithMove where
12+
13+import Reflex.Patch.Class
14+
15+import Control.Arrow
16+import Control.Monad.State
17+import Data.Foldable
18+import Data.Function
19+import Data.List
20+import Data.Map (Map)
21+import qualified Data.Map as Map
22+import Data.Maybe
23+import Data.Semigroup (Semigroup (..), (<>))
24+import qualified Data.Set as Set
25+import Data.These (These(..))
26+import Data.Tuple
27+
28+-- | Patch a DMap with additions, deletions, and moves. Invariant: If key @k1@
29+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
30+-- and vice versa. There should never be any unpaired From/To keys.
31+newtype PatchMapWithMove k v = PatchMapWithMove (Map k (NodeInfo k v)) deriving (Show, Eq, Ord, Functor, Foldable, Traversable)
32+
33+-- | Holds the information about each key: where its new value should come from,
34+-- and where its old value should go to
35+data NodeInfo k v = NodeInfo
36+ { _nodeInfo_from :: !(From k v)
37+ -- ^ Where do we get the new value for this key?
38+ , _nodeInfo_to :: !(To k)
39+ -- ^ If the old value is being kept (i.e. moved rather than deleted or
40+ -- replaced), where is it going?
41+ }
42+ deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
43+
44+-- | Describe how a key's new value should be produced
45+data From k v
46+ = From_Insert v -- ^ Insert the given value here
47+ | From_Delete -- ^ Delete the existing value, if any, from here
48+ | From_Move !k -- ^ Move the value here from the given key
49+ deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
50+
51+-- | Describe where a key's old value will go. If this is 'Just', that means
52+-- the key's old value will be moved to the given other key; if it is 'Nothing',
53+-- that means it will be deleted.
54+type To = Maybe
55+
56+-- | Create a 'PatchMapWithMove', validating it
57+patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
58+patchMapWithMove m = if valid then Just $ PatchMapWithMove m else Nothing
59+ where valid = forwardLinks == backwardLinks
60+ forwardLinks = Map.mapMaybe _nodeInfo_to m
61+ backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, v) ->
62+ case _nodeInfo_from v of
63+ From_Move from -> Just (from, to)
64+ _ -> Nothing
65+
66+-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
67+patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
68+patchMapWithMoveInsertAll m = PatchMapWithMove $ flip fmap m $ \v -> NodeInfo
69+ { _nodeInfo_from = From_Insert v
70+ , _nodeInfo_to = Nothing
71+ }
72+
73+-- | Extract the internal representation of the 'PatchMapWithMove'
74+unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
75+unPatchMapWithMove (PatchMapWithMove p) = p
76+
77+-- | Make a @'PatchMapWithMove' k v@ which has the effect of inserting or updating a value @v@ to the given key @k@, like 'Map.insert'.
78+insertMapKey :: k -> v -> PatchMapWithMove k v
79+insertMapKey k v = PatchMapWithMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
80+
81+-- |Make a @'PatchMapWithMove' k v@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
82+--
83+-- @
84+-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
85+-- @
86+moveMapKey :: Ord k => k -> k -> PatchMapWithMove k v
87+moveMapKey src dst
88+ | src == dst = mempty
89+ | otherwise =
90+ PatchMapWithMove $ Map.fromList
91+ [ (dst, NodeInfo (From_Move src) Nothing)
92+ , (src, NodeInfo From_Delete (Just dst))
93+ ]
94+
95+-- |Make a @'PatchMapWithMove' k v@ which has the effect of swapping two keys in the mapping, equivalent to:
96+--
97+-- @
98+-- let aMay = Map.lookup a map
99+-- bMay = Map.lookup b map
100+-- in maybe id (Map.insert a) (bMay `mplus` aMay)
101+-- . maybe id (Map.insert b) (aMay `mplus` bMay)
102+-- . Map.delete a . Map.delete b $ map
103+-- @
104+swapMapKey :: Ord k => k -> k -> PatchMapWithMove k v
105+swapMapKey src dst
106+ | src == dst = mempty
107+ | otherwise =
108+ PatchMapWithMove $ Map.fromList
109+ [ (dst, NodeInfo (From_Move src) (Just src))
110+ , (src, NodeInfo (From_Move dst) (Just dst))
111+ ]
112+
113+-- |Make a @'PatchMapWithMove' k v@ which has the effect of deleting a key in the mapping, equivalent to 'Map.delete'.
114+deleteMapKey :: k -> PatchMapWithMove k v
115+deleteMapKey k = PatchMapWithMove . Map.singleton k $ NodeInfo From_Delete Nothing
116+
117+-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithMove' k v@, without checking any invariants.
118+--
119+-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithMove' are preserved; they will not be checked.
120+unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
121+unsafePatchMapWithMove = PatchMapWithMove
122+
123+-- | Apply the insertions, deletions, and moves to a given 'Map'
124+instance Ord k => Patch (PatchMapWithMove k v) where
125+ type PatchTarget (PatchMapWithMove k v) = Map k v
126+ apply (PatchMapWithMove p) old = Just $! insertions `Map.union` (old `Map.difference` deletions) --TODO: return Nothing sometimes --Note: the strict application here is critical to ensuring that incremental merges don't hold onto all their prerequisite events forever; can we make this more robust?
127+ where insertions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
128+ From_Insert v -> Just v
129+ From_Move k -> Map.lookup k old
130+ From_Delete -> Nothing
131+ deletions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
132+ From_Delete -> Just ()
133+ _ -> Nothing
134+
135+-- | Returns all the new elements that will be added to the 'Map'.
136+patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
137+patchMapWithMoveNewElements = Map.elems . patchMapWithMoveNewElementsMap
138+
139+-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithMove' k v@.
140+patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
141+patchMapWithMoveNewElementsMap (PatchMapWithMove p) = Map.mapMaybe f p
142+ where f ni = case _nodeInfo_from ni of
143+ From_Insert v -> Just v
144+ From_Move _ -> Nothing
145+ From_Delete -> Nothing
146+
147+-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
148+-- its values using the given ordering function. The set keys of the 'Map' is
149+-- not changed.
150+patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
151+patchThatSortsMapWith cmp m = PatchMapWithMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
152+ where unsorted = Map.toList m
153+ sorted = sortBy (cmp `on` snd) unsorted
154+ f (to, _) (from, _) = if to == from then Nothing else
155+ Just (from, to)
156+ reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
157+ g (to, _) (from, _) = if to == from then Nothing else
158+ let Just movingTo = Map.lookup from reverseMapping
159+ in Just (to, NodeInfo (From_Move from) $ Just movingTo)
160+
161+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
162+-- will produce a 'Map' with the same values as the second 'Map' but with the
163+-- values sorted with the given ordering function.
164+patchThatChangesAndSortsMapWith :: forall k v. (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
165+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
166+ where newList = Map.toList newByIndexUnsorted
167+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
168+
169+-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
170+-- will produce the second 'Map'.
171+patchThatChangesMap :: (Ord k, Ord v) => Map k v -> Map k v -> PatchMapWithMove k v
172+patchThatChangesMap oldByIndex newByIndex = patch
173+ where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
174+ (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
175+ let f k v = do
176+ remainingValues <- get
177+ let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
178+ then Map.delete v remainingValues
179+ else Map.insert v remainingKeys remainingValues
180+ case Map.lookup v remainingValues of
181+ Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
182+ Just fromKs ->
183+ if k `Set.member` fromKs
184+ then do
185+ putRemainingKeys $ Set.delete k fromKs
186+ return $ NodeInfo (From_Move k) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
187+ else do
188+ (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
189+ putRemainingKeys remainingKeys
190+ return $ NodeInfo (From_Move fromK) $ Just undefined
191+ Map.traverseWithKey f newByIndex
192+ unusedOldKeys = fold unusedValuesByValue
193+ pointlessMove k = \case
194+ From_Move k' | k == k' -> True
195+ _ -> False
196+ keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
197+ then Just undefined
198+ else Nothing
199+ patch = unsafePatchMapWithMove $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
200+
201+-- | Change the 'From' value of a 'NodeInfo'
202+nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
203+nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
204+
205+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
206+-- 'Applicative', 'Monad', etc.) action to get the new value
207+nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
208+nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
209+
210+-- | Set the 'To' field of a 'NodeInfo'
211+nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
212+nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
213+
214+-- |Helper data structure used for composing patches using the monoid instance.
215+data Fixup k v
216+ = Fixup_Delete
217+ | Fixup_Update (These (From k v) (To k))
218+
219+-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
220+instance Ord k => Semigroup (PatchMapWithMove k v) where
221+ PatchMapWithMove ma <> PatchMapWithMove mb = PatchMapWithMove m
222+ where
223+ connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
224+ h :: (k, (Maybe k, From k v)) -> [(k, Fixup k v)]
225+ h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
226+ (Just toAfter, From_Move fromBefore)
227+ | fromBefore == toAfter
228+ -> [(toAfter, Fixup_Delete)]
229+ | otherwise
230+ -> [ (toAfter, Fixup_Update (This editBefore))
231+ , (fromBefore, Fixup_Update (That mToAfter))
232+ ]
233+ (Nothing, From_Move fromBefore) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
234+ (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
235+ (Nothing, _) -> []
236+ mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
237+ mergeFixups _ (Fixup_Update a) (Fixup_Update b)
238+ | This x <- a, That y <- b
239+ = Fixup_Update $ These x y
240+ | That y <- a, This x <- b
241+ = Fixup_Update $ These x y
242+ mergeFixups _ _ _ = error "PatchMapWithMove: incompatible fixups"
243+ fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
244+ combineNodeInfos _ nia nib = NodeInfo
245+ { _nodeInfo_from = _nodeInfo_from nia
246+ , _nodeInfo_to = _nodeInfo_to nib
247+ }
248+ applyFixup _ ni = \case
249+ Fixup_Delete -> Nothing
250+ Fixup_Update u -> Just $ NodeInfo
251+ { _nodeInfo_from = fromMaybe (_nodeInfo_from ni) $ getHere u
252+ , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
253+ }
254+ m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
255+ getHere :: These a b -> Maybe a
256+ getHere = \case
257+ This a -> Just a
258+ These a _ -> Just a
259+ That _ -> Nothing
260+ getThere :: These a b -> Maybe b
261+ getThere = \case
262+ This _ -> Nothing
263+ These _ b -> Just b
264+ That b -> Just b
265+
266+--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
267+-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
268+instance Ord k => Monoid (PatchMapWithMove k v) where
269+ mempty = PatchMapWithMove mempty
270+ mappend = (<>)
src/Reflex/PerformEvent/Base.hsnew file+179
@@ -0,0 +1,179 @@
1+-- | This module provides 'PerformEventT', the standard implementation of
2+-- 'PerformEvent'.
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE ExistentialQuantification #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GADTs #-}
8+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE PartialTypeSignatures #-}
11+{-# LANGUAGE PolyKinds #-}
12+{-# LANGUAGE RankNTypes #-}
13+{-# LANGUAGE ScopedTypeVariables #-}
14+{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE TypeFamilies #-}
16+{-# LANGUAGE TypeOperators #-}
17+{-# LANGUAGE UndecidableInstances #-}
18+#ifdef USE_REFLEX_OPTIMIZER
19+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20+#endif
21+module Reflex.PerformEvent.Base
22+ ( PerformEventT (..)
23+ , FireCommand (..)
24+ , hostPerformEventT
25+ ) where
26+
27+import Reflex.Class
28+import Reflex.Adjustable.Class
29+import Reflex.Host.Class
30+import Reflex.PerformEvent.Class
31+import Reflex.Requester.Base
32+import Reflex.Requester.Class
33+
34+import Control.Lens
35+import Control.Monad.Exception
36+import Control.Monad.Identity
37+import Control.Monad.Primitive
38+import Control.Monad.Reader
39+import Control.Monad.Ref
40+import Data.Coerce
41+import Data.Dependent.Map (DMap)
42+import qualified Data.Dependent.Map as DMap
43+import Data.Dependent.Sum
44+import Data.IntMap.Strict (IntMap)
45+import qualified Data.IntMap.Strict as IntMap
46+import qualified Data.Semigroup as S
47+
48+-- | A function that fires events for the given 'EventTrigger's and then runs
49+-- any followup actions provided via 'PerformEvent'. The given 'ReadPhase'
50+-- action will be run once for the initial trigger execution as well as once for
51+-- each followup.
52+newtype FireCommand t m = FireCommand { runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a] } --TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?
53+
54+-- | Provides a basic implementation of 'PerformEvent'. Note that, despite the
55+-- name, 'PerformEventT' is not an instance of 'MonadTrans'.
56+newtype PerformEventT t m a = PerformEventT { unPerformEventT :: RequesterT t (HostFrame t) Identity (HostFrame t) a }
57+
58+deriving instance ReflexHost t => Functor (PerformEventT t m)
59+deriving instance ReflexHost t => Applicative (PerformEventT t m)
60+deriving instance ReflexHost t => Monad (PerformEventT t m)
61+deriving instance ReflexHost t => MonadFix (PerformEventT t m)
62+deriving instance (ReflexHost t, MonadIO (HostFrame t)) => MonadIO (PerformEventT t m)
63+deriving instance (ReflexHost t, MonadException (HostFrame t)) => MonadException (PerformEventT t m)
64+deriving instance (ReflexHost t, Monoid a) => Monoid (PerformEventT t m a)
65+deriving instance (ReflexHost t, S.Semigroup a) => S.Semigroup (PerformEventT t m a)
66+
67+instance (PrimMonad (HostFrame t), ReflexHost t) => PrimMonad (PerformEventT t m) where
68+ type PrimState (PerformEventT t m) = PrimState (HostFrame t)
69+ primitive = PerformEventT . lift . primitive
70+
71+instance (ReflexHost t, Ref m ~ Ref IO) => PerformEvent t (PerformEventT t m) where
72+ type Performable (PerformEventT t m) = HostFrame t
73+ {-# INLINABLE performEvent_ #-}
74+ performEvent_ = PerformEventT . requesting_
75+ {-# INLINABLE performEvent #-}
76+ performEvent = PerformEventT . requestingIdentity
77+
78+instance (ReflexHost t, PrimMonad (HostFrame t)) => Adjustable t (PerformEventT t m) where
79+ runWithReplace outerA0 outerA' = PerformEventT $ runWithReplaceRequesterTWith f (coerce outerA0) (coerceEvent outerA')
80+ where f :: HostFrame t a -> Event t (HostFrame t b) -> RequesterT t (HostFrame t) Identity (HostFrame t) (a, Event t b)
81+ f a0 a' = do
82+ result0 <- lift a0
83+ result' <- requestingIdentity a'
84+ return (result0, result')
85+ traverseIntMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseIntMapWithKeyWithAdjustRequesterTWith (defaultAdjustIntBase traverseIntMapPatchWithKey) patchIntMapNewElementsMap mergeIntIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
86+ traverseDMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithKey) mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
87+ traverseDMapWithKeyWithAdjustWithMove f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithMoveWithKey) mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
88+
89+defaultAdjustBase :: forall t v v2 k' p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
90+ => ((forall a. k' a -> v a -> HostFrame t (v2 a)) -> p k' v -> HostFrame t (p k' v2))
91+ -> (forall a. k' a -> v a -> HostFrame t (v2 a))
92+ -> DMap k' v
93+ -> Event t (p k' v)
94+ -> RequesterT t (HostFrame t) Identity (HostFrame t) (DMap k' v2, Event t (p k' v2))
95+defaultAdjustBase traversePatchWithKey f' dm0 dm' = do
96+ result0 <- lift $ DMap.traverseWithKey f' dm0
97+ result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
98+ return (result0, result')
99+
100+defaultAdjustIntBase :: forall t v v2 p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
101+ => ((IntMap.Key -> v -> HostFrame t v2) -> p v -> HostFrame t (p v2))
102+ -> (IntMap.Key -> v -> HostFrame t v2)
103+ -> IntMap v
104+ -> Event t (p v)
105+ -> RequesterT t (HostFrame t) Identity (HostFrame t) (IntMap v2, Event t (p v2))
106+defaultAdjustIntBase traversePatchWithKey f' dm0 dm' = do
107+ result0 <- lift $ IntMap.traverseWithKey f' dm0
108+ result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
109+ return (result0, result')
110+
111+instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where
112+ {-# INLINABLE newEventWithTrigger #-}
113+ newEventWithTrigger = PerformEventT . lift . newEventWithTrigger
114+ {-# INLINABLE newFanEventWithTrigger #-}
115+ newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f
116+
117+-- | Run a 'PerformEventT' action, returning a 'FireCommand' that allows the
118+-- caller to trigger 'Event's while ensuring that 'performEvent' actions are run
119+-- at the appropriate time.
120+{-# INLINABLE hostPerformEventT #-}
121+hostPerformEventT :: forall t m a.
122+ ( Monad m
123+ , MonadSubscribeEvent t m
124+ , MonadReflexHost t m
125+ , MonadRef m
126+ , Ref m ~ Ref IO
127+ )
128+ => PerformEventT t m a
129+ -> m (a, FireCommand t m)
130+hostPerformEventT a = do
131+ (response, responseTrigger) <- newEventWithTriggerRef
132+ (result, eventToPerform) <- runHostFrame $ runRequesterT (unPerformEventT a) response
133+ eventToPerformHandle <- subscribeEvent eventToPerform
134+ return $ (,) result $ FireCommand $ \triggers (readPhase :: ReadPhase m a') -> do
135+ let go :: [DSum (EventTrigger t) Identity] -> m [a']
136+ go ts = do
137+ (result', mToPerform) <- fireEventsAndRead ts $ do
138+ mToPerform <- sequence =<< readEvent eventToPerformHandle
139+ result' <- readPhase
140+ return (result', mToPerform)
141+ case mToPerform of
142+ Nothing -> return [result']
143+ Just toPerform -> do
144+ responses <- runHostFrame $ traverseRequesterData (\v -> Identity <$> v) toPerform
145+ mrt <- readRef responseTrigger
146+ let followupEventTriggers = case mrt of
147+ Just rt -> [rt :=> Identity responses]
148+ Nothing -> []
149+ (result':) <$> go followupEventTriggers
150+ go triggers
151+
152+instance ReflexHost t => MonadSample t (PerformEventT t m) where
153+ {-# INLINABLE sample #-}
154+ sample = PerformEventT . lift . sample
155+
156+instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where
157+ {-# INLINABLE hold #-}
158+ hold v0 v' = PerformEventT $ lift $ hold v0 v'
159+ {-# INLINABLE holdDyn #-}
160+ holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'
161+ {-# INLINABLE holdIncremental #-}
162+ holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'
163+ {-# INLINABLE buildDynamic #-}
164+ buildDynamic getV0 v' = PerformEventT $ lift $ buildDynamic getV0 v'
165+ {-# INLINABLE headE #-}
166+ headE = PerformEventT . lift . headE
167+
168+instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where
169+ type Ref (PerformEventT t m) = Ref (HostFrame t)
170+ {-# INLINABLE newRef #-}
171+ newRef = PerformEventT . lift . newRef
172+ {-# INLINABLE readRef #-}
173+ readRef = PerformEventT . lift . readRef
174+ {-# INLINABLE writeRef #-}
175+ writeRef r = PerformEventT . lift . writeRef r
176+
177+instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where
178+ {-# INLINABLE atomicModifyRef #-}
179+ atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
src/Reflex/PerformEvent/Class.hsnew file+63
@@ -0,0 +1,63 @@
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.hsnew file+197
@@ -0,0 +1,197 @@
1+-- | This module defines 'PostBuildT', the standard implementation of
2+-- 'PostBuild'.
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE FlexibleInstances #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE RankNTypes #-}
9+{-# LANGUAGE RecursiveDo #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE TypeOperators #-}
13+{-# LANGUAGE UndecidableInstances #-}
14+#ifdef USE_REFLEX_OPTIMIZER
15+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
16+#endif
17+module Reflex.PostBuild.Base
18+ ( PostBuildT (..)
19+ , runPostBuildT
20+ -- * Internal
21+ , mapIntMapWithAdjustImpl
22+ , mapDMapWithAdjustImpl
23+ ) where
24+
25+import Reflex.Class
26+import Reflex.Adjustable.Class
27+import Reflex.Host.Class
28+import Reflex.PerformEvent.Class
29+import Reflex.PostBuild.Class
30+import Reflex.TriggerEvent.Class
31+
32+import Control.Applicative (liftA2)
33+import Control.Monad.Exception
34+import Control.Monad.Identity
35+import Control.Monad.Primitive
36+import Control.Monad.Reader
37+import Control.Monad.Ref
38+import qualified Control.Monad.Trans.Control as TransControl
39+import Data.Dependent.Map (DMap)
40+import qualified Data.Dependent.Map as DMap
41+import Data.Functor.Compose
42+import Data.IntMap.Strict (IntMap)
43+import qualified Data.IntMap.Strict as IntMap
44+import qualified Data.Semigroup as S
45+
46+-- | Provides a basic implementation of 'PostBuild'.
47+newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException)
48+
49+-- | Run a 'PostBuildT' action. An 'Event' should be provided that fires
50+-- immediately after the action is finished running; no other 'Event's should
51+-- fire first.
52+{-# INLINABLE runPostBuildT #-}
53+runPostBuildT :: PostBuildT t m a -> Event t () -> m a
54+runPostBuildT (PostBuildT a) = runReaderT a
55+
56+-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
57+instance (Monoid a, Applicative m) => Monoid (PostBuildT t m a) where
58+ mempty = pure mempty
59+ mappend = liftA2 mappend
60+
61+instance (S.Semigroup a, Applicative m) => S.Semigroup (PostBuildT t m a) where
62+ (<>) = liftA2 (S.<>)
63+
64+instance PrimMonad m => PrimMonad (PostBuildT x m) where
65+ type PrimState (PostBuildT x m) = PrimState m
66+ primitive = lift . primitive
67+
68+instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where
69+ {-# INLINABLE getPostBuild #-}
70+ getPostBuild = PostBuildT ask
71+
72+instance MonadSample t m => MonadSample t (PostBuildT t m) where
73+ {-# INLINABLE sample #-}
74+ sample = lift . sample
75+
76+instance MonadHold t m => MonadHold t (PostBuildT t m) where
77+ {-# INLINABLE hold #-}
78+ hold v0 = lift . hold v0
79+ {-# INLINABLE holdDyn #-}
80+ holdDyn v0 = lift . holdDyn v0
81+ {-# INLINABLE holdIncremental #-}
82+ holdIncremental v0 = lift . holdIncremental v0
83+ {-# INLINABLE buildDynamic #-}
84+ buildDynamic a0 = lift . buildDynamic a0
85+ {-# INLINABLE headE #-}
86+ headE = lift . headE
87+
88+instance PerformEvent t m => PerformEvent t (PostBuildT t m) where
89+ type Performable (PostBuildT t m) = Performable m
90+ {-# INLINABLE performEvent_ #-}
91+ performEvent_ = lift . performEvent_
92+ {-# INLINABLE performEvent #-}
93+ performEvent = lift . performEvent
94+
95+instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where
96+ {-# INLINABLE newEventWithTrigger #-}
97+ newEventWithTrigger = PostBuildT . lift . newEventWithTrigger
98+ {-# INLINABLE newFanEventWithTrigger #-}
99+ newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f
100+
101+instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where
102+ {-# INLINABLE newTriggerEvent #-}
103+ newTriggerEvent = lift newTriggerEvent
104+ {-# INLINABLE newTriggerEventWithOnComplete #-}
105+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
106+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
107+
108+instance MonadRef m => MonadRef (PostBuildT t m) where
109+ type Ref (PostBuildT t m) = Ref m
110+ {-# INLINABLE newRef #-}
111+ newRef = lift . newRef
112+ {-# INLINABLE readRef #-}
113+ readRef = lift . readRef
114+ {-# INLINABLE writeRef #-}
115+ writeRef r = lift . writeRef r
116+
117+instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where
118+ {-# INLINABLE atomicModifyRef #-}
119+ atomicModifyRef r = lift . atomicModifyRef r
120+
121+instance (Reflex t, MonadHold t m, MonadFix m, Adjustable t m, PerformEvent t m) => Adjustable t (PostBuildT t m) where
122+ runWithReplace a0 a' = do
123+ postBuild <- getPostBuild
124+ lift $ do
125+ rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a'
126+ let voidResult' = fmapCheap (\_ -> ()) result'
127+ return result
128+ {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
129+ traverseIntMapWithKeyWithAdjust = mapIntMapWithAdjustImpl traverseIntMapWithKeyWithAdjust
130+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
131+ traverseDMapWithKeyWithAdjust = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap
132+ traverseDMapWithKeyWithAdjustWithMove = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove
133+
134+{-# INLINABLE mapIntMapWithAdjustImpl #-}
135+mapIntMapWithAdjustImpl :: forall t m v v' p. (Reflex t, MonadFix m, MonadHold t m, Functor p)
136+ => ( (IntMap.Key -> (Event t (), v) -> m v')
137+ -> IntMap (Event t (), v)
138+ -> Event t (p (Event t (), v))
139+ -> m (IntMap v', Event t (p v'))
140+ )
141+ -> (IntMap.Key -> v -> PostBuildT t m v')
142+ -> IntMap v
143+ -> Event t (p v)
144+ -> PostBuildT t m (IntMap v', Event t (p v'))
145+mapIntMapWithAdjustImpl base f dm0 dm' = do
146+ postBuild <- getPostBuild
147+ let loweredDm0 = fmap ((,) postBuild) dm0
148+ f' :: IntMap.Key -> (Event t (), v) -> m v'
149+ f' k (e, v) = do
150+ runPostBuildT (f k v) e
151+ lift $ do
152+ rec (result0, result') <- base f' loweredDm0 loweredDm'
153+ cohortDone <- numberOccurrencesFrom_ 1 result'
154+ numberedDm' <- numberOccurrencesFrom 1 dm'
155+ let postBuild' = fanInt $ fmapCheap (`IntMap.singleton` ()) cohortDone
156+ loweredDm' = flip pushAlways numberedDm' $ \(n, p) -> do
157+ return $ fmap ((,) (selectInt postBuild' n)) p
158+ return (result0, result')
159+
160+{-# INLINABLE mapDMapWithAdjustImpl #-}
161+mapDMapWithAdjustImpl :: forall t m k v v' p. (Reflex t, MonadFix m, MonadHold t m)
162+ => ( (forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a))
163+ -> DMap k (Compose ((,) (Bool, Event t ())) v)
164+ -> Event t (p k (Compose ((,) (Bool, Event t ())) v))
165+ -> m (DMap k v', Event t (p k v'))
166+ )
167+ -> ((forall a. v a -> Compose ((,) (Bool, Event t ())) v a) -> p k v -> p k (Compose ((,) (Bool, Event t ())) v))
168+ -> (forall a. k a -> v a -> PostBuildT t m (v' a))
169+ -> DMap k v
170+ -> Event t (p k v)
171+ -> PostBuildT t m (DMap k v', Event t (p k v'))
172+mapDMapWithAdjustImpl base mapPatch f dm0 dm' = do
173+ postBuild <- getPostBuild
174+ let loweredDm0 = DMap.map (Compose . (,) (False, postBuild)) dm0
175+ f' :: forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a)
176+ f' k (Compose ((shouldHeadE, e), v)) = do
177+ eOnce <- if shouldHeadE
178+ then headE e --TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence
179+ else return e
180+ runPostBuildT (f k v) eOnce
181+ lift $ do
182+ rec (result0, result') <- base f' loweredDm0 loweredDm'
183+ let voidResult' = fmapCheap (\_ -> ()) result'
184+ let loweredDm' = ffor dm' $ mapPatch (Compose . (,) (True, voidResult'))
185+ return (result0, result')
186+
187+--------------------------------------------------------------------------------
188+-- Deprecated functionality
189+--------------------------------------------------------------------------------
190+
191+-- | Deprecated
192+instance TransControl.MonadTransControl (PostBuildT t) where
193+ type StT (PostBuildT t) a = TransControl.StT (ReaderT (Event t ())) a
194+ {-# INLINABLE liftWith #-}
195+ liftWith = TransControl.defaultLiftWith PostBuildT unPostBuildT
196+ {-# INLINABLE restoreT #-}
197+ restoreT = TransControl.defaultRestoreT PostBuildT
src/Reflex/PostBuild/Class.hsnew file+41
@@ -0,0 +1,41 @@
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.hsnew file+223
@@ -0,0 +1,223 @@
1+{-# LANGUAGE EmptyDataDecls #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE InstanceSigs #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE StandaloneDeriving #-}
9+{-# LANGUAGE TypeFamilies #-}
10+{-# LANGUAGE UndecidableInstances #-}
11+{-# LANGUAGE PolyKinds #-}
12+{-# LANGUAGE RankNTypes #-}
13+-- |
14+-- Module:
15+-- Reflex.Profiled
16+-- Description:
17+-- This module contains an instance of the 'Reflex' class that provides
18+-- profiling/cost-center information.
19+module Reflex.Profiled where
20+
21+import Control.Monad
22+import Control.Monad.Exception
23+import Control.Monad.Fix
24+import Control.Monad.Primitive
25+import Control.Monad.Reader
26+import Control.Monad.Ref
27+import Control.Monad.State.Strict (StateT, execStateT, modify)
28+import Data.Coerce
29+import Data.Dependent.Map (DMap, GCompare)
30+import Data.FastMutableIntMap
31+import Data.IORef
32+import Data.List
33+import Data.Map (Map)
34+import qualified Data.Map.Strict as Map
35+import Data.Monoid ((<>))
36+import Data.Ord
37+import Data.Profunctor.Unsafe ((#.))
38+import qualified Data.Semigroup as S
39+import Data.Type.Coercion
40+import Foreign.Ptr
41+import GHC.Foreign
42+import GHC.IO.Encoding
43+import GHC.Stack
44+import Reflex.Class
45+import Reflex.Host.Class
46+import Reflex.PerformEvent.Class
47+
48+import System.IO.Unsafe
49+import Unsafe.Coerce
50+
51+data ProfiledTimeline t
52+
53+{-# NOINLINE profilingData #-}
54+profilingData :: IORef (Map (Ptr CostCentreStack) Int)
55+profilingData = unsafePerformIO $ newIORef Map.empty
56+
57+data CostCentreTree = CostCentreTree
58+ { _costCentreTree_ownEntries :: !Int
59+ , _costCentreTree_cumulativeEntries :: !Int
60+ , _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
61+ }
62+ deriving (Show, Eq, Ord)
63+
64+instance S.Semigroup CostCentreTree where
65+ (CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
66+ CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
67+
68+instance Monoid CostCentreTree where
69+ mempty = CostCentreTree 0 0 mempty
70+ mappend = (S.<>)
71+
72+getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
73+getCostCentreStack = go []
74+ where go l ccs = if ccs == nullPtr
75+ then return l
76+ else do
77+ cc <- ccsCC ccs
78+ parent <- ccsParent ccs
79+ go (cc : l) parent
80+
81+toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
82+toCostCentreTree ccs n =
83+ foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty)
84+ <$> getCostCentreStack ccs
85+
86+getCostCentreTree :: IO CostCentreTree
87+getCostCentreTree = do
88+ vals <- readIORef profilingData
89+ mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
90+
91+formatCostCentreTree :: CostCentreTree -> IO String
92+formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
93+ where go :: Int -> CostCentreTree -> StateT [String] IO ()
94+ go depth cct = do
95+ let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
96+ indent = mconcat $ replicate depth " "
97+ forM_ children $ \(cc, childCct) -> do
98+ lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
99+ mdl <- liftIO $ peekCString utf8 =<< ccModule cc
100+ loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
101+ let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
102+ modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
103+ go (succ depth) childCct
104+
105+showProfilingData :: IO ()
106+showProfilingData = do
107+ putStr =<< formatCostCentreTree =<< getCostCentreTree
108+
109+writeProfilingData :: FilePath -> IO ()
110+writeProfilingData p = do
111+ writeFile p =<< formatCostCentreTree =<< getCostCentreTree
112+
113+newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
114+ deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
115+
116+profileEvent :: Reflex t => Event t a -> Event t a
117+profileEvent e = unsafePerformIO $ do
118+ stack <- getCurrentCCS e
119+ let f x = unsafePerformIO $ do
120+ modifyIORef' profilingData $ Map.insertWith (+) stack 1
121+ return $ return $ Just x
122+ return $ pushCheap f e
123+
124+--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
125+
126+instance Reflex t => Reflex (ProfiledTimeline t) where
127+ newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
128+ newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
129+ newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
130+ newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
131+ type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
132+ type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
133+ never = Event_Profiled never
134+ constant = Behavior_Profiled . constant
135+ push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
136+ pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
137+ pull = Behavior_Profiled . pull . coerce
138+ fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)
139+ mergeG :: forall (k :: z -> *) q v. GCompare k
140+ => (forall a. q a -> Event (ProfiledTimeline t) (v a))
141+ -> DMap k q -> Event (ProfiledTimeline t) (DMap k v)
142+ mergeG nt = Event_Profiled #. mergeG (coerce nt)
143+ switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
144+ coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
145+ current (Dynamic_Profiled d) = coerce $ current d
146+ updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
147+ unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
148+ unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
149+ mergeIncrementalG nt = (Event_Profiled . coerce) #. mergeIncrementalG nt
150+ mergeIncrementalWithMoveG nt = (Event_Profiled . coerce) #. mergeIncrementalWithMoveG nt
151+ currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
152+ updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
153+ incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
154+ behaviorCoercion (c :: Coercion a b) = case behaviorCoercion c :: Coercion (Behavior t a) (Behavior t b) of
155+ Coercion -> unsafeCoerce (Coercion :: Coercion (Behavior (ProfiledTimeline t) a) (Behavior (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
156+ eventCoercion (c :: Coercion a b) = case eventCoercion c :: Coercion (Event t a) (Event t b) of
157+ Coercion -> unsafeCoerce (Coercion :: Coercion (Event (ProfiledTimeline t) a) (Event (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
158+ dynamicCoercion (c :: Coercion a b) = case dynamicCoercion c :: Coercion (Dynamic t a) (Dynamic t b) of
159+ Coercion -> unsafeCoerce (Coercion :: Coercion (Dynamic (ProfiledTimeline t) a) (Dynamic (ProfiledTimeline t) a)) --TODO: Figure out how to make this typecheck without the unsafeCoerce
160+ mergeIntIncremental = Event_Profiled . mergeIntIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchIntMap (Event (ProfiledTimeline t) a)) -> Incremental t (PatchIntMap (Event t a)))
161+ fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
162+
163+deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
164+deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
165+deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
166+
167+instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
168+ hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
169+ holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
170+ holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
171+ buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
172+ headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
173+
174+instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
175+ sample (Behavior_Profiled b) = ProfiledM $ sample b
176+
177+instance MonadTrans ProfiledM where
178+ lift = ProfiledM
179+
180+instance MonadIO m => MonadIO (ProfiledM m) where
181+ liftIO = lift . liftIO
182+
183+instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
184+ type Performable (ProfiledM m) = Performable m
185+ performEvent_ = lift . performEvent_ . coerce
186+ performEvent = lift . fmap coerce . performEvent . coerce
187+
188+instance MonadRef m => MonadRef (ProfiledM m) where
189+ type Ref (ProfiledM m) = Ref m
190+ newRef = lift . newRef
191+ readRef = lift . readRef
192+ writeRef r = lift . writeRef r
193+
194+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
195+ newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
196+ newFanEventWithTrigger f = do
197+ es <- lift $ newFanEventWithTrigger f
198+ return $ EventSelector $ \k -> coerce $ select es k
199+
200+instance MonadReader r m => MonadReader r (ProfiledM m) where
201+ ask = lift ask
202+ local f (ProfiledM a) = ProfiledM $ local f a
203+ reader = lift . reader
204+
205+instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
206+ type EventTrigger (ProfiledTimeline t) = EventTrigger t
207+ type EventHandle (ProfiledTimeline t) = EventHandle t
208+ type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
209+
210+instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
211+ subscribeEvent = lift . subscribeEvent . coerce
212+
213+instance PrimMonad m => PrimMonad (ProfiledM m) where
214+ type PrimState (ProfiledM m) = PrimState m
215+ primitive = lift . primitive
216+
217+instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
218+ type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
219+ fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
220+ runHostFrame = lift . runHostFrame . coerce
221+
222+instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
223+ readEvent = lift . fmap coerce . readEvent
src/Reflex/Pure.hsnew file+210
@@ -0,0 +1,210 @@
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+ -- fanG :: GCompare k => Event (Pure t) (DMap k v) -> EventSelectorG (Pure t) k v
92+ fanG e = EventSelectorG $ \k -> Event $ \t -> unEvent e t >>= DMap.lookup k
93+
94+ switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a
95+ switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
96+
97+ coincidence :: Event (Pure t) (Event (Pure t) a) -> Event (Pure t) a
98+ coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
99+
100+ current :: Dynamic (Pure t) a -> Behavior (Pure t) a
101+ current d = Behavior $ \t -> fst $ unDynamic d t
102+
103+ updated :: Dynamic (Pure t) a -> Event (Pure t) a
104+ updated d = Event $ \t -> snd $ unDynamic d t
105+
106+ unsafeBuildDynamic :: PullM (Pure t) a -> Event (Pure t) a -> Dynamic (Pure t) a
107+ unsafeBuildDynamic readV0 v' = Dynamic $ \t -> (readV0 t, unEvent v' t)
108+
109+ -- See UNUSED_CONSTRAINT, above.
110+
111+ --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p
112+ --a) -> Incremental (Pure t) p a
113+ unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)
114+
115+ mergeIncrementalG = mergeIncrementalImpl
116+ mergeIncrementalWithMoveG = mergeIncrementalImpl
117+
118+ currentIncremental i = Behavior $ \t -> fst $ unIncremental i t
119+
120+ updatedIncremental i = Event $ \t -> snd $ unIncremental i t
121+
122+ incrementalToDynamic i = Dynamic $ \t ->
123+ let (old, mPatch) = unIncremental i t
124+ e = case mPatch of
125+ Nothing -> Nothing
126+ Just patch -> apply patch old
127+ in (old, e)
128+ behaviorCoercion Coercion = Coercion
129+ eventCoercion Coercion = Coercion
130+ dynamicCoercion Coercion = Coercion
131+
132+ fanInt e = EventSelectorInt $ \k -> Event $ \t -> unEvent e t >>= IntMap.lookup k
133+
134+ mergeIntIncremental = mergeIntIncrementalImpl
135+
136+mergeIncrementalImpl :: (PatchTarget p ~ DMap k q, GCompare k)
137+ => (forall a. q a -> Event (Pure t) (v a))
138+ -> Incremental (Pure t) p -> Event (Pure t) (DMap k v)
139+mergeIncrementalImpl nt i = Event $ \t ->
140+ let results = DMap.mapMaybeWithKey (\_ q -> case nt q of Event e -> e t) $ fst $ unIncremental i t
141+ in if DMap.null results
142+ then Nothing
143+ else Just results
144+
145+mergeIntIncrementalImpl :: (PatchTarget p ~ IntMap (Event (Pure t) a)) => Incremental (Pure t) p -> Event (Pure t) (IntMap a)
146+mergeIntIncrementalImpl i = Event $ \t ->
147+ let results = IntMap.mapMaybeWithKey (\_ (Event e) -> e t) $ fst $ unIncremental i t
148+ in if IntMap.null results
149+ then Nothing
150+ else Just results
151+
152+instance Functor (Dynamic (Pure t)) where
153+ fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t
154+ in (f cur, fmap f upd)
155+
156+instance Applicative (Dynamic (Pure t)) where
157+ pure a = Dynamic $ \_ -> (a, Nothing)
158+ (<*>) = ap
159+
160+instance Monad (Dynamic (Pure t)) where
161+ return = pure
162+ (x :: Dynamic (Pure t) a) >>= (f :: a -> Dynamic (Pure t) b) = Dynamic $ \t ->
163+ let (curX :: a, updX :: Maybe a) = unDynamic x t
164+ (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t
165+ (updInner :: Maybe b, updBoth :: Maybe b) = case updX of
166+ Nothing -> (Nothing, Nothing)
167+ Just nextX -> let (c, u) = unDynamic (f nextX) t
168+ in (Just c, u)
169+ in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])
170+
171+instance MonadSample (Pure t) ((->) t) where
172+
173+ sample :: Behavior (Pure t) a -> (t -> a)
174+ sample = unBehavior
175+
176+instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
177+
178+ hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a
179+ hold initialValue e initialTime = Behavior f
180+ where f = memo $ \sampleTime ->
181+ -- Really, the sampleTime should never be prior to the initialTime,
182+ -- because that would mean the Behavior is being sampled before
183+ -- being created.
184+ if sampleTime <= initialTime
185+ then initialValue
186+ else let lastTime = pred sampleTime
187+ in fromMaybe (f lastTime) $ unEvent e lastTime
188+
189+ holdDyn v0 = buildDynamic (return v0)
190+
191+ buildDynamic :: (t -> a) -> Event (Pure t) a -> t -> Dynamic (Pure t) a
192+ buildDynamic initialValue e initialTime =
193+ let Behavior f = hold (initialValue initialTime) e initialTime
194+ in Dynamic $ \t -> (f t, unEvent e t)
195+
196+ holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p
197+ holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)
198+ where f = memo $ \sampleTime ->
199+ -- Really, the sampleTime should never be prior to the initialTime,
200+ -- because that would mean the Behavior is being sampled before
201+ -- being created.
202+ if sampleTime <= initialTime
203+ then initialValue
204+ else let lastTime = pred sampleTime
205+ lastValue = f lastTime
206+ in case unEvent e lastTime of
207+ Nothing -> lastValue
208+ Just x -> fromMaybe lastValue $ apply x lastValue
209+
210+ headE = slowHeadE
src/Reflex/Query/Base.hsnew file+335
@@ -0,0 +1,335 @@
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.hsnew file+118
@@ -0,0 +1,118 @@
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.hsnew file+537
@@ -0,0 +1,537 @@
1+-- | This module provides 'RequesterT', the standard implementation of
2+-- 'Requester'.
3+{-# LANGUAGE AllowAmbiguousTypes #-}
4+{-# LANGUAGE CPP #-}
5+{-# LANGUAGE EmptyDataDecls #-}
6+{-# LANGUAGE ExistentialQuantification #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE GADTs #-}
9+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10+{-# LANGUAGE MultiParamTypeClasses #-}
11+{-# LANGUAGE Rank2Types #-}
12+{-# LANGUAGE RecursiveDo #-}
13+{-# LANGUAGE ScopedTypeVariables #-}
14+{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE TypeFamilies #-}
16+{-# LANGUAGE TypeOperators #-}
17+{-# LANGUAGE UndecidableInstances #-}
18+#ifdef USE_REFLEX_OPTIMIZER
19+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20+#endif
21+module Reflex.Requester.Base
22+ ( RequesterT (..)
23+ , runRequesterT
24+ , withRequesterT
25+ , runWithReplaceRequesterTWith
26+ , traverseIntMapWithKeyWithAdjustRequesterTWith
27+ , traverseDMapWithKeyWithAdjustRequesterTWith
28+ , RequesterData
29+ , RequesterDataKey
30+ , traverseRequesterData
31+ , forRequesterData
32+ , requesterDataToList
33+ , singletonRequesterData
34+ , matchResponsesWithRequests
35+ , multiEntry
36+ , unMultiEntry
37+ , requesting'
38+ ) where
39+
40+import Reflex.Class
41+import Reflex.Adjustable.Class
42+import Reflex.Dynamic
43+import Reflex.Host.Class
44+import Reflex.PerformEvent.Class
45+import Reflex.PostBuild.Class
46+import Reflex.Requester.Class
47+import Reflex.TriggerEvent.Class
48+
49+import Control.Applicative (liftA2)
50+import Control.Monad.Exception
51+import Control.Monad.Identity
52+import Control.Monad.Primitive
53+import Control.Monad.Reader
54+import Control.Monad.Ref
55+import Control.Monad.State.Strict
56+import Data.Bits
57+import Data.Coerce
58+import Data.Dependent.Map (DMap, DSum (..))
59+import qualified Data.Dependent.Map as DMap
60+import Data.Functor.Compose
61+import Data.Functor.Misc
62+import Data.IntMap.Strict (IntMap)
63+import qualified Data.IntMap.Strict as IntMap
64+import Data.Map (Map)
65+import qualified Data.Map as Map
66+import Data.Monoid ((<>))
67+import Data.Proxy
68+import qualified Data.Semigroup as S
69+import Data.Some (Some(Some))
70+import Data.Type.Equality
71+import Data.Unique.Tag
72+
73+import GHC.Exts (Any)
74+import Unsafe.Coerce
75+
76+--TODO: Make this module type-safe
77+
78+newtype TagMap (f :: * -> *) = TagMap (IntMap Any)
79+
80+newtype RequesterData f = RequesterData (TagMap (Entry f))
81+
82+data RequesterDataKey a where
83+ RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a
84+ RequesterDataKey_Multi :: {-# UNPACK #-} !(MyTag Multi) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a --TODO: Don't put a second Int here (or in the other Multis); use a single Int instead
85+ RequesterDataKey_Multi2 :: {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
86+ RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
87+
88+singletonRequesterData :: RequesterDataKey a -> f a -> RequesterData f
89+singletonRequesterData rdk v = case rdk of
90+ RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v
91+ RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v
92+ RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
93+ RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
94+
95+requesterDataToList :: RequesterData f -> [DSum RequesterDataKey f]
96+requesterDataToList (RequesterData m) = do
97+ k :=> Entry e <- tagMapToList m
98+ case myKeyType k of
99+ MyTagType_Single -> return $ RequesterDataKey_Single k :=> e
100+ MyTagType_Multi -> do
101+ (k', e') <- IntMap.toList e
102+ k'' :=> e'' <- requesterDataToList e'
103+ return $ RequesterDataKey_Multi k k' k'' :=> e''
104+ MyTagType_Multi2 -> do
105+ (k', e') <- Map.toList e
106+ (k'', e'') <- IntMap.toList e'
107+ k''' :=> e''' <- requesterDataToList e''
108+ return $ RequesterDataKey_Multi2 k k' k'' k''' :=> e'''
109+ MyTagType_Multi3 -> do
110+ (k', e') <- IntMap.toList e
111+ (k'', e'') <- IntMap.toList e'
112+ k''' :=> e''' <- requesterDataToList e''
113+ return $ RequesterDataKey_Multi3 k k' k'' k''' :=> e'''
114+
115+singletonTagMap :: forall f a. MyTag a -> f a -> TagMap f
116+singletonTagMap (MyTag k) v = TagMap $ IntMap.singleton k $ (unsafeCoerce :: f a -> Any) v
117+
118+tagMapToList :: forall f. TagMap f -> [DSum MyTag f]
119+tagMapToList (TagMap m) = f <$> IntMap.toList m
120+ where f :: (Int, Any) -> DSum MyTag f
121+ f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v
122+
123+traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g)
124+traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m
125+ where
126+ g :: Int -> Any -> t Any
127+ g k v = (unsafeCoerce :: g a -> Any) <$> f (MyTag k) ((unsafeCoerce :: Any -> f a) v)
128+
129+-- | Runs in reverse to accommodate for the fact that we accumulate it in reverse
130+traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response)
131+traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order
132+ where go :: forall x. MyTag x -> Entry request x -> m (Entry response x)
133+ go k (Entry request) = Entry <$> case myKeyType k of
134+ MyTagType_Single -> f request
135+ MyTagType_Multi -> traverse (traverseRequesterData f) request
136+ MyTagType_Multi2 -> traverse (traverse (traverseRequesterData f)) request
137+ MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request
138+
139+-- | 'traverseRequesterData' with its arguments flipped
140+forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response)
141+forRequesterData r f = traverseRequesterData f r
142+
143+data MyTagType :: * -> * where
144+ MyTagType_Single :: MyTagType (Single a)
145+ MyTagType_Multi :: MyTagType Multi
146+ MyTagType_Multi2 :: MyTagType (Multi2 k)
147+ MyTagType_Multi3 :: MyTagType Multi3
148+
149+myKeyType :: MyTag x -> MyTagType x
150+myKeyType (MyTag k) = case k .&. 0x3 of
151+ 0x0 -> unsafeCoerce MyTagType_Single
152+ 0x1 -> unsafeCoerce MyTagType_Multi
153+ 0x2 -> unsafeCoerce MyTagType_Multi2
154+ 0x3 -> unsafeCoerce MyTagType_Multi3
155+ t -> error $ "Reflex.Requester.Base.myKeyType: no such key type" <> show t
156+
157+data Single a
158+data Multi
159+data Multi2 (k :: * -> *)
160+data Multi3
161+
162+class MyTagTypeOffset x where
163+ myTagTypeOffset :: proxy x -> Int
164+
165+instance MyTagTypeOffset (Single a) where
166+ myTagTypeOffset _ = 0x0
167+
168+instance MyTagTypeOffset Multi where
169+ myTagTypeOffset _ = 0x1
170+
171+instance MyTagTypeOffset (Multi2 k) where
172+ myTagTypeOffset _ = 0x2
173+
174+instance MyTagTypeOffset Multi3 where
175+ myTagTypeOffset _ = 0x3
176+
177+type family EntryContents request a where
178+ EntryContents request (Single a) = request a
179+ EntryContents request Multi = IntMap (RequesterData request)
180+ EntryContents request (Multi2 k) = Map (Some k) (IntMap (RequesterData request))
181+ EntryContents request Multi3 = IntMap (IntMap (RequesterData request))
182+
183+newtype Entry request x = Entry { unEntry :: EntryContents request x }
184+
185+{-# INLINE singleEntry #-}
186+singleEntry :: f a -> Entry f (Single a)
187+singleEntry = Entry
188+
189+{-# INLINE multiEntry #-}
190+multiEntry :: IntMap (RequesterData f) -> Entry f Multi
191+multiEntry = Entry
192+
193+{-# INLINE unMultiEntry #-}
194+unMultiEntry :: Entry f Multi -> IntMap (RequesterData f)
195+unMultiEntry = unEntry
196+
197+-- | We use a hack here to pretend we have x ~ request a; we don't want to use a GADT, because GADTs (even with zero-size existential contexts) can't be newtypes
198+-- WARNING: This type should never be exposed. In particular, this is extremely unsound if a MyTag from one run of runRequesterT is ever compared against a MyTag from another
199+newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum)
200+
201+newtype MyTagWrap (f :: * -> *) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum)
202+
203+{-# INLINE castMyTagWrap #-}
204+castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x)
205+castMyTagWrap = coerce
206+
207+instance GEq MyTag where
208+ (MyTag a) `geq` (MyTag b) =
209+ if a == b
210+ then Just $ unsafeCoerce Refl
211+ else Nothing
212+
213+instance GCompare MyTag where
214+ (MyTag a) `gcompare` (MyTag b) =
215+ case a `compare` b of
216+ LT -> GLT
217+ EQ -> unsafeCoerce GEQ
218+ GT -> GGT
219+
220+instance GEq (MyTagWrap f) where
221+ (MyTagWrap a) `geq` (MyTagWrap b) =
222+ if a == b
223+ then Just $ unsafeCoerce Refl
224+ else Nothing
225+
226+instance GCompare (MyTagWrap f) where
227+ (MyTagWrap a) `gcompare` (MyTagWrap b) =
228+ case a `compare` b of
229+ LT -> GLT
230+ EQ -> unsafeCoerce GEQ
231+ GT -> GGT
232+
233+data RequesterState t (request :: * -> *) = RequesterState
234+ { _requesterState_nextMyTag :: {-# UNPACK #-} !Int -- Starts at -4 and goes down by 4 each time, to accommodate two 'type' bits at the bottom
235+ , _requesterState_requests :: ![(Int, Event t Any)]
236+ }
237+
238+-- | A basic implementation of 'Requester'.
239+newtype RequesterT t request (response :: * -> *) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a }
240+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
241+-- MonadAsyncException can't be derived on ghc-8.0.1; we use base-4.9.1 as a proxy for ghc-8.0.2
242+#if MIN_VERSION_base(4,9,1)
243+ , MonadAsyncException
244+#endif
245+ )
246+
247+deriving instance MonadSample t m => MonadSample t (RequesterT t request response m)
248+deriving instance MonadHold t m => MonadHold t (RequesterT t request response m)
249+deriving instance PostBuild t m => PostBuild t (RequesterT t request response m)
250+deriving instance TriggerEvent t m => TriggerEvent t (RequesterT t request response m)
251+
252+instance PrimMonad m => PrimMonad (RequesterT t request response m) where
253+ type PrimState (RequesterT t request response m) = PrimState m
254+ primitive = lift . primitive
255+
256+-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
257+instance (Monoid a, Monad m) => Monoid (RequesterT t request response m a) where
258+ mempty = pure mempty
259+ mappend = liftA2 mappend
260+
261+instance (S.Semigroup a, Monad m) => S.Semigroup (RequesterT t request response m a) where
262+ (<>) = liftA2 (S.<>)
263+
264+
265+-- | Run a 'RequesterT' action. The resulting 'Event' will fire whenever
266+-- requests are made, and responses should be provided in the input 'Event'.
267+-- The 'Tag' keys will be used to return the responses to the same place the
268+-- requests were issued.
269+runRequesterT :: (Reflex t, Monad m)
270+ => RequesterT t request response m a
271+ -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse
272+ -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild
273+runRequesterT (RequesterT a) responses = do
274+ (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $
275+ coerceEvent responses
276+ return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s)
277+
278+-- | Map a function over the request and response of a 'RequesterT'
279+withRequesterT
280+ :: (Reflex t, MonadFix m)
281+ => (forall x. req x -> req' x) -- ^ The function to map over the request
282+ -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response
283+ -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed
284+ -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT'
285+withRequesterT freq frsp child = do
286+ rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp'
287+ (a, req) <- lift $ runRequesterT child rsp
288+ rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $
289+ fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req
290+ return a
291+
292+instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where
293+ type Request (RequesterT t request response m) = request
294+ type Response (RequesterT t request response m) = response
295+ requesting = fmap coerceEvent . responseFromTag . castMyTagWrap <=< tagRequest . (coerceEvent :: Event t (request a) -> Event t (Entry request (Single a)))
296+ requesting_ = void . tagRequest . fmapCheap singleEntry
297+
298+{-# INLINE tagRequest #-}
299+tagRequest :: forall m x t request response. (Monad m, MyTagTypeOffset x) => Event t (Entry request x) -> RequesterT t request response m (MyTagWrap request (Entry request x))
300+tagRequest req = do
301+ old <- RequesterT get
302+ let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x)
303+ t = MyTagWrap n
304+ RequesterT $ put $ RequesterState
305+ { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4
306+ , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old
307+ }
308+ return t
309+
310+{-# INLINE responseFromTag #-}
311+responseFromTag :: Monad m => MyTagWrap response (Entry response x) -> RequesterT t request response m (Event t (Entry response x))
312+responseFromTag (MyTagWrap t) = do
313+ responses :: EventSelectorInt t Any <- RequesterT ask
314+ return $ (unsafeCoerce :: Event t Any -> Event t (Entry response x)) $ selectInt responses t
315+
316+instance MonadTrans (RequesterT t request response) where
317+ lift = RequesterT . lift . lift
318+
319+instance PerformEvent t m => PerformEvent t (RequesterT t request response m) where
320+ type Performable (RequesterT t request response m) = Performable m
321+ performEvent_ = lift . performEvent_
322+ performEvent = lift . performEvent
323+
324+instance MonadRef m => MonadRef (RequesterT t request response m) where
325+ type Ref (RequesterT t request response m) = Ref m
326+ newRef = lift . newRef
327+ readRef = lift . readRef
328+ writeRef r = lift . writeRef r
329+
330+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequesterT t request response m) where
331+ newEventWithTrigger = lift . newEventWithTrigger
332+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
333+
334+instance MonadReader r m => MonadReader r (RequesterT t request response m) where
335+ ask = lift ask
336+ local f (RequesterT a) = RequesterT $ mapStateT (mapReaderT $ local f) a
337+ reader = lift . reader
338+
339+instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where
340+ runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
341+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental
342+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
343+ traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental
344+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove
345+
346+requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x))
347+requesting' = responseFromTag . castMyTagWrap <=< tagRequest
348+
349+{-# INLINABLE runWithReplaceRequesterTWith #-}
350+runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m
351+ , MonadFix m
352+ )
353+ => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))
354+ -> RequesterT t request response m a
355+ -> Event t (RequesterT t request response m b)
356+ -> RequesterT t request response m (a, Event t b)
357+runWithReplaceRequesterTWith f a0 a' = do
358+ rec na' <- numberOccurrencesFrom 1 a'
359+ responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here
360+ let responses' = fanInt responses
361+ ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na'
362+ requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v'
363+ return (result0, fmapCheap (fst . snd) v')
364+
365+{-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-}
366+traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p.
367+ ( Reflex t
368+ , MonadHold t m
369+ , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))
370+ , Patch (p (Event t (IntMap (RequesterData request))))
371+ , Functor p
372+ , MonadFix m
373+ )
374+ => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))
375+ -> IntMap (IntMap.Key, v)
376+ -> Event t (p (IntMap.Key, v))
377+ -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))
378+ )
379+ -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))
380+ -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))
381+ -> (IntMap.Key -> v -> RequesterT t request response m v')
382+ -> IntMap v
383+ -> Event t (p v)
384+ -> RequesterT t request response m (IntMap v', Event t (p v'))
385+traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do
386+ rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
387+ let responses :: EventSelectorInt t (IntMap (RequesterData response))
388+ responses = fanInt $ fmapCheap unpack response
389+ unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response))
390+ unpack = unEntry
391+ pack :: IntMap (IntMap (RequesterData request)) -> Entry request Multi3
392+ pack = Entry
393+ f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v')
394+ f' k (n, v) = do
395+ (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ selectInt responses k --TODO: Instead of doing mapMaybeCheap, can we share a fanInt across all instances of a given key, or at least the ones that are adjacent in time?
396+ return (fmapCheap (IntMap.singleton n) myRequests, result)
397+ ndm' <- numberOccurrencesFrom 1 dm'
398+ (children0, children') <- base f' (fmap ((,) 0) dm0) $ fmap (\(n, dm) -> fmap ((,) n) dm) ndm' --TODO: Avoid this somehow, probably by adding some sort of per-cohort information passing to Adjustable
399+ let result0 = fmap snd children0
400+ result' = fforCheap children' $ fmap snd
401+ requests0 :: IntMap (Event t (IntMap (RequesterData request)))
402+ requests0 = fmap fst children0
403+ requests' :: Event t (p (Event t (IntMap (RequesterData request))))
404+ requests' = fforCheap children' $ fmap fst
405+ promptRequests :: Event t (IntMap (IntMap (RequesterData request)))
406+ promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
407+ requests <- holdIncremental requests0 requests'
408+ return (result0, result')
409+
410+{-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-}
411+traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'.
412+ ( GCompare k
413+ , Reflex t
414+ , MonadHold t m
415+ , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))
416+ , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))
417+ , MonadFix m
418+ )
419+ => (forall k' v1 v2. GCompare k'
420+ => (forall a. k' a -> v1 a -> m (v2 a))
421+ -> DMap k' v1
422+ -> Event t (p k' v1)
423+ -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))
424+ )
425+ -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)
426+ -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)
427+ -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)
428+ -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))
429+ -> (forall a. k a -> v a -> RequesterT t request response m (v' a))
430+ -> DMap k v
431+ -> Event t (p k v)
432+ -> RequesterT t request response m (DMap k v', Event t (p k v'))
433+traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do
434+ rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
435+ let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response)))
436+ responses = fanMap $ fmapCheap unpack response
437+ unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response))
438+ unpack = unEntry
439+ pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k)
440+ pack = Entry
441+ f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a)
442+ f' k (Compose (n, v)) = do
443+ (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some k))
444+ return $ Compose (fmapCheap (IntMap.singleton n) myRequests, result)
445+ ndm' <- numberOccurrencesFrom 1 dm'
446+ (children0, children') <- base f' (DMap.map (\v -> Compose (0, v)) dm0) $ fmap (\(n, dm) -> mapPatch (\v -> Compose (n, v)) dm) ndm'
447+ let result0 = DMap.map (snd . getCompose) children0
448+ result' = fforCheap children' $ mapPatch $ snd . getCompose
449+ requests0 :: Map (Some k) (Event t (IntMap (RequesterData request)))
450+ requests0 = weakenDMapWith (fst . getCompose) children0
451+ requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request))))
452+ requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
453+ promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request)))
454+ promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
455+ requests <- holdIncremental requests0 requests'
456+ return (result0, result')
457+
458+data Decoder rawResponse response =
459+ forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)
460+
461+-- | Matches incoming responses with previously-sent requests
462+-- and uses the provided request "decoder" function to process
463+-- incoming responses.
464+matchResponsesWithRequests
465+ :: forall t rawRequest rawResponse request response m.
466+ ( MonadFix m
467+ , MonadHold t m
468+ , Reflex t
469+ )
470+ => (forall a. request a -> (rawRequest, rawResponse -> response a))
471+ -- ^ Given a request (from 'Requester'), produces the wire format of the
472+ -- request and a function used to process the associated response
473+ -> Event t (RequesterData request)
474+ -- ^ The outgoing requests
475+ -> Event t (Int, rawResponse)
476+ -- ^ The incoming responses, tagged by an identifying key
477+ -> m ( Event t (Map Int rawRequest)
478+ , Event t (RequesterData response)
479+ )
480+ -- ^ A map of outgoing wire-format requests and an event of responses keyed
481+ -- by the 'RequesterData' key of the associated outgoing request
482+matchResponsesWithRequests f send recv = do
483+ rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing
484+ waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <-
485+ holdIncremental mempty $ leftmost
486+ [ fmap (\(_, outstanding, _) -> outstanding) outgoing
487+ , snd <$> incoming
488+ ]
489+ let outgoing = processOutgoing nextId send
490+ incoming = processIncoming waitingFor recv
491+ return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming)
492+ where
493+ -- Tags each outgoing request with an identifying integer key
494+ -- and returns the next available key, a map of response decoders
495+ -- for requests for which there are outstanding responses, and the
496+ -- raw requests to be sent out.
497+ processOutgoing
498+ :: Behavior t Int
499+ -- The next available key
500+ -> Event t (RequesterData request)
501+ -- The outgoing request
502+ -> Event t ( Int
503+ , PatchMap Int (Decoder rawResponse response)
504+ , Map Int rawRequest )
505+ -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests
506+ processOutgoing nextId out = flip pushAlways out $ \dm -> do
507+ oldNextId <- sample nextId
508+ let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do
509+ n <- get
510+ put $ succ n
511+ let (rawReq, rspF) = f v
512+ return (n, rawReq, Decoder k rspF)
513+ patchWaitingFor = PatchMap $ Map.fromList $
514+ (\(n, _, dec) -> (n, Just dec)) <$> result
515+ toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result
516+ return (newNextId, patchWaitingFor, toSend)
517+ -- Looks up the each incoming raw response in a map of response
518+ -- decoders and returns the decoded response and a patch that can
519+ -- be used to clear the ID of the consumed response out of the queue
520+ -- of expected responses.
521+ processIncoming
522+ :: Incremental t (PatchMap Int (Decoder rawResponse response))
523+ -- A map of outstanding expected responses
524+ -> Event t (Int, rawResponse)
525+ -- A incoming response paired with its identifying key
526+ -> Event t (RequesterData response, PatchMap Int v)
527+ -- The decoded response and a patch that clears the outstanding responses queue
528+ processIncoming waitingFor inc = flip push inc $ \(n, rawRsp) -> do
529+ wf <- sample $ currentIncremental waitingFor
530+ case Map.lookup n wf of
531+ Nothing -> return Nothing -- TODO How should lookup failures be handled here? They shouldn't ever happen..
532+ Just (Decoder k rspF) -> do
533+ let rsp = rspF rawRsp
534+ return $ Just
535+ ( singletonRequesterData k rsp
536+ , PatchMap $ Map.singleton n Nothing
537+ )
src/Reflex/Requester/Class.hsnew file+72
@@ -0,0 +1,72 @@
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.hsnew file+20
@@ -0,0 +1,20 @@
1+{-# LANGUAGE CPP #-}
2+-- |
3+-- Module:
4+-- Reflex.Spider
5+-- Description:
6+-- This module exports all of the user-facing functionality of the 'Spider' 'Reflex' engine
7+module Reflex.Spider
8+ ( Spider
9+ , SpiderTimeline
10+ , Global
11+ , SpiderHost
12+ , runSpiderHost
13+ , runSpiderHostForTimeline
14+ , newSpiderTimeline
15+ , withSpiderTimeline
16+ -- * Deprecated
17+ , SpiderEnv
18+ ) where
19+
20+import Reflex.Spider.Internal
src/Reflex/Spider/Internal.hsnew file+2681
@@ -0,0 +1,2681 @@
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 InstanceSigs #-}
21+
22+#ifdef USE_REFLEX_OPTIMIZER
23+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
24+#endif
25+{-# OPTIONS_GHC -Wunused-binds #-}
26+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
27+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
28+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
29+
30+#if MIN_VERSION_base(4,10,0)
31+import Control.Applicative (liftA2)
32+#endif
33+import Control.Concurrent
34+import Control.Exception
35+import Control.Monad hiding (forM, forM_, mapM, mapM_)
36+import Control.Monad.Exception
37+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
38+import Control.Monad.Primitive
39+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
40+import Control.Monad.Ref
41+import Data.Align
42+import Data.Coerce
43+import Data.Dependent.Map (DMap, DSum (..))
44+import qualified Data.Dependent.Map as DMap
45+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
46+import qualified Data.FastMutableIntMap as FastMutableIntMap
47+import Data.Foldable hiding (concat, elem, sequence_)
48+import Data.Functor.Constant
49+import Data.Functor.Misc
50+import Data.Functor.Product
51+import Data.GADT.Compare
52+import Data.IntMap.Strict (IntMap)
53+import qualified Data.IntMap.Strict as IntMap
54+import Data.IORef
55+import Data.Kind (Type)
56+import Data.Maybe hiding (mapMaybe)
57+import Data.Monoid ((<>))
58+import Data.Proxy
59+import Data.These
60+import Data.Traversable
61+import Data.Witherable (Filterable, mapMaybe)
62+import GHC.Exts
63+import GHC.IORef (IORef (..))
64+import GHC.Stack
65+import Reflex.FastWeak
66+import System.IO.Unsafe
67+import System.Mem.Weak
68+import Unsafe.Coerce
69+
70+#if defined(MIN_VERSION_semialign)
71+#if MIN_VERSION_these(0,8,0)
72+import Data.These.Combinators (justThese)
73+#endif
74+#endif
75+
76+#ifdef DEBUG_CYCLES
77+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
78+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
79+import qualified Data.List.NonEmpty as NonEmpty
80+import Data.Monoid (mempty)
81+import Data.Tree (Forest, Tree (..), drawForest)
82+#endif
83+
84+import Data.FastWeakBag (FastWeakBag)
85+import qualified Data.FastWeakBag as FastWeakBag
86+import Data.Reflection
87+import Data.Some (Some(Some))
88+import Data.Type.Coercion
89+import Data.Profunctor.Unsafe ((#.), (.#))
90+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
91+import qualified Data.WeakBag as WeakBag
92+import qualified Reflex.Class
93+import qualified Reflex.Class as R
94+import qualified Reflex.Host.Class
95+import Reflex.NotReady.Class
96+import Reflex.Patch
97+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
98+
99+#ifdef DEBUG_TRACE_EVENTS
100+import qualified Data.ByteString.Char8 as BS8
101+import System.IO (stderr)
102+#endif
103+
104+#ifdef DEBUG_TRACE_EVENTS
105+
106+withStackOneLine :: (BS8.ByteString -> a) -> a
107+withStackOneLine expr = unsafePerformIO $ do
108+ stack <- currentCallStack
109+ return (expr (BS8.pack (unwords (reverse stack))))
110+
111+#endif
112+
113+debugPropagate :: Bool
114+
115+debugInvalidateHeight :: Bool
116+
117+debugInvalidate :: Bool
118+
119+#ifdef DEBUG
120+
121+#define DEBUG_NODEIDS
122+
123+debugPropagate = True
124+
125+debugInvalidateHeight = False
126+
127+debugInvalidate = True
128+
129+class HasNodeId a where
130+ getNodeId :: a -> Int
131+
132+instance HasNodeId (Hold x p a) where
133+ getNodeId = holdNodeId
134+
135+instance HasNodeId (PushSubscribed x a b) where
136+ getNodeId = pushSubscribedNodeId
137+
138+instance HasNodeId (SwitchSubscribed x a) where
139+ getNodeId = switchSubscribedNodeId
140+
141+instance HasNodeId (FanSubscribed x a) where
142+ getNodeId = fanSubscribedNodeId
143+
144+instance HasNodeId (CoincidenceSubscribed x a) where
145+ getNodeId = coincidenceSubscribedNodeId
146+
147+instance HasNodeId (RootSubscribed x a) where
148+ getNodeId = rootSubscribedNodeId
149+
150+instance HasNodeId (Pull x a) where
151+ getNodeId = pullNodeId
152+
153+{-# INLINE showNodeId #-}
154+showNodeId :: HasNodeId a => a -> String
155+showNodeId = ("#"<>) . show . getNodeId
156+
157+showSubscriberType :: Subscriber x a -> String
158+showSubscriberType = \case
159+ SubscriberPush _ _ -> "SubscriberPush"
160+ SubscriberMerge _ _ -> "SubscriberMerge"
161+ SubscriberFan _ -> "SubscriberFan"
162+ SubscriberMergeChange _ -> "SubscriberMergeChange"
163+ SubscriberHold _ -> "SubscriberHold"
164+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
165+ SubscriberSwitch _ -> "SubscriberSwitch"
166+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
167+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
168+ SubscriberHandle -> "SubscriberHandle"
169+
170+showEventType :: Event x a -> String
171+showEventType = \case
172+ EventRoot _ _ -> "EventRoot"
173+ EventNever -> "EventNever"
174+ EventPush _ -> "EventPush"
175+ EventMerge _ -> "EventMerge"
176+ EventFan _ _ -> "EventFan"
177+ EventSwitch _ -> "EventSwitch"
178+ EventCoincidence _ -> "EventCoincidence"
179+ EventHold _ -> "EventHold"
180+ EventDyn _ -> "EventDyn"
181+ EventHoldIdentity _ -> "EventHoldIdentity"
182+ EventDynIdentity _ -> "EventDynIdentity"
183+
184+#else
185+
186+debugPropagate = False
187+
188+debugInvalidateHeight = False
189+
190+debugInvalidate = False
191+
192+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
193+{-# INLINE showNodeId #-}
194+showNodeId :: a -> String
195+showNodeId _ = ""
196+
197+#endif
198+
199+#ifdef DEBUG_NODEIDS
200+{-# NOINLINE nextNodeIdRef #-}
201+nextNodeIdRef :: IORef Int
202+nextNodeIdRef = unsafePerformIO $ newIORef 1
203+
204+newNodeId :: IO Int
205+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
206+#endif
207+
208+--------------------------------------------------------------------------------
209+-- EventSubscription
210+--------------------------------------------------------------------------------
211+
212+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
213+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
214+data EventSubscription x = EventSubscription
215+ { _eventSubscription_unsubscribe :: !(IO ())
216+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
217+ }
218+
219+unsubscribe :: EventSubscription x -> IO ()
220+unsubscribe (EventSubscription u _) = u
221+
222+--------------------------------------------------------------------------------
223+-- Event
224+--------------------------------------------------------------------------------
225+
226+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
227+
228+{-# INLINE subscribeAndRead #-}
229+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
230+subscribeAndRead = unEvent
231+
232+{-# RULES
233+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
234+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
235+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
236+ #-}
237+
238+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
239+-- caching; if the computation function is very cheap, this is (much) more
240+-- efficient than 'push'
241+{-# INLINE [1] pushCheap #-}
242+pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
243+pushCheap !f e = Event $ \sub -> do
244+ (subscription, occ) <- subscribeAndRead e $ sub
245+ { subscriberPropagate = \a -> do
246+ mb <- f a
247+ mapM_ (subscriberPropagate sub) mb
248+ }
249+ occ' <- join <$> mapM f occ
250+ return (subscription, occ')
251+
252+-- | A subscriber that never triggers other 'Event's
253+{-# INLINE terminalSubscriber #-}
254+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
255+terminalSubscriber p = Subscriber
256+ { subscriberPropagate = p
257+ , subscriberInvalidateHeight = \_ -> return ()
258+ , subscriberRecalculateHeight = \_ -> return ()
259+ }
260+
261+-- | Subscribe to an Event only for the duration of one occurrence
262+{-# INLINE subscribeAndReadHead #-}
263+subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
264+subscribeAndReadHead e sub = do
265+ subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
266+ (subscription, occ) <- subscribeAndRead e $ sub
267+ { subscriberPropagate = \a -> do
268+ liftIO $ unsubscribe =<< readIORef subscriptionRef
269+ subscriberPropagate sub a
270+ }
271+ liftIO $ case occ of
272+ Nothing -> writeIORef subscriptionRef $! subscription
273+ Just _ -> unsubscribe subscription
274+ return (subscription, occ)
275+
276+--TODO: Make this lazy in its input event
277+headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
278+headE originalE = do
279+ parent <- liftIO $ newIORef $ Just originalE
280+ defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
281+ let clearParent = liftIO $ writeIORef parent Nothing
282+ (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
283+ when (isJust occ) clearParent
284+ return $ Event $ \sub -> do
285+ liftIO (readIORef parent) >>= \case
286+ Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
287+ Just e -> subscribeAndReadHead e sub
288+
289+data CacheSubscribed x a
290+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
291+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
292+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
293+ }
294+
295+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
296+-- repeatedly
297+--
298+--TODO: Try a caching strategy where we subscribe directly to the parent when
299+--there's only one subscriber, and then build our own FastWeakBag only when a second
300+--subscriber joins
301+{-# NOINLINE [0] cacheEvent #-}
302+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
303+cacheEvent e =
304+#ifdef DEBUG_TRACE_EVENTS
305+ withStackOneLine $ \callSite -> Event $
306+#else
307+ Event $
308+#endif
309+ unsafePerformIO $ do
310+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
311+ <- newIORef emptyFastWeak
312+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
313+#ifdef DEBUG_TRACE_EVENTS
314+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
315+#endif
316+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
317+ Just subscribedTicket -> return subscribedTicket
318+ Nothing -> do
319+ subscribers <- liftIO FastWeakBag.empty
320+ occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
321+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
322+ { subscriberPropagate = \a -> do
323+ liftIO $ writeIORef occRef $ Just a
324+ scheduleClear occRef
325+ propagateFast a subscribers
326+ , subscriberInvalidateHeight = \old -> do
327+ FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
328+ , subscriberRecalculateHeight = \new -> do
329+ FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
330+ }
331+ when (isJust occ) $ do
332+ liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
333+ scheduleClear occRef
334+ let !subscribed = CacheSubscribed
335+ { _cacheSubscribed_subscribers = subscribers
336+ , _cacheSubscribed_parent = parentSub
337+ , _cacheSubscribed_occurrence = occRef
338+ }
339+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
340+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
341+ return subscribedTicket
342+ liftIO $ do
343+ subscribed <- getFastWeakTicketValue subscribedTicket
344+ ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
345+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
346+ let es = EventSubscription
347+ { _eventSubscription_unsubscribe = do
348+ FastWeakBag.remove ticket
349+ isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
350+ when isEmpty $ do
351+ writeIORef mSubscribedRef emptyFastWeak
352+ unsubscribe $ _cacheSubscribed_parent subscribed
353+ touch ticket
354+ touch subscribedTicket
355+ , _eventSubscription_subscribed = EventSubscribed
356+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
357+ , eventSubscribedRetained = toAny subscribedTicket
358+ }
359+ }
360+ return (es, occ)
361+
362+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
363+subscribe e s = fst <$> subscribeAndRead e s
364+
365+{-# INLINE wrap #-}
366+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
367+wrap tag getSpecificSubscribed sub = do
368+ (sln, subd, occ) <- getSpecificSubscribed sub
369+ let es = tag subd
370+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
371+
372+eventRoot :: GCompare k => k a -> Root x k -> Event x a
373+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
374+
375+eventNever :: Event x a
376+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
377+
378+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
379+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
380+
381+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
382+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
383+
384+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
385+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
386+
387+eventHold :: Hold x p -> Event x p
388+eventHold !h = Event $ subscribeHoldEvent h
389+
390+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
391+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
392+
393+{-# INLINE subscribeCoincidenceInner #-}
394+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
395+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
396+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
397+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
398+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
399+ let height = max innerHeight outerHeight
400+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
401+ return (innerOcc, height, innerSubd)
402+
403+--------------------------------------------------------------------------------
404+-- Subscriber
405+--------------------------------------------------------------------------------
406+
407+data Subscriber x a = Subscriber
408+ { subscriberPropagate :: !(a -> EventM x ())
409+ , subscriberInvalidateHeight :: !(Height -> IO ())
410+ , subscriberRecalculateHeight :: !(Height -> IO ())
411+ }
412+
413+--TODO: Move this comment to WeakBag
414+-- These function are constructor functions that are marked NOINLINE so they are
415+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
416+-- so any weak references that are attached to the constructors will have their
417+-- finalizer run. Using the opaque constructor, does not see the
418+-- constructor application, so it behaves like an IORef and cannot be fused away.
419+--
420+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
421+-- the weak pointer to it in some cases.
422+
423+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
424+newSubscriberHold h = return $ Subscriber
425+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
426+ , subscriberInvalidateHeight = \_ -> return ()
427+ , subscriberRecalculateHeight = \_ -> return ()
428+ }
429+
430+newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
431+newSubscriberFan subscribed = return $ Subscriber
432+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
433+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
434+ tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
435+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
436+ scheduleClear $ fanSubscribedOccurrence subscribed
437+ let f _ (Pair v subsubs) = do
438+ propagate v $ _fanSubscribedChildren_list subsubs
439+ return $ Constant ()
440+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
441+ return ()
442+ , subscriberInvalidateHeight = \old -> do
443+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
444+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
445+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
446+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
447+ , subscriberRecalculateHeight = \new -> do
448+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
449+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
450+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
451+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
452+ }
453+
454+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
455+newSubscriberSwitch subscribed = return $ Subscriber
456+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
457+ tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
458+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
459+ scheduleClear $ switchSubscribedOccurrence subscribed
460+ propagate a $ switchSubscribedSubscribers subscribed
461+ , subscriberInvalidateHeight = \_ -> do
462+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
463+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
464+ when (oldHeight /= invalidHeight) $ do
465+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
466+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
467+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
468+ , subscriberRecalculateHeight = \new -> do
469+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
470+ updateSwitchHeight new subscribed
471+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
472+ }
473+
474+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
475+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
476+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
477+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
478+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
479+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
480+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
481+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
482+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
483+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
484+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
485+ case occ of
486+ Nothing -> do
487+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
488+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
489+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
490+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
491+ Just o -> do -- Since it's already firing, no need to adjust height
492+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
493+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
494+ propagate o $ coincidenceSubscribedSubscribers subscribed
495+ , subscriberInvalidateHeight = \_ -> do
496+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
497+ invalidateCoincidenceHeight subscribed
498+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
499+ , subscriberRecalculateHeight = \_ -> do
500+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
501+ recalculateCoincidenceHeight subscribed
502+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
503+ }
504+
505+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
506+newSubscriberCoincidenceInner subscribed = return $ Subscriber
507+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
508+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
509+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
510+ case occ of
511+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
512+ Nothing -> do
513+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
514+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
515+ propagate a $ coincidenceSubscribedSubscribers subscribed
516+ , subscriberInvalidateHeight = \_ -> do
517+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
518+ invalidateCoincidenceHeight subscribed
519+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
520+ , subscriberRecalculateHeight = \_ -> do
521+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
522+ recalculateCoincidenceHeight subscribed
523+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
524+ }
525+
526+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
527+invalidateSubscriberHeight = flip subscriberInvalidateHeight
528+
529+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
530+recalculateSubscriberHeight = flip subscriberRecalculateHeight
531+
532+-- | Propagate everything at the current height
533+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
534+propagate a subscribers = withIncreasedDepth $ do
535+ -- 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
536+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
537+ WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
538+
539+-- | Propagate everything at the current height
540+propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
541+propagateFast a subscribers = withIncreasedDepth $ do
542+ -- 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
543+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
544+ FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
545+
546+--------------------------------------------------------------------------------
547+-- EventSubscribed
548+--------------------------------------------------------------------------------
549+
550+toAny :: a -> Any
551+toAny = unsafeCoerce
552+
553+data EventSubscribed x = EventSubscribed
554+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
555+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
556+#ifdef DEBUG_CYCLES
557+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
558+ , eventSubscribedHasOwnHeightRef :: !Bool
559+ , eventSubscribedWhoCreated :: !(IO [String])
560+#endif
561+ }
562+
563+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
564+eventSubscribedRoot !r = EventSubscribed
565+ { eventSubscribedHeightRef = zeroRef
566+ , eventSubscribedRetained = toAny r
567+#ifdef DEBUG_CYCLES
568+ , eventSubscribedGetParents = return []
569+ , eventSubscribedHasOwnHeightRef = False
570+ , eventSubscribedWhoCreated = return ["root"]
571+#endif
572+ }
573+
574+eventSubscribedNever :: EventSubscribed x
575+eventSubscribedNever = EventSubscribed
576+ { eventSubscribedHeightRef = zeroRef
577+ , eventSubscribedRetained = toAny ()
578+#ifdef DEBUG_CYCLES
579+ , eventSubscribedGetParents = return []
580+ , eventSubscribedHasOwnHeightRef = False
581+ , eventSubscribedWhoCreated = return ["never"]
582+#endif
583+ }
584+
585+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
586+eventSubscribedFan !subscribed = EventSubscribed
587+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
588+ , eventSubscribedRetained = toAny subscribed
589+#ifdef DEBUG_CYCLES
590+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
591+ , eventSubscribedHasOwnHeightRef = False
592+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
593+#endif
594+ }
595+
596+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
597+eventSubscribedSwitch !subscribed = EventSubscribed
598+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
599+ , eventSubscribedRetained = toAny subscribed
600+#ifdef DEBUG_CYCLES
601+ , eventSubscribedGetParents = do
602+ s <- readIORef $ switchSubscribedCurrentParent subscribed
603+ return [Some $ _eventSubscription_subscribed s]
604+ , eventSubscribedHasOwnHeightRef = True
605+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
606+#endif
607+ }
608+
609+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
610+eventSubscribedCoincidence !subscribed = EventSubscribed
611+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
612+ , eventSubscribedRetained = toAny subscribed
613+#ifdef DEBUG_CYCLES
614+ , eventSubscribedGetParents = do
615+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
616+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
617+ innerParents = maybeToList $ fmap Some innerSubscription
618+ return $ outerParent : innerParents
619+ , eventSubscribedHasOwnHeightRef = True
620+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
621+#endif
622+ }
623+
624+getEventSubscribedHeight :: EventSubscribed x -> IO Height
625+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
626+
627+#ifdef DEBUG_CYCLES
628+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
629+whoCreatedEventSubscribed = eventSubscribedWhoCreated
630+
631+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
632+walkInvalidHeightParents s0 = do
633+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
634+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
635+ when (h == invalidHeight) $ do
636+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
637+ modify (Some s :)
638+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
639+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
640+ return subscribers
641+#endif
642+
643+{-# INLINE subscribeHoldEvent #-}
644+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
645+subscribeHoldEvent = subscribeAndRead . holdEvent
646+
647+--------------------------------------------------------------------------------
648+-- Behavior
649+--------------------------------------------------------------------------------
650+
651+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
652+
653+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
654+behaviorHold !h = Behavior $ readHoldTracked h
655+
656+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
657+behaviorHoldIdentity = behaviorHold
658+
659+behaviorConst :: a -> Behavior x a
660+behaviorConst !a = Behavior $ return a
661+
662+behaviorPull :: Pull x a -> Behavior x a
663+behaviorPull !p = Behavior $ do
664+ val <- liftIO $ readIORef $ pullValue p
665+ case val of
666+ Just subscribed -> do
667+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
668+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
669+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
670+ return $ pullSubscribedValue subscribed
671+ Nothing -> do
672+ i <- liftIO $ newInvalidatorPull p
673+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
674+ parentsRef <- liftIO $ newIORef []
675+ holdInits <- askBehaviorHoldInits
676+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
677+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
678+ parents <- liftIO $ readIORef parentsRef
679+ let subscribed = PullSubscribed
680+ { pullSubscribedValue = a
681+ , pullSubscribedInvalidators = invsRef
682+ , pullSubscribedOwnInvalidator = i
683+ , pullSubscribedParents = parents
684+ }
685+ liftIO $ writeIORef (pullValue p) $ Just subscribed
686+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
687+ return a
688+
689+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
690+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
691+
692+{-# INLINE readHoldTracked #-}
693+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
694+readHoldTracked h = do
695+ result <- liftIO $ readIORef $ holdValue h
696+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
697+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
698+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
699+ return result
700+
701+{-# INLINABLE readBehaviorUntracked #-}
702+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
703+readBehaviorUntracked b = do
704+ holdInits <- getDeferralQueue
705+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
706+
707+--------------------------------------------------------------------------------
708+-- Dynamic
709+--------------------------------------------------------------------------------
710+
711+data Dynamic x p = Dynamic
712+ { dynamicCurrent :: !(Behavior x (PatchTarget p))
713+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
714+ }
715+
716+dynamicHold :: Hold x p -> Dynamic x p
717+dynamicHold !h = Dynamic
718+ { dynamicCurrent = behaviorHold h
719+ , dynamicUpdated = eventHold h
720+ }
721+
722+dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
723+dynamicHoldIdentity = dynamicHold
724+
725+dynamicConst :: PatchTarget p -> Dynamic x p
726+dynamicConst !a = Dynamic
727+ { dynamicCurrent = behaviorConst a
728+ , dynamicUpdated = eventNever
729+ }
730+
731+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
732+dynamicDyn !d = Dynamic
733+ { dynamicCurrent = behaviorDyn d
734+ , dynamicUpdated = eventDyn d
735+ }
736+
737+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
738+dynamicDynIdentity = dynamicDyn
739+
740+--------------------------------------------------------------------------------
741+-- Combinators
742+--------------------------------------------------------------------------------
743+
744+--TODO: Figure out why certain things are not 'representational', then make them
745+--representational so we can use coerce
746+
747+--type role Hold representational
748+data Hold x p
749+ = Hold { holdValue :: !(IORef (PatchTarget p))
750+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
751+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
752+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
753+#ifdef DEBUG_NODEIDS
754+ , holdNodeId :: Int
755+#endif
756+ }
757+
758+-- | A statically allocated 'SpiderTimeline'
759+data Global
760+
761+{-# NOINLINE globalSpiderTimelineEnv #-}
762+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
763+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
764+
765+-- | Stores all global data relevant to a particular Spider timeline; only one
766+-- value should exist for each type @x@
767+data SpiderTimelineEnv x = SpiderTimelineEnv
768+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
769+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
770+#ifdef DEBUG
771+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
772+#endif
773+ }
774+type role SpiderTimelineEnv nominal
775+
776+instance Eq (SpiderTimelineEnv x) where
777+ _ == _ = True -- Since only one exists of each type
778+
779+instance GEq SpiderTimelineEnv where
780+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
781+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
782+ else Nothing
783+
784+data EventEnv x
785+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
786+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
787+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
788+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
789+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
790+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
791+ , eventEnvIntClears :: !(IORef [Some IntClear])
792+ , eventEnvRootClears :: !(IORef [Some RootClear])
793+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
794+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
795+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
796+ }
797+
798+{-# INLINE runEventM #-}
799+runEventM :: EventM x a -> IO a
800+runEventM = unEventM
801+
802+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
803+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
804+
805+class MonadIO m => Defer a m where
806+ getDeferralQueue :: m (IORef [a])
807+
808+{-# INLINE defer #-}
809+defer :: Defer a m => a -> m ()
810+defer a = do
811+ q <- getDeferralQueue
812+ liftIO $ modifyIORef' q (a:)
813+
814+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
815+ {-# INLINE getDeferralQueue #-}
816+ getDeferralQueue = asksEventEnv eventEnvAssignments
817+
818+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
819+ {-# INLINE getDeferralQueue #-}
820+ getDeferralQueue = asksEventEnv eventEnvHoldInits
821+
822+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
823+ {-# INLINE getDeferralQueue #-}
824+ getDeferralQueue = asksEventEnv eventEnvDynInits
825+
826+instance Defer (SomeHoldInit x) (BehaviorM x) where
827+ {-# INLINE getDeferralQueue #-}
828+ getDeferralQueue = BehaviorM $ asks snd
829+
830+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
831+ {-# INLINE getDeferralQueue #-}
832+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
833+
834+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
835+ {-# INLINE getDeferralQueue #-}
836+ getDeferralQueue = asksEventEnv eventEnvMergeInits
837+
838+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
839+ getCurrentHeight :: m Height
840+ scheduleMerge :: Height -> EventM x () -> m ()
841+
842+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
843+ {-# INLINE getCurrentHeight #-}
844+ getCurrentHeight = do
845+ heightRef <- asksEventEnv eventEnvCurrentHeight
846+ liftIO $ readIORef heightRef
847+ {-# INLINE scheduleMerge #-}
848+ scheduleMerge height subscribed = do
849+ delayedRef <- asksEventEnv eventEnvDelayedMerges
850+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
851+
852+class HasSpiderTimeline x where
853+ -- | Retrieve the current SpiderTimelineEnv
854+ spiderTimeline :: SpiderTimelineEnv x
855+
856+instance HasSpiderTimeline Global where
857+ spiderTimeline = globalSpiderTimelineEnv
858+
859+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
860+putCurrentHeight h = do
861+ heightRef <- asksEventEnv eventEnvCurrentHeight
862+ liftIO $ writeIORef heightRef $! h
863+
864+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
865+ {-# INLINE getDeferralQueue #-}
866+ getDeferralQueue = asksEventEnv eventEnvClears
867+
868+{-# INLINE scheduleClear #-}
869+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
870+scheduleClear r = defer $ Some $ Clear r
871+
872+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
873+ {-# INLINE getDeferralQueue #-}
874+ getDeferralQueue = asksEventEnv eventEnvIntClears
875+
876+{-# INLINE scheduleIntClear #-}
877+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
878+scheduleIntClear r = defer $ Some $ IntClear r
879+
880+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
881+ {-# INLINE getDeferralQueue #-}
882+ getDeferralQueue = asksEventEnv eventEnvRootClears
883+
884+{-# INLINE scheduleRootClear #-}
885+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
886+scheduleRootClear r = defer $ Some $ RootClear r
887+
888+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
889+ {-# INLINE getDeferralQueue #-}
890+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
891+
892+-- Note: hold cannot examine its event until after the phase is over
893+{-# INLINE [1] hold #-}
894+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
895+hold v0 e = do
896+ valRef <- liftIO $ newIORef v0
897+ invsRef <- liftIO $ newIORef []
898+ parentRef <- liftIO $ newIORef Nothing
899+#ifdef DEBUG_NODEIDS
900+ nodeId <- liftIO newNodeId
901+#endif
902+ let h = Hold
903+ { holdValue = valRef
904+ , holdInvalidators = invsRef
905+ , holdEvent = e
906+ , holdParent = parentRef
907+#ifdef DEBUG_NODEIDS
908+ , holdNodeId = nodeId
909+#endif
910+ }
911+ defer $ SomeHoldInit h
912+ return h
913+
914+{-# INLINE getHoldEventSubscription #-}
915+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
916+getHoldEventSubscription h = do
917+ ep <- liftIO $ readIORef $ holdParent h
918+ case ep of
919+ Just subd -> return subd
920+ Nothing -> do
921+ let e = holdEvent h
922+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
923+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
924+ liftIO $ writeIORef subscriptionRef $! subscription
925+ case occ of
926+ Nothing -> return ()
927+ Just o -> do
928+ old <- liftIO $ readIORef $ holdValue h
929+ case apply o old of
930+ Nothing -> return ()
931+ Just new -> do
932+ -- Need to evaluate these so that we don't retain the Hold itself
933+ v <- liftIO $ evaluate $ holdValue h
934+ i <- liftIO $ evaluate $ holdInvalidators h
935+ defer $ SomeAssignment v i new
936+ liftIO $ writeIORef (holdParent h) $ Just subscription
937+ return subscription
938+
939+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
940+
941+--type role BehaviorM representational
942+-- BehaviorM can sample behaviors
943+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
944+
945+instance Monad (BehaviorM x) where
946+ {-# INLINE (>>=) #-}
947+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
948+ {-# INLINE (>>) #-}
949+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
950+ {-# INLINE return #-}
951+ return x = BehaviorM $ return x
952+ {-# INLINE fail #-}
953+ fail s = BehaviorM $ fail s
954+
955+data BehaviorSubscribed x a
956+ = forall p. BehaviorSubscribedHold (Hold x p)
957+ | BehaviorSubscribedPull (PullSubscribed x a)
958+
959+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
960+
961+--type role PullSubscribed representational
962+data PullSubscribed x a
963+ = PullSubscribed { pullSubscribedValue :: !a
964+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
965+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
966+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
967+ }
968+
969+--type role Pull representational
970+data Pull x a
971+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
972+ , pullCompute :: !(BehaviorM x a)
973+#ifdef DEBUG_NODEIDS
974+ , pullNodeId :: Int
975+#endif
976+ }
977+
978+data Invalidator x
979+ = forall a. InvalidatorPull (Pull x a)
980+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
981+
982+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
983+ { rootSubscribedKey :: !(k a)
984+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
985+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
986+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
987+ , rootSubscribedUninit :: IO ()
988+ , 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?
989+#ifdef DEBUG_NODEIDS
990+ , rootSubscribedNodeId :: Int
991+#endif
992+ }
993+
994+data Root x k
995+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
996+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
997+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
998+ }
999+
1000+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1001+
1002+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1003+
1004+data SomeMergeUpdate x = SomeMergeUpdate
1005+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1006+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1007+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1008+ }
1009+
1010+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1011+
1012+-- EventM can do everything BehaviorM can, plus create holds
1013+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
1014+
1015+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1016+
1017+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1018+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1019+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1020+ }
1021+
1022+data HeightBag = HeightBag
1023+ { _heightBag_size :: {-# UNPACK #-} !Int
1024+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1025+ }
1026+ deriving (Show, Read, Eq, Ord)
1027+
1028+heightBagEmpty :: HeightBag
1029+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1030+
1031+heightBagSize :: HeightBag -> Int
1032+heightBagSize = _heightBag_size
1033+
1034+heightBagFromList :: [Height] -> HeightBag
1035+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1036+
1037+heightBagAdd :: Height -> HeightBag -> HeightBag
1038+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1039+
1040+heightBagRemove :: Height -> HeightBag -> HeightBag
1041+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1042+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1043+ Just old -> HeightBag (pred s) $ case old of
1044+ 0 -> IntMap.delete h c
1045+ _ -> IntMap.insert h (pred old) c
1046+
1047+heightBagMax :: HeightBag -> Height
1048+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1049+ Just ((h, _), _) -> Height h
1050+ Nothing -> zeroHeight
1051+
1052+heightBagVerify :: HeightBag -> HeightBag
1053+#ifdef DEBUG
1054+heightBagVerify b@(HeightBag s c) = if
1055+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1056+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1057+ | unHeight invalidHeight `IntMap.member` c
1058+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1059+ | otherwise -> b
1060+#else
1061+heightBagVerify = id
1062+#endif
1063+
1064+data FanSubscribedChildren x k v a = FanSubscribedChildren
1065+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1066+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1067+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1068+ }
1069+
1070+data FanSubscribed x k v
1071+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1072+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1073+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1074+ , fanSubscribedParent :: !(EventSubscription x)
1075+#ifdef DEBUG_NODEIDS
1076+ , fanSubscribedNodeId :: Int
1077+#endif
1078+ }
1079+
1080+data Fan x k v
1081+ = Fan { fanParent :: !(Event x (DMap k v))
1082+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1083+ }
1084+
1085+data SwitchSubscribed x a
1086+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1087+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1088+ , switchSubscribedHeight :: !(IORef Height)
1089+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1090+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1091+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1092+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1093+ , switchSubscribedParent :: !(Behavior x (Event x a))
1094+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1095+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1096+#ifdef DEBUG_NODEIDS
1097+ , switchSubscribedNodeId :: Int
1098+#endif
1099+ }
1100+
1101+data Switch x a
1102+ = Switch { switchParent :: !(Behavior x (Event x a))
1103+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1104+ }
1105+
1106+#ifdef USE_TEMPLATE_HASKELL
1107+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1108+#endif
1109+data CoincidenceSubscribed x a
1110+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1111+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1112+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1113+ , coincidenceSubscribedHeight :: !(IORef Height)
1114+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1115+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1116+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1117+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1118+#ifdef DEBUG_NODEIDS
1119+ , coincidenceSubscribedNodeId :: Int
1120+#endif
1121+ }
1122+
1123+data Coincidence x a
1124+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1125+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1126+ }
1127+
1128+{-# NOINLINE newInvalidatorSwitch #-}
1129+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1130+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1131+
1132+{-# NOINLINE newInvalidatorPull #-}
1133+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1134+newInvalidatorPull p = return $! InvalidatorPull p
1135+
1136+instance HasSpiderTimeline x => Filterable (Event x) where
1137+ mapMaybe f = push $ return . f
1138+
1139+instance HasSpiderTimeline x => Align (Event x) where
1140+ nil = eventNever
1141+#if MIN_VERSION_these(0, 8, 0)
1142+instance HasSpiderTimeline x => Semialign (Event x) where
1143+#endif
1144+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1145+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1146+
1147+#if defined(MIN_VERSION_semialign)
1148+ zip x y = mapMaybe justThese $ align x y
1149+#endif
1150+
1151+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1152+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1153+ | HoldDyn !(Hold x p)
1154+
1155+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1156+
1157+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1158+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1159+
1160+--TODO: Avoid the duplication between this and R.zipDynWith
1161+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1162+zipDynWith f da db =
1163+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1164+ ec = flip push eab $ \o -> do
1165+ (a, b) <- case o of
1166+ This (Identity a) -> do
1167+ b <- readBehaviorUntracked $ dynamicCurrent db
1168+ return (a, b)
1169+ That (Identity b) -> do
1170+ a <- readBehaviorUntracked $ dynamicCurrent da
1171+ return (a, b)
1172+ These (Identity a) (Identity b) -> return (a, b)
1173+ return $ Just $ Identity $ f a b
1174+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1175+
1176+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1177+buildDynamic readV0 v' = do
1178+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1179+ let !d = Dyn result
1180+ defer $ SomeDynInit d
1181+ return d
1182+
1183+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1184+unsafeBuildDynamic readV0 v' =
1185+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
1186+
1187+-- ResultM can read behaviors and events
1188+type ResultM = EventM
1189+
1190+instance HasSpiderTimeline x => Functor (Event x) where
1191+ fmap f = push $ return . Just . f
1192+
1193+instance Functor (Behavior x) where
1194+ fmap f = pull . fmap f . readBehaviorTracked
1195+
1196+{-# INLINE push #-}
1197+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1198+push f e = cacheEvent (pushCheap f e)
1199+
1200+{-# INLINABLE pull #-}
1201+pull :: BehaviorM x a -> Behavior x a
1202+pull a = unsafePerformIO $ do
1203+ ref <- newIORef Nothing
1204+#ifdef DEBUG_NODEIDS
1205+ nid <- newNodeId
1206+#endif
1207+ pure $ behaviorPull $ Pull
1208+ { pullCompute = a
1209+ , pullValue = ref
1210+#ifdef DEBUG_NODEIDS
1211+ , pullNodeId = nid
1212+#endif
1213+ }
1214+
1215+{-# INLINABLE switch #-}
1216+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1217+switch a = unsafePerformIO $ do
1218+ ref <- newIORef Nothing
1219+ pure $ eventSwitch $ Switch
1220+ { switchParent = a
1221+ , switchSubscribed = ref
1222+ }
1223+
1224+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1225+coincidence a = unsafePerformIO $ do
1226+ ref <- newIORef Nothing
1227+ pure $ eventCoincidence $ Coincidence
1228+ { coincidenceParent = a
1229+ , coincidenceSubscribed = ref
1230+ }
1231+
1232+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1233+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1234+run roots after = do
1235+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1236+ let t = spiderTimeline :: SpiderTimelineEnv x
1237+ result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1238+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1239+ occBefore <- liftIO $ do
1240+ occBefore <- readIORef occRef
1241+ writeIORef occRef $! DMap.insert k a occBefore
1242+ return occBefore
1243+ if DMap.null occBefore
1244+ then do scheduleRootClear occRef
1245+ return $ Just r
1246+ else return Nothing
1247+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1248+ propagate a subscribersRef
1249+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1250+ let go = do
1251+ delayed <- liftIO $ readIORef delayedRef
1252+ case IntMap.minViewWithKey delayed of
1253+ Nothing -> return ()
1254+ Just ((currentHeight, cur), future) -> do
1255+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1256+ putCurrentHeight $ Height currentHeight
1257+ liftIO $ writeIORef delayedRef $! future
1258+ sequence_ cur
1259+ go
1260+ go
1261+ putCurrentHeight maxBound
1262+ after
1263+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1264+ return result
1265+
1266+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1267+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1268+ height <- liftIO $ readIORef heightRef
1269+ currentHeight <- getCurrentHeight
1270+ case height `compare` currentHeight of
1271+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1272+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1273+ EQ -> a
1274+
1275+newtype Clear a = Clear (IORef (Maybe a))
1276+
1277+newtype IntClear a = IntClear (IORef (IntMap a))
1278+
1279+newtype RootClear k = RootClear (IORef (DMap k Identity))
1280+
1281+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1282+
1283+debugFinalize :: Bool
1284+debugFinalize = False
1285+
1286+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1287+mkWeakPtrWithDebug x debugNote = do
1288+ x' <- evaluate x
1289+ mkWeakPtr x' $
1290+ if debugFinalize
1291+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1292+ else Nothing
1293+
1294+type WeakList a = [Weak a]
1295+
1296+{-# INLINE withIncreasedDepth #-}
1297+#ifdef DEBUG
1298+withIncreasedDepth :: CanTrace x m => m a -> m a
1299+withIncreasedDepth a = do
1300+ spiderTimeline <- askSpiderTimelineEnv
1301+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1302+ result <- a
1303+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1304+ return result
1305+#else
1306+withIncreasedDepth :: m a -> m a
1307+withIncreasedDepth = id
1308+#endif
1309+
1310+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1311+
1312+{-# INLINE tracePropagate #-}
1313+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1314+tracePropagate p = traceWhen p debugPropagate
1315+
1316+{-# INLINE traceInvalidate #-}
1317+traceInvalidate :: String -> IO ()
1318+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1319+
1320+{-# INLINE traceWhen #-}
1321+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1322+traceWhen p b message = traceMWhen p b $ return message
1323+
1324+{-# INLINE traceMWhen #-}
1325+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1326+traceMWhen _ b getMessage = when b $ do
1327+ message <- getMessage
1328+#ifdef DEBUG
1329+ spiderTimeline <- askSpiderTimelineEnv
1330+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1331+#else
1332+ let d = 0
1333+#endif
1334+ liftIO $ putStrLn $ replicate d ' ' <> message
1335+
1336+whoCreatedIORef :: IORef a -> IO [String]
1337+whoCreatedIORef (IORef a) = whoCreated $! a
1338+
1339+#ifdef DEBUG_CYCLES
1340+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1341+groupByHead = \case
1342+ [] -> []
1343+ (x :| xs) : t -> case groupByHead t of
1344+ [] -> [(x, xs :| [])]
1345+ l@((y, yss) : t')
1346+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1347+ | otherwise -> (x, xs :| []) : l
1348+
1349+listsToForest :: Eq a => [[a]] -> Forest a
1350+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1351+#endif
1352+
1353+{-# INLINE propagateSubscriberHold #-}
1354+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1355+propagateSubscriberHold h a = do
1356+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1357+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1358+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1359+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1360+ case {-# SCC "apply" #-} apply a v of
1361+ Nothing -> return ()
1362+ Just v' -> do
1363+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1364+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1365+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1366+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1367+
1368+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1369+
1370+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1371+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1372+
1373+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1374+askInvalidator = do
1375+ (!m, _) <- BehaviorM ask
1376+ case m of
1377+ Nothing -> return Nothing
1378+ Just (!wi, _) -> return $ Just wi
1379+
1380+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1381+askParentsRef = do
1382+ (!m, _) <- BehaviorM ask
1383+ case m of
1384+ Nothing -> return Nothing
1385+ Just (_, !p) -> return $ Just p
1386+
1387+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1388+askBehaviorHoldInits = do
1389+ (_, !his) <- BehaviorM ask
1390+ return his
1391+
1392+{-# INLINE getDynHold #-}
1393+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1394+getDynHold d = do
1395+ mh <- liftIO $ readIORef $ unDyn d
1396+ case mh of
1397+ HoldDyn h -> return h
1398+ UnsafeDyn (readV0, v') -> do
1399+ holdInits <- getDeferralQueue
1400+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1401+ hold' v0 v'
1402+ BuildDyn (readV0, v') -> do
1403+ v0 <- liftIO $ runEventM readV0
1404+ hold' v0 v'
1405+ where
1406+ hold' v0 v' = do
1407+ h <- hold v0 v'
1408+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1409+ return h
1410+
1411+
1412+-- Always refers to 0
1413+{-# NOINLINE zeroRef #-}
1414+zeroRef :: IORef Height
1415+zeroRef = unsafePerformIO $ newIORef zeroHeight
1416+
1417+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1418+getRootSubscribed k r sub = do
1419+ mSubscribed <- readIORef $ rootSubscribed r
1420+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1421+ case DMap.lookup k mSubscribed of
1422+ Just subscribed -> {-# SCC "hitRoot" #-} do
1423+ sln <- subscribeRootSubscribed subscribed sub
1424+ occ <- getOcc
1425+ return (sln, subscribed, occ)
1426+ Nothing -> {-# SCC "missRoot" #-} do
1427+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1428+ let !cached = rootSubscribed r
1429+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1430+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1431+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1432+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1433+ writeIORef uninitRef $! uninit
1434+#ifdef DEBUG_NODEIDS
1435+ nid <- newNodeId
1436+#endif
1437+ let !subscribed = RootSubscribed
1438+ { rootSubscribedKey = k
1439+ , rootSubscribedCachedSubscribed = cached
1440+ , rootSubscribedOccurrence = getOcc
1441+ , rootSubscribedSubscribers = subs
1442+ , rootSubscribedUninit = uninit
1443+ , rootSubscribedWeakSelf = weakSelf
1444+#ifdef DEBUG_NODEIDS
1445+ , rootSubscribedNodeId = nid
1446+#endif
1447+ }
1448+ -- If we die at the same moment that all our children die, they will
1449+ -- try to clean us up but will fail because their Weak reference to us
1450+ -- will also be dead. So, if we are dying, check if there are any
1451+ -- children; since children don't bother cleaning themselves up if
1452+ -- their parents are already dead, I don't think there's a race
1453+ -- condition here. However, if there are any children, then we can
1454+ -- infer that we need to clean ourselves up, so we do.
1455+ finalCleanup = do
1456+ cs <- readIORef $ _weakBag_children subs
1457+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1458+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1459+ 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
1460+ occ <- getOcc
1461+ return (sln, subscribed, occ)
1462+
1463+#ifdef USE_TEMPLATE_HASKELL
1464+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1465+#endif
1466+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1467+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1468+ rootSubscribedUninit self
1469+ modifyIORef' cached $ DMap.delete k
1470+
1471+{-# INLINE subscribeRootSubscribed #-}
1472+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1473+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1474+
1475+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1476+
1477+data FanInt x a = FanInt
1478+ { _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
1479+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1480+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1481+ }
1482+
1483+newFanInt :: IO (FanInt x a)
1484+newFanInt = do
1485+ 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
1486+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1487+ occRef <- newIORef $ error "fanInt: no occurrence"
1488+ return $ FanInt
1489+ { _fanInt_subscribers = subscribers
1490+ , _fanInt_subscriptionRef = subscriptionRef
1491+ , _fanInt_occRef = occRef
1492+ }
1493+
1494+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1495+fanInt p = unsafePerformIO $ do
1496+ self <- newFanInt
1497+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1498+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1499+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1500+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1501+ { subscriberPropagate = \m -> do
1502+ liftIO $ writeIORef (_fanInt_occRef self) m
1503+ scheduleIntClear $ _fanInt_occRef self
1504+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1505+ FastWeakBag.traverse b $ \s -> do
1506+ subscriberPropagate s v
1507+ , subscriberInvalidateHeight = \old -> do
1508+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1509+ FastWeakBag.traverse b $ \s -> do
1510+ subscriberInvalidateHeight s old
1511+ , subscriberRecalculateHeight = \new -> do
1512+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1513+ FastWeakBag.traverse b $ \s -> do
1514+ subscriberRecalculateHeight s new
1515+ }
1516+ liftIO $ do
1517+ writeIORef (_fanInt_subscriptionRef self) subscription
1518+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1519+ scheduleIntClear $ _fanInt_occRef self
1520+ liftIO $ do
1521+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1522+ Nothing -> do
1523+ b <- FastWeakBag.empty
1524+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1525+ return b
1526+ Just b -> return b
1527+ t <- liftIO $ FastWeakBag.insert sub b
1528+ currentOcc <- readIORef (_fanInt_occRef self)
1529+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1530+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1531+
1532+{-# INLINABLE getFanSubscribed #-}
1533+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))
1534+getFanSubscribed k f sub = do
1535+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1536+ case mSubscribed of
1537+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1538+ sln <- subscribeFanSubscribed k subscribed sub
1539+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1540+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1541+ Nothing -> {-# SCC "missFan" #-} do
1542+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1543+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1544+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1545+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1546+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1547+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1548+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1549+ occRef <- liftIO $ newIORef parentOcc
1550+ when (isJust parentOcc) $ scheduleClear occRef
1551+#ifdef DEBUG_NODEIDS
1552+ nid <- liftIO newNodeId
1553+#endif
1554+ let subscribed = FanSubscribed
1555+ { fanSubscribedCachedSubscribed = fanSubscribed f
1556+ , fanSubscribedOccurrence = occRef
1557+ , fanSubscribedParent = subscription
1558+ , fanSubscribedSubscribers = subscribersRef
1559+#ifdef DEBUG_NODEIDS
1560+ , fanSubscribedNodeId = nid
1561+#endif
1562+ }
1563+ let !self = (k, subscribed)
1564+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1565+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1566+ liftIO $ writeIORef subscribedRef $! subscribed
1567+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1568+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1569+
1570+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1571+cleanupFanSubscribed (k, subscribed) = do
1572+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1573+ let reducedSubscribers = DMap.delete k subscribers
1574+ if DMap.null reducedSubscribers
1575+ then do
1576+ unsubscribe $ fanSubscribedParent subscribed
1577+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1578+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1579+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1580+
1581+{-# INLINE subscribeFanSubscribed #-}
1582+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1583+subscribeFanSubscribed k subscribed sub = do
1584+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1585+ case DMap.lookup k subscribers of
1586+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1587+ let !self = (k, subscribed)
1588+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1589+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1590+ 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
1591+ return sln
1592+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1593+
1594+{-# INLINABLE getSwitchSubscribed #-}
1595+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1596+getSwitchSubscribed s sub = do
1597+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1598+ case mSubscribed of
1599+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1600+ sln <- subscribeSwitchSubscribed subscribed sub
1601+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1602+ return (sln, subscribed, occ)
1603+ Nothing -> {-# SCC "missSwitch" #-} do
1604+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1605+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1606+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1607+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1608+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1609+ wiRef <- liftIO $ newIORef wi
1610+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1611+ holdInits <- getDeferralQueue
1612+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1613+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1614+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1615+ subscriptionRef <- liftIO $ newIORef subscription
1616+ occRef <- liftIO $ newIORef parentOcc
1617+ when (isJust parentOcc) $ scheduleClear occRef
1618+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1619+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1620+#ifdef DEBUG_NODEIDS
1621+ nid <- liftIO newNodeId
1622+#endif
1623+ let !subscribed = SwitchSubscribed
1624+ { switchSubscribedCachedSubscribed = switchSubscribed s
1625+ , switchSubscribedOccurrence = occRef
1626+ , switchSubscribedHeight = heightRef
1627+ , switchSubscribedSubscribers = subs
1628+ , switchSubscribedOwnInvalidator = i
1629+ , switchSubscribedOwnWeakInvalidator = wiRef
1630+ , switchSubscribedBehaviorParents = parentsRef
1631+ , switchSubscribedParent = switchParent s
1632+ , switchSubscribedCurrentParent = subscriptionRef
1633+ , switchSubscribedWeakSelf = weakSelf
1634+#ifdef DEBUG_NODEIDS
1635+ , switchSubscribedNodeId = nid
1636+#endif
1637+ }
1638+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1639+ liftIO $ writeIORef subscribedRef $! subscribed
1640+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1641+ return (slnForSub, subscribed, parentOcc)
1642+
1643+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1644+cleanupSwitchSubscribed subscribed = do
1645+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1646+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1647+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1648+
1649+{-# INLINE subscribeSwitchSubscribed #-}
1650+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1651+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1652+
1653+{-# INLINABLE getCoincidenceSubscribed #-}
1654+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1655+getCoincidenceSubscribed c sub = do
1656+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1657+ case mSubscribed of
1658+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1659+ sln <- subscribeCoincidenceSubscribed subscribed sub
1660+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1661+ return (sln, subscribed, occ)
1662+ Nothing -> {-# SCC "missCoincidence" #-} do
1663+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1664+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1665+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1666+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1667+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1668+ (occ, height, mInnerSubd) <- case outerOcc of
1669+ Nothing -> return (Nothing, outerHeight, Nothing)
1670+ Just o -> do
1671+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1672+ return (occ, height, Just innerSubd)
1673+ occRef <- liftIO $ newIORef occ
1674+ when (isJust occ) $ scheduleClear occRef
1675+ heightRef <- liftIO $ newIORef height
1676+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1677+ scheduleClear innerSubdRef
1678+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1679+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1680+#ifdef DEBUG_NODEIDS
1681+ nid <- liftIO newNodeId
1682+#endif
1683+ let subscribed = CoincidenceSubscribed
1684+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1685+ , coincidenceSubscribedOccurrence = occRef
1686+ , coincidenceSubscribedHeight = heightRef
1687+ , coincidenceSubscribedSubscribers = subs
1688+ , coincidenceSubscribedOuter = subOuter
1689+ , coincidenceSubscribedOuterParent = outerSubscription
1690+ , coincidenceSubscribedInnerParent = innerSubdRef
1691+ , coincidenceSubscribedWeakSelf = weakSelf
1692+#ifdef DEBUG_NODEIDS
1693+ , coincidenceSubscribedNodeId = nid
1694+#endif
1695+ }
1696+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1697+ liftIO $ writeIORef subscribedRef $! subscribed
1698+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1699+ return (slnForSub, subscribed, occ)
1700+
1701+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1702+cleanupCoincidenceSubscribed subscribed = do
1703+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1704+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1705+
1706+{-# INLINE subscribeCoincidenceSubscribed #-}
1707+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1708+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1709+
1710+{-# INLINE mergeG #-}
1711+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1712+ => (forall a. q a -> Event x (v a))
1713+ -> Dynamic x (PatchDMap k q) -> Event x (DMap k v)
1714+mergeG nt d = cacheEvent (mergeCheap nt d)
1715+
1716+{-# INLINE mergeWithMove #-}
1717+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1718+ => (forall a. q a -> Event x (v a))
1719+ -> Dynamic x (PatchDMapWithMove k q) -> Event x (DMap k v)
1720+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1721+
1722+{-# INLINE [1] mergeCheap #-}
1723+mergeCheap
1724+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1725+ => (forall a. q a -> Event x (v a))
1726+ -> Dynamic x (PatchDMap k q)
1727+ -> Event x (DMap k v)
1728+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
1729+ where
1730+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1731+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1732+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1733+ (mOldSubd, newPs) <- case me of
1734+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1735+ Just e -> do
1736+ let s = subscriber $ return k
1737+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1738+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1739+ let newParent = MergeSubscribedParent subscription
1740+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1741+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1742+ forM_ mOldSubd $ \oldSubd -> do
1743+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1744+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1745+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1746+ foldM f ([], oldParents) $ DMap.toList p
1747+
1748+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1749+ getInitialSubscribers initialParents subscriber = do
1750+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1751+ let s = subscriber $ return k
1752+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1753+ height <- liftIO $ getEventSubscribedHeight parentSubd
1754+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1755+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1756+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1757+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1758+ )
1759+
1760+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1761+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1762+
1763+{-# INLINE [1] mergeCheapWithMove #-}
1764+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1765+ => (forall a. q a -> Event x (v a))
1766+ -> Dynamic x (PatchDMapWithMove k q)
1767+ -> Event x (DMap k v)
1768+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
1769+ where
1770+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1771+ updateMe subscriber heightBagRef oldParents p = do
1772+ -- Prepare new parents for insertion
1773+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1774+ subscribeParent k e = do
1775+ keyRef <- liftIO $ newIORef k
1776+ let s = subscriber $ liftIO $ readIORef keyRef
1777+ subscription@(EventSubscription _ subd) <- subscribe e s
1778+ liftIO $ do
1779+ newParentHeight <- getEventSubscribedHeight subd
1780+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1781+ return $ MergeSubscribedParentWithMove subscription keyRef
1782+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1783+ -- Collect old parents for deletion and update the keys of moved parents
1784+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1785+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1786+ Nothing -> do
1787+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1788+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1789+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1790+ Just toKey -> do
1791+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1792+ return Nothing
1793+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1794+ return (toDelete, applyAlways p' oldParents)
1795+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1796+ getInitialSubscribers initialParents subscriber = do
1797+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1798+ keyRef <- liftIO $ newIORef k
1799+ let s = subscriber $ liftIO $ readIORef keyRef
1800+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1801+ height <- liftIO $ getEventSubscribedHeight parentSubd
1802+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1803+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1804+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1805+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1806+ )
1807+
1808+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1809+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1810+
1811+type MergeUpdateFunc k v x p s
1812+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1813+ -> IORef HeightBag
1814+ -> DMap k s
1815+ -> p
1816+ -> EventM x ([EventSubscription x], DMap k s)
1817+
1818+type MergeInitFunc k v q x s
1819+ = DMap k q
1820+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1821+ -> EventM x (DMap k v, [Height], DMap k s)
1822+
1823+type MergeDestroyFunc k s
1824+ = DMap k s
1825+ -> IO ()
1826+
1827+data Merge x k v s = Merge
1828+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1829+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1830+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1831+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1832+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
1833+ }
1834+
1835+invalidateMergeHeight :: Merge x k v s -> IO ()
1836+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1837+
1838+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1839+invalidateMergeHeight' heightRef sub = do
1840+ oldHeight <- readIORef heightRef
1841+ 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
1842+ writeIORef heightRef $! invalidHeight
1843+ subscriberInvalidateHeight sub oldHeight
1844+
1845+revalidateMergeHeight :: Merge x k v s -> IO ()
1846+revalidateMergeHeight m = do
1847+ currentHeight <- readIORef $ _merge_heightRef m
1848+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1849+ heights <- readIORef $ _merge_heightBagRef m
1850+ parents <- readIORef $ _merge_parentsRef m
1851+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1852+ case heightBagSize heights `compare` DMap.size parents of
1853+ LT -> return ()
1854+ EQ -> do
1855+ let height = succHeight $ heightBagMax heights
1856+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1857+ writeIORef (_merge_heightRef m) $! height
1858+ subscriberRecalculateHeight (_merge_sub m) height
1859+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1860+
1861+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
1862+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1863+ vals <- liftIO $ readIORef $ _merge_accumRef m
1864+ 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
1865+ --TODO: Assert that m is not empty
1866+ subscriberPropagate (_merge_sub m) vals
1867+
1868+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
1869+mergeSubscriber m getKey = Subscriber
1870+ { subscriberPropagate = \a -> do
1871+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1872+ k <- getKey
1873+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
1874+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1875+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1876+ when (DMap.null oldM) $ do -- Only schedule the firing once
1877+ height <- liftIO $ readIORef $ _merge_heightRef m
1878+ --TODO: assertions about height
1879+ currentHeight <- getCurrentHeight
1880+ when (height <= currentHeight) $ do
1881+ if height /= invalidHeight
1882+ then do
1883+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1884+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1885+ else liftIO $ do
1886+#ifdef DEBUG_CYCLES
1887+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1888+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
1889+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1890+#else
1891+ let cycleInfo = ""
1892+#endif
1893+ error $ "Causality loop found" <> cycleInfo
1894+ scheduleMergeSelf m height
1895+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1896+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1897+ invalidateMergeHeight m
1898+ , subscriberRecalculateHeight = \new -> do
1899+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1900+ revalidateMergeHeight m
1901+ }
1902+
1903+--TODO: Be able to run as much of this as possible promptly
1904+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
1905+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1906+ where updateMe = do
1907+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1908+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1909+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1910+ return subscriptionsToKill
1911+
1912+{-# INLINE mergeGCheap' #-}
1913+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1914+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> Dynamic x p -> Event x (DMap k v)
1915+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1916+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1917+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1918+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1919+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1920+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1921+ let m = Merge
1922+ { _merge_parentsRef = parentsRef
1923+ , _merge_heightBagRef = heightBagRef
1924+ , _merge_heightRef = heightRef
1925+ , _merge_sub = sub
1926+ , _merge_accumRef = accumRef
1927+ }
1928+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1929+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1930+ myHeight = if invalidHeight `elem` heights
1931+ then invalidHeight
1932+ else succHeight $ heightBagMax myHeightBag
1933+ currentHeight <- getCurrentHeight
1934+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1935+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1936+ else (Nothing, dm)
1937+ unless (DMap.null accum) $ do
1938+ scheduleMergeSelf m myHeight
1939+ liftIO $ writeIORef accumRef $! accum
1940+ liftIO $ writeIORef heightRef $! myHeight
1941+ liftIO $ writeIORef heightBagRef $! myHeightBag
1942+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1943+ liftIO $ writeIORef parentsRef $! initialParentState
1944+ defer $ SomeMergeInit $ do
1945+ let s = Subscriber
1946+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1947+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1948+ defer $ updateMerge m updateFunc a
1949+ , subscriberInvalidateHeight = \_ -> return ()
1950+ , subscriberRecalculateHeight = \_ -> return ()
1951+ }
1952+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1953+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1954+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1955+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1956+ -- its subscription.
1957+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1958+ let unsubscribeAll = destroy =<< readIORef parentsRef
1959+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1960+ , occ
1961+ )
1962+
1963+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1964+mergeInt = cacheEvent . mergeIntCheap
1965+
1966+{-# INLINABLE mergeIntCheap #-}
1967+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1968+mergeIntCheap d = Event $ \sub -> do
1969+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1970+ accum <- liftIO $ FastMutableIntMap.newEmpty
1971+ heightRef <- liftIO $ newIORef zeroHeight
1972+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1973+ parents <- liftIO $ FastMutableIntMap.newEmpty
1974+ let scheduleSelf = do
1975+ height <- liftIO $ readIORef $ heightRef
1976+ scheduleMerge' height heightRef $ do
1977+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1978+ subscriberPropagate sub vals
1979+ invalidateMyHeight = do
1980+ invalidateMergeHeight' heightRef sub
1981+ recalculateMyHeight = do
1982+ currentHeight <- readIORef heightRef
1983+ 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?
1984+ heights <- readIORef heightBagRef
1985+ numParents <- FastMutableIntMap.size parents
1986+ case heightBagSize heights `compare` numParents of
1987+ LT -> return ()
1988+ EQ -> do
1989+ let height = succHeight $ heightBagMax heights
1990+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1991+ writeIORef heightRef $! height
1992+ subscriberRecalculateHeight sub height
1993+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1994+ mySubscriber k = Subscriber
1995+ { subscriberPropagate = \a -> do
1996+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1997+ liftIO $ FastMutableIntMap.insert accum k a
1998+ when wasEmpty scheduleSelf
1999+ , subscriberInvalidateHeight = \old -> do
2000+ modifyIORef' heightBagRef $ heightBagRemove old
2001+ invalidateMyHeight
2002+ , subscriberRecalculateHeight = \new -> do
2003+ modifyIORef' heightBagRef $ heightBagAdd new
2004+ recalculateMyHeight
2005+ }
2006+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2007+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2008+ liftIO $ do
2009+ forM_ parentOcc $ FastMutableIntMap.insert accum k
2010+ FastMutableIntMap.insert parents k subscription
2011+ height <- getEventSubscribedHeight parentSubd
2012+ if height == invalidHeight
2013+ then writeIORef heightRef invalidHeight
2014+ else do
2015+ modifyIORef' heightBagRef $ heightBagAdd height
2016+ modifyIORef' heightRef $ \oldHeight ->
2017+ if oldHeight == invalidHeight
2018+ then invalidHeight
2019+ else max (succHeight height) oldHeight
2020+ myHeight <- liftIO $ readIORef heightRef
2021+ currentHeight <- getCurrentHeight
2022+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2023+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2024+ then if isEmpty
2025+ then return Nothing
2026+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2027+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2028+ return Nothing
2029+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2030+ defer $ SomeMergeInit $ do
2031+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2032+ where
2033+ u = do
2034+ let f k newParent = do
2035+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2036+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2037+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2038+ return subscription
2039+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2040+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2041+ liftIO $ for_ oldParents $ \oldParent -> do
2042+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2043+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2044+ return $ IntMap.elems oldParents
2045+ let s = Subscriber
2046+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2047+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2048+ defer $ updateMe a
2049+ , subscriberInvalidateHeight = \_ -> return ()
2050+ , subscriberRecalculateHeight = \_ -> return ()
2051+ }
2052+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2053+ forM_ change $ \c -> defer $ updateMe c
2054+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2055+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2056+ -- its subscription.
2057+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2058+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2059+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2060+ , occ
2061+ )
2062+
2063+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2064+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2065+
2066+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2067+fanG e = unsafePerformIO $ do
2068+ ref <- newIORef Nothing
2069+ let f = Fan
2070+ { fanParent = e
2071+ , fanSubscribed = ref
2072+ }
2073+ pure $ EventSelectorG $ \k -> eventFan k f
2074+
2075+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2076+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2077+ holdInits <- liftIO $ readIORef holdInitRef
2078+ dynInits <- liftIO $ readIORef dynInitRef
2079+ mergeInits <- liftIO $ readIORef mergeInitRef
2080+ unless (null holdInits && null dynInits && null mergeInits) $ do
2081+ liftIO $ writeIORef holdInitRef []
2082+ liftIO $ writeIORef dynInitRef []
2083+ liftIO $ writeIORef mergeInitRef []
2084+ mapM_ initHold holdInits
2085+ mapM_ initDyn dynInits
2086+ mapM_ unSomeMergeInit mergeInits
2087+ runHoldInits holdInitRef dynInitRef mergeInitRef
2088+
2089+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2090+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2091+
2092+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2093+initDyn (SomeDynInit d) = void $ getDynHold d
2094+
2095+newEventEnv :: IO (EventEnv x)
2096+newEventEnv = do
2097+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2098+ holdInitRef <- newIORef []
2099+ dynInitRef <- newIORef []
2100+ mergeUpdateRef <- newIORef []
2101+ mergeInitRef <- newIORef []
2102+ heightRef <- newIORef zeroHeight
2103+ toClearRef <- newIORef []
2104+ toClearIntRef <- newIORef []
2105+ toClearRootRef <- newIORef []
2106+ coincidenceInfosRef <- newIORef []
2107+ delayedRef <- newIORef IntMap.empty
2108+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2109+
2110+clearEventEnv :: EventEnv x -> IO ()
2111+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2112+ writeIORef toAssignRef []
2113+ writeIORef holdInitRef []
2114+ writeIORef dynInitRef []
2115+ writeIORef mergeUpdateRef []
2116+ writeIORef mergeInitRef []
2117+ writeIORef heightRef zeroHeight
2118+ writeIORef toClearRef []
2119+ writeIORef toClearIntRef []
2120+ writeIORef toClearRootRef []
2121+ writeIORef coincidenceInfosRef []
2122+ writeIORef delayedRef IntMap.empty
2123+
2124+-- | Run an event action outside of a frame
2125+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2126+runFrame a = SpiderHost $ do
2127+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2128+ let go = do
2129+ result <- a
2130+ 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
2131+ return result
2132+ result <- runEventM go
2133+ toClear <- readIORef $ eventEnvClears env
2134+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2135+ toClearInt <- readIORef $ eventEnvIntClears env
2136+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2137+ toClearRoot <- readIORef $ eventEnvRootClears env
2138+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2139+ toAssign <- readIORef $ eventEnvAssignments env
2140+ toReconnectRef <- newIORef []
2141+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2142+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2143+ writeIORef vRef v
2144+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2145+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2146+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2147+ writeIORef (eventEnvMergeUpdates env) []
2148+ when debugPropagate $ putStrLn "Updating merges"
2149+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2150+ when debugPropagate $ putStrLn "Updating merges done"
2151+ toReconnect <- readIORef toReconnectRef
2152+ clearEventEnv env
2153+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2154+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2155+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2156+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2157+ finalize wi
2158+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2159+ wi' <- mkWeakPtrWithDebug i "wi'"
2160+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2161+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2162+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2163+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2164+ 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
2165+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2166+ sub <- newSubscriberSwitch subscribed
2167+ 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
2168+ {-
2169+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2170+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2171+ EventRoot _ -> "EventRoot"
2172+ EventNever -> "EventNever"
2173+ _ -> "something else"
2174+ -}
2175+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2176+ return oldSubscription
2177+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2178+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2179+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2180+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2181+ parentHeight <- getEventSubscribedHeight subd'
2182+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2183+ when (parentHeight /= myHeight) $ do
2184+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2185+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2186+ 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
2187+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2188+ unsubscribe subscription
2189+ mapM_ invalidateCoincidenceHeight mcs
2190+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2191+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2192+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2193+ height <- calculateSwitchHeight subscribed
2194+ updateSwitchHeight height subscribed
2195+ return result
2196+
2197+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2198+
2199+{-# INLINE zeroHeight #-}
2200+zeroHeight :: Height
2201+zeroHeight = Height 0
2202+
2203+{-# INLINE invalidHeight #-}
2204+invalidHeight :: Height
2205+invalidHeight = Height (-1000)
2206+
2207+#ifdef DEBUG_CYCLES
2208+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2209+{-# INLINE invalidHeightBeingTraversed #-}
2210+invalidHeightBeingTraversed :: Height
2211+invalidHeightBeingTraversed = Height (-1001)
2212+#endif
2213+
2214+{-# INLINE succHeight #-}
2215+succHeight :: Height -> Height
2216+succHeight h@(Height a) =
2217+ if h == invalidHeight
2218+ then invalidHeight
2219+ else Height $ succ a
2220+
2221+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2222+invalidateCoincidenceHeight subscribed = do
2223+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2224+ when (oldHeight /= invalidHeight) $ do
2225+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2226+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2227+
2228+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2229+updateSwitchHeight new subscribed = do
2230+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2231+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2232+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2233+ writeIORef (switchSubscribedHeight subscribed) $! new
2234+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2235+
2236+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2237+recalculateCoincidenceHeight subscribed = do
2238+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2239+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2240+ height <- calculateCoincidenceHeight subscribed
2241+ when (height /= invalidHeight) $ do
2242+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2243+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2244+
2245+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2246+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2247+
2248+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2249+calculateCoincidenceHeight subscribed = do
2250+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2251+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2252+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2253+
2254+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2255+
2256+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2257+invalidate toReconnectRef wis = do
2258+ forM_ wis $ \wi -> do
2259+ mi <- deRefWeak wi
2260+ case mi of
2261+ Nothing -> do
2262+ traceInvalidate "invalidate Dead"
2263+ return () --TODO: Should we clean this up here?
2264+ Just i -> do
2265+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2266+ case i of
2267+ InvalidatorPull p -> do
2268+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2269+ mVal <- readIORef $ pullValue p
2270+ forM_ mVal $ \val -> do
2271+ writeIORef (pullValue p) Nothing
2272+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2273+ InvalidatorSwitch subscribed -> do
2274+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2275+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2276+ 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
2277+
2278+--------------------------------------------------------------------------------
2279+-- Reflex integration
2280+--------------------------------------------------------------------------------
2281+
2282+-- | Designates the default, global Spider timeline
2283+data SpiderTimeline x
2284+type role SpiderTimeline nominal
2285+
2286+-- | The default, global Spider environment
2287+type Spider = SpiderTimeline Global
2288+
2289+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2290+ {-# INLINABLE sample #-}
2291+ sample (SpiderBehavior b) = readBehaviorUntracked b
2292+
2293+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2294+ {-# INLINABLE hold #-}
2295+ hold = holdSpiderEventM
2296+ {-# INLINABLE holdDyn #-}
2297+ holdDyn = holdDynSpiderEventM
2298+ {-# INLINABLE holdIncremental #-}
2299+ holdIncremental = holdIncrementalSpiderEventM
2300+ {-# INLINABLE buildDynamic #-}
2301+ buildDynamic = buildDynamicSpiderEventM
2302+ {-# INLINABLE headE #-}
2303+ headE = R.slowHeadE
2304+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2305+
2306+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2307+ {-# INLINABLE sample #-}
2308+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2309+
2310+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2311+ {-# INLINABLE sample #-}
2312+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2313+
2314+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2315+ {-# INLINABLE hold #-}
2316+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2317+ {-# INLINABLE holdDyn #-}
2318+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2319+ {-# INLINABLE holdIncremental #-}
2320+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2321+ {-# INLINABLE buildDynamic #-}
2322+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2323+ {-# INLINABLE headE #-}
2324+ headE = R.slowHeadE
2325+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2326+
2327+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2328+ {-# INLINE return #-}
2329+ return = pure
2330+ {-# INLINE (>>=) #-}
2331+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2332+ {-# INLINE (>>) #-}
2333+ (>>) = (*>)
2334+ {-# INLINE fail #-}
2335+ fail _ = error "Dynamic does not support 'fail'"
2336+
2337+{-# INLINABLE newJoinDyn #-}
2338+newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2339+newJoinDyn d =
2340+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2341+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2342+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2343+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2344+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2345+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2346+
2347+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2348+ fmap = mapDynamicSpider
2349+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2350+
2351+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2352+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2353+{-# INLINE [1] mapDynamicSpider #-}
2354+
2355+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2356+ pure = SpiderDynamic . dynamicConst
2357+#if MIN_VERSION_base(4,10,0)
2358+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2359+#endif
2360+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2361+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2362+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2363+
2364+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2365+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2366+
2367+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2368+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2369+
2370+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2371+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2372+
2373+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2374+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2375+
2376+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2377+ {-# INLINABLE hold #-}
2378+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2379+ {-# INLINABLE holdDyn #-}
2380+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2381+ {-# INLINABLE holdIncremental #-}
2382+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2383+ {-# INLINABLE buildDynamic #-}
2384+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2385+ {-# INLINABLE headE #-}
2386+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2387+
2388+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2389+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2390+
2391+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2392+ {-# INLINABLE hold #-}
2393+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2394+ {-# INLINABLE holdDyn #-}
2395+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2396+ {-# INLINABLE holdIncremental #-}
2397+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2398+ {-# INLINABLE buildDynamic #-}
2399+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2400+ {-# INLINABLE headE #-}
2401+ headE = R.slowHeadE
2402+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2403+
2404+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2405+ {-# INLINABLE sample #-}
2406+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2407+
2408+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2409+ {-# INLINABLE sample #-}
2410+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2411+
2412+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2413+ {-# INLINABLE hold #-}
2414+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2415+ {-# INLINABLE holdDyn #-}
2416+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2417+ {-# INLINABLE holdIncremental #-}
2418+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2419+ {-# INLINABLE buildDynamic #-}
2420+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2421+ {-# INLINABLE headE #-}
2422+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2423+
2424+--------------------------------------------------------------------------------
2425+-- Deprecated items
2426+--------------------------------------------------------------------------------
2427+
2428+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2429+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2430+type SpiderEnv = SpiderTimeline
2431+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2432+ {-# INLINABLE subscribeEvent #-}
2433+ subscribeEvent e = SpiderHostFrame $ do
2434+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2435+ val <- liftIO $ newIORef Nothing
2436+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2437+ { subscriberPropagate = \a -> do
2438+ liftIO $ writeIORef val $ Just a
2439+ scheduleClear val
2440+ , subscriberInvalidateHeight = \_ -> return ()
2441+ , subscriberRecalculateHeight = \_ -> return ()
2442+ }
2443+ return $ SpiderEventHandle
2444+ { spiderEventHandleSubscription = subscription
2445+ , spiderEventHandleValue = val
2446+ }
2447+
2448+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2449+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2450+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2451+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2452+
2453+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2454+ {-# NOINLINE readEvent #-}
2455+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2456+ result <- readIORef $ spiderEventHandleValue h
2457+ touch h
2458+ return result
2459+
2460+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2461+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2462+ newFanEventWithTrigger f = SpiderHost $ do
2463+ es <- newFanEventWithTriggerIO f
2464+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2465+
2466+instance Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2467+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2468+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2469+ es <- newFanEventWithTriggerIO f
2470+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2471+
2472+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2473+ {-# INLINABLE subscribeEvent #-}
2474+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2475+
2476+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2477+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2478+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2479+ runHostFrame = runFrame . runSpiderHostFrame
2480+
2481+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2482+unsafeNewSpiderTimelineEnv = do
2483+ lock <- newMVar ()
2484+ env <- newEventEnv
2485+#ifdef DEBUG
2486+ depthRef <- newIORef 0
2487+#endif
2488+ return $ SpiderTimelineEnv
2489+ { _spiderTimeline_lock = lock
2490+ , _spiderTimeline_eventEnv = env
2491+#ifdef DEBUG
2492+ , _spiderTimeline_depth = depthRef
2493+#endif
2494+ }
2495+
2496+-- | Create a new SpiderTimelineEnv
2497+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2498+newSpiderTimeline = withSpiderTimeline (pure . Some)
2499+
2500+data LocalSpiderTimeline (x :: Type) s
2501+
2502+instance Reifies s (SpiderTimelineEnv x) =>
2503+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2504+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2505+
2506+localSpiderTimeline
2507+ :: Proxy s
2508+ -> SpiderTimelineEnv x
2509+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2510+localSpiderTimeline _ = unsafeCoerce
2511+
2512+-- | Pass a new timeline to the given function.
2513+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2514+withSpiderTimeline k = do
2515+ env <- unsafeNewSpiderTimelineEnv
2516+ reify env $ \s -> k $ localSpiderTimeline s env
2517+
2518+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2519+
2520+type ComputeM = EventM
2521+
2522+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2523+
2524+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2525+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2526+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2527+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2528+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2529+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2530+ type PullM (SpiderTimeline x) = SpiderPullM x
2531+ type PushM (SpiderTimeline x) = SpiderPushM x
2532+ {-# INLINABLE never #-}
2533+ never = SpiderEvent eventNever
2534+ {-# INLINABLE constant #-}
2535+ constant = SpiderBehavior . behaviorConst
2536+ {-# INLINE push #-}
2537+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2538+ {-# INLINE pushCheap #-}
2539+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2540+ {-# INLINABLE pull #-}
2541+ pull = SpiderBehavior . pull . coerce
2542+ {-# INLINABLE fanG #-}
2543+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2544+ {-# INLINABLE mergeG #-}
2545+ mergeG
2546+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2547+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2548+ -> DMap k q
2549+ -> R.Event (SpiderTimeline x) (DMap k v)
2550+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2551+ {-# INLINABLE switch #-}
2552+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2553+ {-# INLINABLE coincidence #-}
2554+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2555+ {-# INLINABLE current #-}
2556+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2557+ {-# INLINABLE updated #-}
2558+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2559+ {-# INLINABLE unsafeBuildDynamic #-}
2560+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2561+ {-# INLINABLE unsafeBuildIncremental #-}
2562+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2563+ {-# INLINABLE mergeIncrementalG #-}
2564+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2565+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2566+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2567+ {-# INLINABLE currentIncremental #-}
2568+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2569+ {-# INLINABLE updatedIncremental #-}
2570+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2571+ {-# INLINABLE incrementalToDynamic #-}
2572+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2573+ c <- readBehaviorUntracked $ dynamicCurrent i
2574+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2575+ eventCoercion Coercion = Coercion
2576+ behaviorCoercion Coercion = Coercion
2577+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2578+ {-# INLINABLE mergeIntIncremental #-}
2579+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2580+ {-# INLINABLE fanInt #-}
2581+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2582+
2583+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2584+
2585+data SpiderEventHandle x a = SpiderEventHandle
2586+ { spiderEventHandleSubscription :: EventSubscription x
2587+ , spiderEventHandleValue :: IORef (Maybe a)
2588+ }
2589+
2590+instance MonadRef (EventM x) where
2591+ type Ref (EventM x) = Ref IO
2592+ {-# INLINABLE newRef #-}
2593+ {-# INLINABLE readRef #-}
2594+ {-# INLINABLE writeRef #-}
2595+ newRef = liftIO . newRef
2596+ readRef = liftIO . readRef
2597+ writeRef r a = liftIO $ writeRef r a
2598+
2599+instance MonadAtomicRef (EventM x) where
2600+ {-# INLINABLE atomicModifyRef #-}
2601+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2602+
2603+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2604+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2605+
2606+instance Monad (SpiderHost x) where
2607+ {-# INLINABLE (>>=) #-}
2608+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2609+ {-# INLINABLE (>>) #-}
2610+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2611+ {-# INLINABLE return #-}
2612+ return x = SpiderHost $ return x
2613+ {-# INLINABLE fail #-}
2614+ fail s = SpiderHost $ fail s
2615+
2616+-- | Run an action affecting the global Spider timeline; this will be guarded by
2617+-- a mutex for that timeline
2618+runSpiderHost :: SpiderHost Global a -> IO a
2619+runSpiderHost (SpiderHost a) = a
2620+
2621+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2622+-- mutex for that timeline
2623+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2624+runSpiderHostForTimeline (SpiderHost a) _ = a
2625+
2626+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2627+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2628+
2629+instance Monad (SpiderHostFrame x) where
2630+ {-# INLINABLE (>>=) #-}
2631+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2632+ {-# INLINABLE (>>) #-}
2633+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2634+ {-# INLINABLE return #-}
2635+ return x = SpiderHostFrame $ return x
2636+ {-# INLINABLE fail #-}
2637+ fail s = SpiderHostFrame $ fail s
2638+
2639+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2640+ notReadyUntil _ = pure ()
2641+ notReady = pure ()
2642+
2643+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2644+newEventWithTriggerIO f = do
2645+ es <- newFanEventWithTriggerIO $ \Refl -> f
2646+ return $ select es Refl
2647+
2648+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2649+newFanEventWithTriggerIO f = do
2650+ occRef <- newIORef DMap.empty
2651+ subscribedRef <- newIORef DMap.empty
2652+ let !r = Root
2653+ { rootOccurrence = occRef
2654+ , rootSubscribed = subscribedRef
2655+ , rootInit = f
2656+ }
2657+ return $ EventSelector $ \k -> eventRoot k r
2658+
2659+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2660+
2661+instance MonadRef (SpiderHost x) where
2662+ type Ref (SpiderHost x) = Ref IO
2663+ newRef = SpiderHost . newRef
2664+ readRef = SpiderHost . readRef
2665+ writeRef r = SpiderHost . writeRef r
2666+
2667+instance MonadAtomicRef (SpiderHost x) where
2668+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2669+
2670+instance MonadRef (SpiderHostFrame x) where
2671+ type Ref (SpiderHostFrame x) = Ref IO
2672+ newRef = SpiderHostFrame . newRef
2673+ readRef = SpiderHostFrame . readRef
2674+ writeRef r = SpiderHostFrame . writeRef r
2675+
2676+instance MonadAtomicRef (SpiderHostFrame x) where
2677+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2678+
2679+instance PrimMonad (SpiderHostFrame x) where
2680+ type PrimState (SpiderHostFrame x) = PrimState IO
2681+ primitive = SpiderHostFrame . EventM . primitive
src/Reflex/Time.hsnew file+384
@@ -0,0 +1,384 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveGeneric #-}
4+{-# LANGUAGE DeriveTraversable #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE RecursiveDo #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE TupleSections #-}
10+{-# LANGUAGE TypeFamilies #-}
11+#ifdef USE_TEMPLATE_HASKELL
12+{-# LANGUAGE TemplateHaskell #-}
13+#endif
14+-- |
15+-- Module:
16+-- Reflex.Time
17+-- Description:
18+-- Clocks, timers, and other time-related functions.
19+module Reflex.Time where
20+
21+import Reflex.Class
22+import Reflex.Dynamic
23+import Reflex.PerformEvent.Class
24+import Reflex.PostBuild.Class
25+import Reflex.TriggerEvent.Class
26+
27+import Control.Concurrent
28+import qualified Control.Concurrent.Thread.Delay as Concurrent
29+import Control.Lens hiding ((|>))
30+import Control.Monad
31+import Control.Monad.Fix
32+import Control.Monad.IO.Class
33+import Data.Align
34+import Data.Data (Data)
35+import Data.Fixed
36+import Data.Semigroup (Semigroup(..))
37+import Data.Sequence (Seq, (|>))
38+import qualified Data.Sequence as Seq
39+import Data.These
40+import Data.Time.Clock
41+import Data.Typeable
42+import GHC.Generics (Generic)
43+import System.Random
44+
45+-- | Metadata associated with a timer "tick"
46+data TickInfo
47+ = TickInfo { _tickInfo_lastUTC :: UTCTime
48+ -- ^ UTC time immediately after the last tick.
49+ , _tickInfo_n :: Integer
50+ -- ^ Number of time periods or ticks since the start of the timer
51+ , _tickInfo_alreadyElapsed :: NominalDiffTime
52+ -- ^ Amount of time that has elapsed in the current tick period.
53+ }
54+ deriving (Eq, Ord, Show, Typeable)
55+
56+-- | Fires an 'Event' once every time provided interval elapses, approximately.
57+-- The provided 'UTCTime' is used bootstrap the determination of how much time has elapsed with each tick.
58+-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread.
59+tickLossy :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> UTCTime -> m (Event t TickInfo)
60+tickLossy dt t0 = tickLossyFrom dt t0 =<< getPostBuild
61+
62+-- | Fires an 'Event' once every time provided interval elapses, approximately.
63+-- This is a special case of 'tickLossyFrom' that uses the post-build event to start the tick thread and the time of the post-build as the tick basis time.
64+tickLossyFromPostBuildTime :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> m (Event t TickInfo)
65+tickLossyFromPostBuildTime dt = do
66+ postBuild <- getPostBuild
67+ postBuildTime <- performEvent $ liftIO getCurrentTime <$ postBuild
68+ tickLossyFrom' $ (dt,) <$> postBuildTime
69+
70+-- | Fires an 'Event' approximately each time the provided interval elapses. If the system starts running behind, occurrences will be dropped rather than buffered.
71+-- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the provided initial time.
72+tickLossyFrom
73+ :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
74+ => NominalDiffTime
75+ -- ^ The length of a tick interval
76+ -> UTCTime
77+ -- ^ The basis time from which intervals count and with which the initial calculation of elapsed time will be made.
78+ -> Event t a
79+ -- ^ Event that starts a tick generation thread. Usually you want this to
80+ -- be something like the result of getPostBuild that only fires once. But
81+ -- there could be uses for starting multiple timer threads.
82+ -> m (Event t TickInfo)
83+tickLossyFrom dt t0 e = tickLossyFrom' $ (dt, t0) <$ e
84+
85+-- | Generalization of tickLossyFrom that takes the delay and initial time as an 'Event'.
86+tickLossyFrom'
87+ :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
88+ => Event t (NominalDiffTime, UTCTime)
89+ -- ^ Event that starts a tick generation thread. Usually you want this to
90+ -- be something like the result of 'getPostBuild' that only fires once. But
91+ -- there could be uses for starting multiple timer threads.
92+ -> m (Event t TickInfo)
93+tickLossyFrom' e = do
94+ rec result <- performEventAsync $ callAtNextInterval <$> leftmost [e, snd <$> result]
95+ return $ fst <$> result
96+ where callAtNextInterval pair cb = void $ liftIO $ forkIO $ do
97+ tick <- uncurry getCurrentTick pair
98+ Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000
99+ cb (tick, pair)
100+
101+-- | Like 'tickLossy', but immediately calculates the first tick and provides a 'Dynamic' that is updated as ticks fire.
102+clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)
103+clockLossy dt t0 = do
104+ initial <- liftIO $ getCurrentTick dt t0
105+ e <- tickLossy dt t0
106+ holdDyn initial e
107+
108+-- | Generates a 'TickInfo', given the specified interval and timestamp. The 'TickInfo' will include the
109+-- current time, the number of ticks that have elapsed since the timestamp, and the amount of time that
110+-- has elapsed since the start time of this tick.
111+getCurrentTick :: NominalDiffTime -> UTCTime -> IO TickInfo
112+getCurrentTick dt t0 = do
113+ t <- getCurrentTime
114+ let offset = t `diffUTCTime` t0
115+ (n, alreadyElapsed) = offset `divMod'` dt
116+ return $ TickInfo t n alreadyElapsed
117+
118+-- | Delay an Event's occurrences by a given amount in seconds.
119+delay :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
120+delay dt e = performEventAsync $ ffor e $ \a cb -> liftIO $ void $ forkIO $ do
121+ Concurrent.delay $ ceiling $ dt * 1000000
122+ cb a
123+
124+-- | Send events with Poisson timing with the given basis and rate
125+-- Each occurrence of the resulting event will contain the index of
126+-- the current interval, with 0 representing the basis time
127+poissonLossyFrom
128+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
129+ => g
130+ -> Double
131+ -- ^ Poisson event rate (Hz)
132+ -> UTCTime
133+ -- ^ Baseline time for events
134+ -> Event t a
135+ -- ^ Event that starts a tick generation thread. Usually you want this to
136+ -- be something like the result of getPostBuild that only fires once. But
137+ -- there could be uses for starting multiple timer threads.
138+ -- Start sending events in response to the event parameter.
139+ -> m (Event t TickInfo)
140+poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate
141+
142+
143+-- | Send events with Poisson timing with the given basis and rate
144+-- Each occurrence of the resulting event will contain the index of
145+-- the current interval, with 0 representing the basis time.
146+-- Automatically begin sending events when the DOM is built
147+poissonLossy
148+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
149+ => g
150+ -> Double
151+ -- ^ Poisson event rate (Hz)
152+ -> UTCTime
153+ -- ^ Baseline time for events
154+ -> m (Event t TickInfo)
155+poissonLossy rnd rate t0 = poissonLossyFrom rnd rate t0 =<< getPostBuild
156+
157+-- | Send events with inhomogeneous Poisson timing with the given basis
158+-- and variable rate. Provide a maxRate that you expect to support.
159+inhomogeneousPoissonFrom
160+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
161+ => g
162+ -> Behavior t Double
163+ -> Double
164+ -> UTCTime
165+ -> Event t a
166+ -> m (Event t TickInfo)
167+inhomogeneousPoissonFrom rnd rate maxRate t0 e = do
168+
169+ -- Create a thread for producing homogeneous poisson events
170+ -- along with random Doubles (usage of Double's explained below)
171+ ticksWithRateRand <- performEventAsync $
172+ fmap callAtNextInterval e
173+
174+ -- Filter homogeneous events according to associated
175+ -- random values and the current rate parameter
176+ return $ attachWithMaybe filterFun rate ticksWithRateRand
177+
178+ where
179+
180+ -- Inhomogeneous poisson processes are built from faster
181+ -- homogeneous ones by randomly dropping events from the
182+ -- fast process. For each fast homogeneous event, choose
183+ -- a uniform random sample from (0, rMax). If the
184+ -- inhomogeneous rate at this moment is greater than the
185+ -- random sample, then keep this event, otherwise drop it
186+ filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo
187+ filterFun r (tInfo, p)
188+ | r >= p = Just tInfo
189+ | otherwise = Nothing
190+
191+ callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0
192+
193+ go tTargetLast lastGen cb lastN = do
194+ t <- getCurrentTime
195+
196+ -- Generate random numbers for this poisson interval (u)
197+ -- and sample-retention likelihood (p)
198+ let (u, nextGen) = randomR (0,1) lastGen
199+ (p :: Double, nextGen') = randomR (0,maxRate) nextGen
200+
201+ -- Inter-event interval is drawn from exponential
202+ -- distribution accourding to u
203+ let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime
204+ nEvents = lastN + 1
205+ alreadyElapsed = diffUTCTime t tTargetLast
206+ tTarget = addUTCTime dt tTargetLast
207+ thisDelay = realToFrac $ diffUTCTime tTarget t :: Double
208+ Concurrent.delay $ ceiling $ thisDelay * 1000000
209+ _ <- cb (TickInfo t nEvents alreadyElapsed, p)
210+ go tTarget nextGen' cb nEvents
211+
212+-- | Send events with inhomogeneous Poisson timing with the given basis
213+-- and variable rate. Provide a maxRate that you expect to support
214+inhomogeneousPoisson
215+ :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
216+ => g
217+ -> Behavior t Double
218+ -> Double
219+ -> UTCTime
220+ -> m (Event t TickInfo)
221+inhomogeneousPoisson rnd rate maxRate t0 =
222+ inhomogeneousPoissonFrom rnd rate maxRate t0 =<< getPostBuild
223+
224+-- | Block occurrences of an Event until the given number of seconds elapses without
225+-- the Event firing, at which point the last occurrence of the Event will fire.
226+debounce :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
227+debounce dt e = do
228+ n :: Dynamic t Integer <- count e
229+ let tagged = attachPromptlyDynWith (,) n e
230+ delayed <- delay dt tagged
231+ return $ attachWithMaybe (\n' (t, v) -> if n' == t then Just v else Nothing) (current n) delayed
232+
233+-- | When the given 'Event' occurs, wait the given amount of time and collect
234+-- all occurrences during that time. Then, fire the output 'Event' with the
235+-- collected output.
236+batchOccurrences :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t (Seq a))
237+batchOccurrences t newValues = do
238+ let f s x = (Just newState, out)
239+ where newState = case x of
240+ This a -> s |> a
241+ That _ -> mempty
242+ These a _ -> Seq.singleton a
243+ out = case x of
244+ This _ -> if Seq.null s then Just () else Nothing
245+ That _ -> Nothing
246+ These _ _ -> Just ()
247+ rec (buffer, toDelay) <- mapAccumMaybe f mempty $ align newValues delayed
248+ delayed <- delay t toDelay
249+ return $ tag buffer delayed
250+
251+-- | Throttle an input event, ensuring that at least a given amount of time passes between occurrences of the output event. If the input event occurs too
252+-- frequently, the output event occurs with the most recently seen input value after the given delay passes since the last occurrence of the output.
253+-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
254+throttle :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
255+throttle t e = do
256+ let f (immediate, buffer) x = case x of -- (Just newState, out)
257+ This a -- If only the input event fires
258+ | immediate -> -- and we're in immediate mode
259+ -- Immediate mode turns off, and the buffer is empty.
260+ -- We fire the output event with the input event value immediately.
261+ (Just (False, Nothing), Just a)
262+ | otherwise -> -- and we're not in immediate mode
263+ -- Immediate mode remains off, and we replace the contents of the buffer (if any) with the input value.
264+ -- We don't fire the output event.
265+ (Just (False, Just a), Nothing)
266+ That _ -> -- If only the delayed output event fires,
267+ case buffer of
268+ Nothing -> -- and the buffer is empty:
269+ -- Immediate mode turns back on, and the buffer remains empty.
270+ -- We don't fire.
271+ (Just (True, Nothing), Nothing)
272+ Just b -> -- and the buffer is full:
273+ -- Immediate mode remains off, and the buffer is cleared.
274+ -- We fire with the buffered value.
275+ (Just (False, Nothing), Just b)
276+ These a _ -> -- If both the input and delayed output event fire simultaneously:
277+ -- Immediate mode turns off, and the buffer is empty.
278+ -- We fire with the input event's value, as it is the most recent we have seen at this moment.
279+ (Just (False, Nothing), Just a)
280+ rec (_, outE) <- mapAccumMaybeDyn f (True, Nothing) $ align e delayed -- We start in immediate mode with an empty buffer.
281+ delayed <- delay t outE
282+ return outE
283+
284+data ThrottleState b
285+ = ThrottleState_Immediate
286+ | ThrottleState_Buffered (ThrottleBuffer b)
287+ deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
288+
289+data ThrottleBuffer b
290+ = ThrottleBuffer_Empty -- Empty conflicts with lens, and hiding it would require turning
291+ -- on PatternSynonyms
292+ | ThrottleBuffer_Full b
293+ deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data, Typeable)
294+
295+instance Semigroup b => Semigroup (ThrottleBuffer b) where
296+ x <> y = case x of
297+ ThrottleBuffer_Empty -> y
298+ ThrottleBuffer_Full b1 -> case y of
299+ ThrottleBuffer_Empty -> x
300+ ThrottleBuffer_Full b2 -> ThrottleBuffer_Full $ b1 <> b2
301+ {-# INLINE (<>) #-}
302+
303+instance Semigroup b => Monoid (ThrottleBuffer b) where
304+ mempty = ThrottleBuffer_Empty
305+ {-# INLINE mempty #-}
306+ mappend = (<>)
307+ {-# INLINE mappend #-}
308+
309+-- | Throttle an input event, ensuring that the output event doesn't occur more often than you are ready for it. If the input event occurs too
310+-- frequently, the output event will contain semigroup-based summaries of the input firings that happened since the last output firing.
311+-- If the output event has not occurred recently, occurrences of the input event will cause the output event to fire immediately.
312+-- The first parameter is a function that receives access to the output event, and should construct an event that fires when the receiver is
313+-- ready for more input. For example, using @delay 20@ would give a simple time-based throttle.
314+--
315+-- NB: The provided lag function must *actually* delay the event.
316+throttleBatchWithLag :: (MonadFix m, MonadHold t m, PerformEvent t m, Semigroup a) => (Event t () -> m (Event t ())) -> Event t a -> m (Event t a)
317+-- Invariants:
318+-- * Immediate mode must turn off whenever output is produced.
319+-- * Output must be produced whenever immediate mode turns from on to off.
320+-- * Immediate mode can only go from off to on when the delayed event fires.
321+-- * Every input firing must go into either an immediate output firing or the
322+-- buffer, but not both.
323+-- * An existing full buffer must either stay in the buffer or go to output,
324+-- but not both.
325+throttleBatchWithLag lag e = do
326+ let f state x = case x of -- (Just $ newState, out)
327+ This a -> -- If only the input event fires
328+ case state of
329+ ThrottleState_Immediate -> -- and we're in immediate mode
330+ -- Immediate mode turns off, and the buffer is empty.
331+ -- We fire the output event with the input event value immediately.
332+ (Just $ ThrottleState_Buffered $ ThrottleBuffer_Empty, Just a)
333+ ThrottleState_Buffered b -> -- and we're not in immediate mode
334+ -- Immediate mode remains off, and we accumulate the input value.
335+ -- We don't fire the output event.
336+ (Just $ ThrottleState_Buffered $ b <> ThrottleBuffer_Full a, Nothing)
337+ That _ -> -- If only the delayed output event fires,
338+ case state of
339+ ThrottleState_Immediate -> -- and we're in immediate mode
340+ -- Nothing happens.
341+ (Nothing, Nothing)
342+ ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
343+ -- Immediate mode turns back on, and the buffer remains empty.
344+ -- We don't fire.
345+ (Just ThrottleState_Immediate, Nothing)
346+ ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
347+ -- Immediate mode remains off, and the buffer is cleared.
348+ -- We fire with the buffered value.
349+ (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just b)
350+ These a _ -> -- If both the input and delayed output event fire simultaneously:
351+ case state of
352+ ThrottleState_Immediate -> -- and we're in immediate mode
353+ -- Immediate mode turns off, and the buffer is empty.
354+ -- We fire with the input event's value, as it is the most recent we have seen at this moment.
355+ (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
356+ ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:
357+ -- Immediate mode stays off, and the buffer remains empty.
358+ -- We fire with the input event's value.
359+ (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)
360+ ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:
361+ -- Immediate mode remains off, and the buffer is cleared.
362+ -- We fire with everything including the buffered value.
363+ (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just (b <> a))
364+ rec (_stateDyn, outE) <- mapAccumMaybeDyn f
365+ ThrottleState_Immediate -- We start in immediate mode with an empty buffer.
366+ (align e delayed)
367+ delayed <- lag (void outE)
368+ return outE
369+
370+#ifdef USE_TEMPLATE_HASKELL
371+makeLensesWith (lensRules & simpleLenses .~ True) ''TickInfo
372+#else
373+tickInfo_lastUTC :: Lens' TickInfo UTCTime
374+tickInfo_lastUTC f (TickInfo x1 x2 x3) = (\y -> TickInfo y x2 x3) <$> f x1
375+{-# INLINE tickInfo_lastUTC #-}
376+
377+tickInfo_n :: Lens' TickInfo Integer
378+tickInfo_n f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 y x3) <$> f x2
379+{-# INLINE tickInfo_n #-}
380+
381+tickInfo_alreadyElapsed :: Lens' TickInfo NominalDiffTime
382+tickInfo_alreadyElapsed f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 x2 y) <$> f x3
383+{-# INLINE tickInfo_alreadyElapsed #-}
384+#endif
src/Reflex/TriggerEvent/Base.hsnew file+148
@@ -0,0 +1,148 @@
1+-- | This module defines 'TriggerEventT', the standard implementation of
2+-- 'TriggerEvent'.
3+{-# LANGUAGE DeriveFunctor #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE TypeFamilies #-}
8+module Reflex.TriggerEvent.Base
9+ ( TriggerEventT (..)
10+ , runTriggerEventT
11+ , askEvents
12+ , TriggerInvocation (..)
13+ , EventTriggerRef (..)
14+ ) where
15+
16+import Control.Applicative (liftA2)
17+import Control.Concurrent
18+import Control.Monad.Exception
19+import Control.Monad.Primitive
20+import Control.Monad.Reader
21+import Control.Monad.Ref
22+import Data.Coerce
23+import Data.Dependent.Sum
24+import Data.IORef
25+import Data.Monoid ((<>))
26+import qualified Data.Semigroup as S
27+import Reflex.Class
28+import Reflex.Adjustable.Class
29+import Reflex.Host.Class
30+import Reflex.PerformEvent.Class
31+import Reflex.PostBuild.Class
32+import Reflex.TriggerEvent.Class
33+
34+-- | A value with which to fire an 'Event', as well as a callback to invoke
35+-- after its propagation has completed.
36+data TriggerInvocation a = TriggerInvocation a (IO ())
37+
38+-- | A reference to an 'EventTrigger' suitable for firing with 'TriggerEventT'.
39+newtype EventTriggerRef t a = EventTriggerRef { unEventTriggerRef :: IORef (Maybe (EventTrigger t a)) }
40+
41+-- | A basic implementation of 'TriggerEvent'.
42+newtype TriggerEventT t m a = TriggerEventT { unTriggerEventT :: ReaderT (Chan [DSum (EventTriggerRef t) TriggerInvocation]) m a }
43+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
44+
45+-- | Run a 'TriggerEventT' action. The argument should be a 'Chan' into which
46+-- 'TriggerInvocation's can be passed; it is expected that some other thread
47+-- will be responsible for popping values out of the 'Chan' and firing their
48+-- 'EventTrigger's.
49+runTriggerEventT :: TriggerEventT t m a -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a
50+runTriggerEventT = runReaderT . unTriggerEventT
51+
52+instance MonadTrans (TriggerEventT t) where
53+ {-# INLINABLE lift #-}
54+ lift = TriggerEventT . lift
55+
56+instance PrimMonad m => PrimMonad (TriggerEventT t m) where
57+ type PrimState (TriggerEventT t m) = PrimState m
58+ {-# INLINABLE primitive #-}
59+ primitive = lift . primitive
60+
61+instance PerformEvent t m => PerformEvent t (TriggerEventT t m) where
62+ type Performable (TriggerEventT t m) = Performable m
63+ {-# INLINABLE performEvent_ #-}
64+ performEvent_ e = lift $ performEvent_ e
65+ {-# INLINABLE performEvent #-}
66+ performEvent e = lift $ performEvent e
67+
68+instance PostBuild t m => PostBuild t (TriggerEventT t m) where
69+ {-# INLINABLE getPostBuild #-}
70+ getPostBuild = lift getPostBuild
71+
72+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (TriggerEventT t m) where
73+ {-# INLINABLE newEventWithTrigger #-}
74+ newEventWithTrigger = lift . newEventWithTrigger
75+ {-# INLINABLE newFanEventWithTrigger #-}
76+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
77+
78+instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (TriggerEventT t m) where
79+ {-# INLINABLE newTriggerEvent #-}
80+ newTriggerEvent = do
81+ (e, t) <- newTriggerEventWithOnComplete
82+ return (e, \a -> t a $ return ())
83+ {-# INLINABLE newTriggerEventWithOnComplete #-}
84+ newTriggerEventWithOnComplete = do
85+ events <- askEvents
86+ (eResult, reResultTrigger) <- lift newEventWithTriggerRef
87+ return . (,) eResult $ \a cb ->
88+ writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
89+ {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
90+ newEventWithLazyTriggerWithOnComplete f = do
91+ events <- askEvents
92+ lift . newEventWithTrigger $ \t ->
93+ f $ \a cb -> do
94+ reResultTrigger <- newRef $ Just t
95+ writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]
96+
97+instance MonadRef m => MonadRef (TriggerEventT t m) where
98+ type Ref (TriggerEventT t m) = Ref m
99+ {-# INLINABLE newRef #-}
100+ newRef = lift . newRef
101+ {-# INLINABLE readRef #-}
102+ readRef = lift . readRef
103+ {-# INLINABLE writeRef #-}
104+ writeRef r = lift . writeRef r
105+
106+instance MonadAtomicRef m => MonadAtomicRef (TriggerEventT t m) where
107+ {-# INLINABLE atomicModifyRef #-}
108+ atomicModifyRef r = lift . atomicModifyRef r
109+
110+instance MonadSample t m => MonadSample t (TriggerEventT t m) where
111+ {-# INLINABLE sample #-}
112+ sample = lift . sample
113+
114+instance MonadHold t m => MonadHold t (TriggerEventT t m) where
115+ {-# INLINABLE hold #-}
116+ hold v0 v' = lift $ hold v0 v'
117+ {-# INLINABLE holdDyn #-}
118+ holdDyn v0 v' = lift $ holdDyn v0 v'
119+ {-# INLINABLE holdIncremental #-}
120+ holdIncremental v0 v' = lift $ holdIncremental v0 v'
121+ {-# INLINABLE buildDynamic #-}
122+ buildDynamic a0 = lift . buildDynamic a0
123+ {-# INLINABLE headE #-}
124+ headE = lift . headE
125+
126+instance Adjustable t m => Adjustable t (TriggerEventT t m) where
127+ {-# INLINABLE runWithReplace #-}
128+ runWithReplace (TriggerEventT a0) a' = TriggerEventT $ runWithReplace a0 (coerceEvent a')
129+ {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
130+ traverseIntMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseIntMapWithKeyWithAdjust (coerce . f) dm0 dm'
131+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
132+ traverseDMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
133+ {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}
134+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
135+
136+-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
137+instance (Monoid a, Applicative m) => Monoid (TriggerEventT t m a) where
138+ mempty = pure mempty
139+ mappend = (<>)
140+
141+instance (S.Semigroup a, Applicative m) => S.Semigroup (TriggerEventT t m a) where
142+ (<>) = liftA2 (S.<>)
143+
144+
145+-- | Retrieve the current 'Chan'; event trigger invocations pushed into it will
146+-- be fired.
147+askEvents :: Monad m => TriggerEventT t m (Chan [DSum (EventTriggerRef t) TriggerInvocation])
148+askEvents = TriggerEventT ask
src/Reflex/TriggerEvent/Class.hsnew file+50
@@ -0,0 +1,50 @@
1+-- | This module defines 'TriggerEvent', which describes actions that may create
2+-- new 'Event's that can be triggered from 'IO'.
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE FunctionalDependencies #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE UndecidableInstances #-}
7+module Reflex.TriggerEvent.Class
8+ ( TriggerEvent (..)
9+ ) where
10+
11+import Reflex.Class
12+
13+import Control.Monad.Reader
14+import Control.Monad.State
15+import qualified Control.Monad.State.Strict as Strict
16+
17+--TODO: Shouldn't have IO hard-coded
18+-- | 'TriggerEvent' represents actions that can create 'Event's that can be
19+-- triggered by 'IO' actions.
20+class Monad m => TriggerEvent t m | m -> t where
21+ -- | Create a triggerable 'Event'. Whenever the resulting function is called,
22+ -- the resulting 'Event' will fire at some point in the future. Note that
23+ -- this may not be synchronous.
24+ newTriggerEvent :: m (Event t a, a -> IO ())
25+ -- | Like 'newTriggerEvent', but the callback itself takes another callback,
26+ -- to be invoked once the requested 'Event' occurrence has finished firing.
27+ -- This allows synchronous operation.
28+ newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow
29+ -- | Like 'newTriggerEventWithOnComplete', but with setup and teardown. This
30+ -- relatively complex type signature allows any external listeners to be
31+ -- subscribed lazily and then removed whenever the returned 'Event' is no
32+ -- longer being listened to. Note that the setup/teardown may happen multiple
33+ -- times, and there is no guarantee that the teardown will be executed
34+ -- promptly, or even at all, in the case of program termination.
35+ newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)
36+
37+instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
38+ newTriggerEvent = lift newTriggerEvent
39+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
40+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
41+
42+instance TriggerEvent t m => TriggerEvent t (StateT s m) where
43+ newTriggerEvent = lift newTriggerEvent
44+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
45+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
46+
47+instance TriggerEvent t m => TriggerEvent t (Strict.StateT s m) where
48+ newTriggerEvent = lift newTriggerEvent
49+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
50+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
src/Reflex/Widget/Basic.hsnew file+44
@@ -0,0 +1,44 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ExplicitForAll #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE RecursiveDo #-}
5+#ifdef USE_REFLEX_OPTIMIZER
6+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
7+#endif
8+
9+module Reflex.Widget.Basic where
10+
11+import Control.Monad.Fix (MonadFix)
12+import Data.Map (Map)
13+
14+import Reflex.Class
15+import Reflex.Adjustable.Class
16+import Reflex.Patch.MapWithMove
17+
18+
19+-- | Build sortable content in such a way that re-sorting it can cause minimal
20+-- disruption to an existing context.
21+--
22+-- Naively re-sorting a list of images would destroy every image and add them back
23+-- in the new order. This framework is able to avoid that by preserving the
24+-- identity of each image and simply moving it to the new location.
25+--
26+-- Example:
27+--
28+-- > let sortByFst = buttonA $> comparing fst
29+-- > sortBySnd = buttonB $> comparing snd
30+-- > sortEvent = leftmost [sortByFst, sortBySnd]
31+-- > sortableList
32+-- > (\k v -> text $ "\n" ++ show k ++ " " ++ v) -- show each element on a new line
33+-- > (Map.fromList $ zip [0..] [(3, "a"), (2, "b"), (1, "c")])
34+-- > sortEvent
35+sortableList :: forall t m k v a. (MonadHold t m, MonadFix m, Adjustable t m, Ord k)
36+ => (k -> v -> m a) -- ^ Function to render the content for each key/value pair
37+ -> Map k v -- ^ The sortable list with an initial ordering determined by the @Map@ keys in ascending order
38+ -> Event t (v -> v -> Ordering) -- ^ An event carrying a sort function for the list
39+ -> m (Map k a)
40+sortableList f m0 reSortFunc = do
41+ rec let reSortPatch = attachWith (flip patchThatSortsMapWith) (currentIncremental m) reSortFunc
42+ m <- holdIncremental m0 reSortPatch
43+ (results, _) <- mapMapWithAdjustWithMove f m0 reSortPatch
44+ pure results
src/Reflex/Workflow.hsnew file+50
@@ -0,0 +1,50 @@
1+{-# LANGUAGE RecursiveDo #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
3+-- |
4+-- Module:
5+-- Reflex.Workflow
6+-- Description:
7+-- Provides a convenient way to describe a series of interrelated widgets that
8+-- can send data to, invoke, and replace one another. Useful for modeling user interface
9+-- "workflows."
10+module Reflex.Workflow (
11+ Workflow (..)
12+ , workflow
13+ , workflowView
14+ , mapWorkflow
15+ , mapWorkflowCheap
16+ ) where
17+
18+import Control.Arrow ((***))
19+import Control.Monad.Fix (MonadFix)
20+
21+import Reflex.Class
22+import Reflex.Adjustable.Class
23+import Reflex.Network
24+import Reflex.NotReady.Class
25+import Reflex.PostBuild.Class
26+
27+-- | A widget in a workflow
28+-- When the 'Event' returned by a 'Workflow' fires, the current 'Workflow' is replaced by the one inside the firing 'Event'. A series of 'Workflow's must share the same return type.
29+newtype Workflow t m a = Workflow { unWorkflow :: m (a, Event t (Workflow t m a)) }
30+
31+-- | Runs a 'Workflow' and returns the 'Dynamic' result of the 'Workflow' (i.e., a 'Dynamic' of the value produced by the current 'Workflow' node, and whose update 'Event' fires whenever one 'Workflow' is replaced by another).
32+workflow :: forall t m a. (Reflex t, Adjustable t m, MonadFix m, MonadHold t m) => Workflow t m a -> m (Dynamic t a)
33+workflow w0 = do
34+ rec eResult <- networkHold (unWorkflow w0) $ fmap unWorkflow $ switch $ snd <$> current eResult
35+ return $ fmap fst eResult
36+
37+-- | Similar to 'workflow', but outputs an 'Event' that fires whenever the current 'Workflow' is replaced by the next 'Workflow'.
38+workflowView :: forall t m a. (Reflex t, NotReady t m, Adjustable t m, MonadFix m, MonadHold t m, PostBuild t m) => Workflow t m a -> m (Event t a)
39+workflowView w0 = do
40+ rec eResult <- networkView . fmap unWorkflow =<< holdDyn w0 eReplace
41+ eReplace <- fmap switch $ hold never $ fmap snd eResult
42+ return $ fmap fst eResult
43+
44+-- | Map a function over a 'Workflow', possibly changing the return type.
45+mapWorkflow :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
46+mapWorkflow f (Workflow x) = Workflow (fmap (f *** fmap (mapWorkflow f)) x)
47+
48+-- | Map a "cheap" function over a 'Workflow'. Refer to the documentation for 'pushCheap' for more information and performance considerations.
49+mapWorkflowCheap :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
50+mapWorkflowCheap f (Workflow x) = Workflow (fmap (f *** fmapCheap (mapWorkflowCheap f)) x)
test/EventWriterT.hsnew file+134
@@ -0,0 +1,134 @@
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.hsnew file+101
@@ -0,0 +1,101 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE GADTs #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE RankNTypes #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+{-# LANGUAGE TypeFamilies #-}
7+module Main where
8+
9+import Control.Monad
10+import Control.Monad.IO.Class
11+import Control.Monad.Ref
12+import Data.Align
13+import Data.Dependent.Map (DMap)
14+import qualified Data.Dependent.Map as DMap
15+import Data.Dependent.Sum
16+import Data.Functor.Identity
17+import Data.GADT.Compare
18+import Data.IORef
19+import Data.Semigroup
20+import Data.These
21+
22+import Data.Functor.Misc
23+import Reflex.Patch
24+
25+import qualified Reflex.Host.Class as Host
26+import qualified Reflex.Spider.Internal as S
27+
28+import System.Exit
29+import System.Mem
30+import Data.Coerce
31+
32+main :: IO ()
33+main = do
34+ ref <- newIORef Nothing
35+ hostPerf ref
36+ readIORef ref >>= maybe exitFailure (putStrLn . ("Result " <>) . show)
37+
38+hostPerf :: IORef (Maybe Int) -> IO ()
39+hostPerf ref = S.runSpiderHost $ do
40+ ---- body
41+ liftIO $ putStrLn "#creating triggers"
42+ (response', responseTrigger) <- Host.newEventWithTriggerRef
43+ (eadd', addTriggerRef) <- Host.newEventWithTriggerRef
44+ let response = S.unSpiderEvent response'
45+ eadd = S.unSpiderEvent eadd'
46+ liftIO $ putStrLn "#creating event graph"
47+ eventToPerform <- Host.runHostFrame $ do
48+ (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity))
49+ <- S.SpiderHostFrame
50+ $ fmap ( S.mergeG coerce
51+ . S.dynamicHold)
52+ $ S.hold DMap.empty
53+ -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained
54+ $ (\e -> S.Event $ \sub -> do
55+ (s, o) <- S.subscribeAndRead e $ sub
56+ { S.subscriberPropagate = S.subscriberPropagate sub
57+ }
58+ return (s, o))
59+ $ runIdentity . 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.hsnew file+142
@@ -0,0 +1,142 @@
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.hsnew file+369
@@ -0,0 +1,369 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE RankNTypes #-}
7+{-# LANGUAGE RecursiveDo #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE TupleSections #-}
10+{-# LANGUAGE TypeSynonymInstances #-}
11+
12+module Reflex.Bench.Focused where
13+
14+import Reflex
15+import Reflex.TestPlan
16+
17+import Control.Applicative
18+import Control.Monad
19+import Control.Monad.Fix
20+import Control.Monad.Identity
21+import Data.Traversable (for, traverse)
22+
23+import qualified Data.Dependent.Map as DMap
24+import Data.Map (Map)
25+import qualified Data.Map as Map
26+import Data.Maybe
27+
28+import Data.Functor.Misc
29+
30+import Data.List
31+import Data.List.Split
32+import Data.Tuple
33+
34+import Data.Monoid
35+import Data.Word
36+
37+import Control.DeepSeq
38+
39+import Prelude hiding (concat, sum)
40+
41+
42+mergeTree :: Num a => (Monoid (f [a]), Functor f) => Int -> [f a] -> f a
43+mergeTree n es | length es <= n = sum' es
44+ | otherwise = mergeTree n subTrees
45+ where
46+ merges = chunksOf n es
47+ subTrees = map sum' merges
48+ sum' = fmap sum . mconcat . fmap (fmap (:[]) )
49+
50+mergeListDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
51+mergeListDyn = mconcat . fmap (fmap pure)
52+
53+mergeTreeDyn :: (Num a, Reflex t) => Int -> [Dynamic t a] -> Dynamic t a
54+mergeTreeDyn n dyns | length dyns <= n = sumDyns dyns
55+ | otherwise = mergeTreeDyn n $ fmap sumDyns merges
56+ where
57+ merges = chunksOf n dyns
58+ sumDyns = fmap sum . mergeListDyn
59+
60+
61+
62+-- N events all firing for N frames
63+continuous :: TestPlan t m => Word -> Word -> m [Event t Word]
64+continuous n frames = for [1..n] $ \i -> plan $ (, i) <$> [1..frames]
65+
66+-- Fire N events once every P frames for total N frames (interspersed evenly)
67+occasional :: TestPlan t m => Word -> Word -> Word -> m [Event t Word]
68+occasional n period frames = traverse plan $ zipWith occs [1..] phases
69+ where
70+ phases = take (fromIntegral n) $ concat (repeat [1..period])
71+ occs i phase = (, i) <$> [1, phase+1..frames]
72+
73+
74+
75+-- Event which never fires (but isn't 'never')
76+never' :: TestPlan t m => m (Event t Word)
77+never' = plan []
78+
79+
80+-- Event which fires once on first frame
81+event :: TestPlan t m => m (Event t Word)
82+event = plan [(1, 0)]
83+
84+-- Event which fires constantly over N frames
85+events :: TestPlan t m => Word -> m (Event t Word)
86+events n = plan $ (\i -> (i, i)) <$> [1..n]
87+
88+
89+-- N events all originating from one event
90+fmapFan :: Reflex t => Word -> Event t Word -> [Event t Word]
91+fmapFan n e = (\i -> (+i) <$> e) <$> [1..n]
92+
93+
94+-- Make a fan using the value in the event converting it to a singleton Map
95+-- use a fan of size n (key is the value mod n)
96+fanMerge :: Reflex t => Word -> Event t Word -> Event t Word
97+fanMerge n e = leftmost $ s <$> [0..n - 1] where
98+ s k = select f (Const2 k)
99+ f = fan (toMap <$> e)
100+ toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k)
101+
102+-- Dumb version of the above using simple fmapMaybe to filter
103+fmapFanMerge :: Reflex t => Word -> Event t Word -> Event t Word
104+fmapFanMerge n e = leftmost $ s <$> [0..n - 1] where
105+ s k = flip fmapMaybe e $ \j -> if k == j `mod` n
106+ then Just k
107+ else Nothing
108+
109+
110+
111+-- Create an Event with a Map which is dense to size N
112+denseMap :: TestPlan t m => Word -> m (Event t (Map Word Word))
113+denseMap n = plan [(1, m)] where
114+ m = Map.fromList $ zip [1..n] [1..n]
115+
116+iter :: (a -> a) -> Word -> a -> a
117+iter _ 0 a = a
118+iter f n a = iter f (n - 1) (f a)
119+
120+iterM :: Monad m => (a -> m a) -> Word -> a -> m a
121+iterM _ 0 a = return a
122+iterM f n a = iterM f (n - 1) =<< f a
123+
124+fmapChain :: (Functor f) => Word -> f Word -> f Word
125+fmapChain = iter (fmap (+1))
126+
127+mapDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
128+mapDynChain = iterM (return . fmap (+1))
129+
130+joinDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
131+joinDynChain = iterM (\d -> return $ join $ fmap (const d) d)
132+
133+combineDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
134+combineDynChain = iterM (\d -> return $ zipDynWith (+) d d)
135+
136+pingPong :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> Event t a -> m (Event t a)
137+pingPong e1 e2 = do
138+ rec
139+ d <- foldDyn (const swap) (e1, e2) e
140+ let e = switch (fst <$> current d)
141+ return e
142+
143+switchFactors :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
144+switchFactors 0 e = return e
145+switchFactors i e = do
146+ b <- hold ((+1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)
147+ switchFactors (i - 1) (switch b)
148+
149+
150+switchChain :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
151+switchChain = iterM (\e -> pingPong e ((+1) <$> e))
152+
153+
154+switchChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
155+switchChain2 = iterM (\e -> pingPong e ((+1) <$> leftmost [e, e]))
156+
157+switchPromptlyChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
158+switchPromptlyChain = iterM $ \e ->
159+ switchPromptlyDyn <$> holdDyn e (e <$ e)
160+
161+
162+coinChain :: Reflex t => Word -> Event t Word -> Event t Word
163+coinChain = iter $ \e -> coincidence (e <$ e)
164+
165+fanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
166+fanMergeChain width = iter $ fanMerge width
167+
168+fmapFanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
169+fmapFanMergeChain width = iter $ fmapFanMerge width
170+
171+-- | Data type for a collection (a map) which is updated by providing differences
172+data UpdatedMap t k a = UpdatedMap (Map k a) (Event t (Map k (Maybe a)))
173+
174+-- This will hopefully become a primitive (faster!)
175+switchMergeEvents :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
176+switchMergeEvents mapChanges = switch . fmap mergeMap <$> holdMap mapChanges
177+
178+-- switchMergeMaybe :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
179+-- switchMergeMaybe (UpdatedMap initial changes) = switchMergeMap initial (fmap (fromMaybe never) <$> changes)
180+
181+switchMergeBehaviors :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Behavior t a) -> m (Behavior t (Map k a))
182+switchMergeBehaviors mapChanges = pull . joinMap <$> holdMap mapChanges
183+ where joinMap m = traverse sample =<< sample m
184+
185+-- | Turn an UpdatedMap into a Dynamic by applying the differences to the initial value
186+holdMapDyn :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Dynamic t (Map k a))
187+holdMapDyn (UpdatedMap initial changes) = foldDyn (flip (Map.foldrWithKey modify)) initial changes
188+
189+ where
190+ modify k Nothing items = Map.delete k items
191+ modify k (Just item) items = Map.insert k item items
192+
193+
194+-- | Hold an UpdatedMap as a behavior by applying differences to the initial value
195+holdMap :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Behavior t (Map k a))
196+holdMap = (current <$>) . holdMapDyn
197+
198+
199+increasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a)
200+increasingMerge xs = do
201+ e <- planList (zipWith Map.singleton [1..] (Just <$> xs) ++ [reset])
202+ return (UpdatedMap Map.empty e)
203+ where
204+ reset = Map.fromList $ zip [1..] (const Nothing <$> xs)
205+
206+decreasingMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
207+decreasingMerge xs = do
208+ e <- planList (zipWith Map.singleton [1..] (const Nothing <$> xs) ++ [reset])
209+ return (UpdatedMap initial e)
210+ where
211+ initial = Map.fromList $ zip [1..] xs
212+ reset = Just <$> initial
213+
214+modifyMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
215+modifyMerge xs = do
216+ e <- planList $ zipWith Map.singleton [1..] (Just <$> xs)
217+ return (UpdatedMap initial e)
218+ where
219+ initial = Map.fromList $ zip [1..] xs
220+
221+
222+countMany :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Behavior t Int]
223+countMany = traverse (fmap current . count)
224+
225+countManyDyn :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Dynamic t Int]
226+countManyDyn = traverse count
227+
228+
229+-- Given a function which creates a sub-network (from a single event)
230+-- Create a plan which uses a switch to substitute it
231+switches :: TestPlan t m => Word -> (forall n. (MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> m (Event t a)
232+switches numFrames f = do
233+ es <- events numFrames
234+ switch <$> hold never (makeEvents es)
235+
236+ where
237+ makeEvents es = pushAlways (\n -> f (fmap (+n) es)) es
238+
239+
240+
241+-- Two sets of benchmarks, one which we're interested in testing subscribe time (as well as time to fire frames)
242+-- the other, which we're only interested in time for running frames
243+subscribing :: Word -> Word -> [(String, TestCase)]
244+subscribing n frames =
245+ [ testSub "fmapFanMerge" $ return . mergeList . fmapFan n
246+ , testSub "fanMerge" $ return . fanMerge n
247+ , testSub "fmapFan/mergeTree" $ return . mergeTree 8 . fmapFan n
248+ , testSub "fmapChain" $ return . fmapChain n
249+ , testSub "switchChain" $ switchChain n
250+ , testSub "switchPromptlyChain" $ switchPromptlyChain n
251+ , testSub "switchFactors" $ switchFactors n
252+ , testSub "coincidenceChain" $ return . coinChain n
253+ ]
254+
255+ where
256+ testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)
257+ testSub name test = testE name (switches frames test)
258+
259+-- Set of benchmark to test specifically merging dynamic collections
260+-- a pattern which occurs frequently in reflex-dom collections
261+merging :: Word -> [(String, TestCase)]
262+merging n =
263+ [ testE "static events" $ mergeList <$> sparse
264+ , testE "increasing events" $ switchMergeEvents =<< increasingMerge =<< sparse
265+ , testE "decreasing events" $ switchMergeEvents =<< decreasingMerge =<< sparse
266+ , testE "modify events" $ switchMergeEvents =<< modifyMerge =<< sparse
267+
268+ , testB "static behaviors" $ pull . traverse sample <$> counters
269+ , testB "increasing behaviors" $ switchMergeBehaviors =<< increasingMerge =<< counters
270+ , testB "decreasing behaviors" $ switchMergeBehaviors =<< decreasingMerge =<< counters
271+ , testB "modify behaviors" $ switchMergeBehaviors =<< modifyMerge =<< counters
272+
273+
274+ -- , testE "increasing events/switchMerge" $ switchMergeMaybe =<< increasingMerge =<< sparse
275+ -- , testE "decreasing events/switchMerge" $ switchMergeMaybe =<< decreasingMerge =<< sparse
276+ -- , testE "modify events/switchMerge" $ switchMergeMaybe =<< modifyMerge =<< sparse
277+ ]
278+
279+ where
280+ sparse :: TestPlan t m => m [Event t Word]
281+ sparse = fmap (fmap (+1)) <$> occasional n 8 n
282+
283+ counters :: TestPlan t m => m [Behavior t Int]
284+ counters = countMany =<< sparse
285+
286+
287+
288+fans :: Word -> [(String, TestCase)]
289+fans n =
290+ [ testE "fanMapChain" $ fanMergeChain n 10 <$> e
291+ , testE "fmapFanMapChain" $ fmapFanMergeChain n 10 <$> e
292+
293+ , testE "fanMerge " $ fanMerge n <$> events n
294+
295+ , testE "fmapFanMerge " $ fmapFanMerge n <$> events n
296+ , testE "triggerMerge" $ leftmost <$> for [1..n] (\i -> plan [(i, i)])
297+
298+ ]
299+ where
300+
301+ e :: TestPlan t m => m (Event t Word)
302+ e = events 100
303+
304+
305+
306+
307+dynamics :: Word -> [(String, TestCase)]
308+dynamics n =
309+ [ testE "mapDynChain" $ fmap updated $ mapDynChain n =<< d
310+ , testE "joinDynChain" $ fmap updated $ joinDynChain n =<< d
311+ , testE "combineDynChain" $ fmap updated $ combineDynChain n =<< d
312+ , testE "dense mergeTree" $ fmap (updated . mergeTreeDyn 8) dense
313+ , testE "sparse mergeTree" $ fmap (updated . mergeTreeDyn 8) sparse
314+ , testE "mergeDyn" $ fmap (updated . fmap sum . mergeListDyn) sparse
315+ ] where
316+
317+ d :: TestPlan t m => m (Dynamic t Word)
318+ d = count =<< events 10
319+
320+ sparse, dense :: TestPlan t m => m [Dynamic t Int]
321+ sparse = countManyDyn =<< occasional n 8 16
322+ dense = countManyDyn =<< continuous n 2
323+
324+
325+firing :: Word -> [(String, TestCase)]
326+firing n =
327+ [ testE "fmapChain" $ fmapChain n <$> e
328+ , testE "switchChain2" $ switchChain2 n =<< e
329+ , testE "switchPromptlyChain" $ switchPromptlyChain n =<< e
330+ , testE "switchFactors" $ switchFactors n =<< e
331+ , testE "coincidenceChain" $ coinChain n <$> e
332+
333+ , testE "dense mergeTree" $ mergeTree 8 <$> dense
334+ , testE "sparse mergeTree" $ mergeTree 8 <$> sparse
335+
336+ -- Triggers test failure in Spider
337+ --, testE "runFrame" $ events n
338+
339+ , testB "sum counters" $ do
340+ counts <- counters
341+ return $ pull $ sum <$> traverse sample counts
342+
343+ , testB "pullChain" $ fmapChain n . current <$> (count =<< events 4)
344+ , testB "pullChain2" $ do
345+ es <- events 4
346+ e' <- plan [(0, ())]
347+
348+ b <- hold (constant 0) $
349+ pushAlways (const $ fmapChain n <$> hold 0 es) e'
350+
351+ return (join b)
352+ , testB "counters/pullTree" $ mergeTree 8 <$> counters
353+
354+ ]
355+ where
356+ e :: TestPlan t m => m (Event t Word)
357+ e = events 10
358+
359+ dense, sparse :: TestPlan t m => m [Event t Word]
360+ dense = continuous n 2
361+ sparse = occasional n 8 16
362+
363+ counters :: TestPlan t m => m [Behavior t Int]
364+ counters = countMany =<< sparse
365+
366+
367+
368+
369+
test/Reflex/Plan/Pure.hsnew file+72
@@ -0,0 +1,72 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE GADTs #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE RankNTypes #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+
9+module Reflex.Plan.Pure where
10+
11+import Reflex
12+import Reflex.Pure
13+import Reflex.TestPlan
14+
15+import Control.Applicative
16+import Control.Monad.Fix
17+import Control.Monad.State
18+import Data.IntMap (IntMap)
19+import qualified Data.IntMap as IntMap
20+import Data.IntSet (IntSet)
21+import qualified Data.IntSet as IntSet
22+
23+import Data.Bifunctor
24+import Data.Maybe
25+import Data.Monoid
26+import Prelude
27+
28+
29+mapToPureEvent :: IntMap a -> Event (Pure Int) a
30+mapToPureEvent m = Event $ flip IntMap.lookup m
31+
32+type TimeM = (->) Int
33+newtype PurePlan a = PurePlan { unPlan :: StateT IntSet TimeM a } deriving (Functor, Applicative, Monad, MonadFix)
34+
35+liftPlan :: TimeM a -> PurePlan a
36+liftPlan = PurePlan . lift
37+
38+instance MonadHold (Pure Int) PurePlan where
39+ hold initial = liftPlan . hold initial
40+ holdDyn initial = liftPlan . holdDyn initial
41+ holdIncremental initial = liftPlan . holdIncremental initial
42+ buildDynamic getInitial = liftPlan . buildDynamic getInitial
43+ headE = liftPlan . headE
44+
45+instance MonadSample (Pure Int) PurePlan where
46+ sample = liftPlan . sample
47+
48+
49+instance TestPlan (Pure Int) PurePlan where
50+ plan occs = do
51+ PurePlan . modify $ IntSet.union (IntMap.keysSet m)
52+ return $ mapToPureEvent m
53+ where m = IntMap.fromList (first fromIntegral <$> occs)
54+
55+runPure :: PurePlan a -> (a, IntSet)
56+runPure (PurePlan p) = runStateT p mempty $ 0
57+
58+relevantTimes :: IntSet -> IntSet
59+relevantTimes occs = IntSet.fromList [0..l + 1]
60+ where l = fromMaybe 0 (fst <$> IntSet.maxView occs)
61+
62+testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a
63+testBehavior (b, occs) = IntMap.fromSet (sample b) (relevantTimes occs)
64+
65+testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a)
66+testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relevantTimes occs)
67+
68+
69+
70+
71+
72+
test/Reflex/Plan/Reflex.hsnew file+135
@@ -0,0 +1,135 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE RankNTypes #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE StandaloneDeriving #-}
10+{-# LANGUAGE UndecidableInstances #-}
11+module Reflex.Plan.Reflex
12+ ( TestPlan(..)
13+ , runPlan
14+ , Plan (..)
15+ , Schedule
16+ , Firing (..)
17+ , MonadIORef
18+
19+
20+ , readSchedule
21+ , readSchedule_
22+ , testSchedule
23+ , readEvent'
24+ , makeDense
25+
26+ , runTestE
27+ , runTestB
28+
29+ ) where
30+
31+import Reflex.Class
32+import Reflex.Host.Class
33+import Reflex.TestPlan
34+
35+import Control.Applicative
36+import Control.Monad
37+import Control.Monad.Identity
38+import Control.Monad.State.Strict
39+
40+import Control.Monad.Ref
41+import Data.Dependent.Sum (DSum (..))
42+import qualified Data.IntMap.Strict as IntMap
43+import Data.Maybe
44+import Data.Monoid
45+import Data.Traversable (sequenceA, traverse)
46+
47+import Control.DeepSeq
48+import Control.Exception
49+import Data.IntMap.Strict (IntMap)
50+import Data.IORef
51+import System.Mem
52+
53+-- Note: this import must come last to silence warnings from AMP
54+import Prelude
55+
56+type MonadIORef m = (MonadIO m, MonadRef m, Ref m ~ Ref IO)
57+
58+data Firing t where
59+ Firing :: IORef (Maybe (EventTrigger t a)) -> a -> Firing t
60+
61+
62+type Schedule t = IntMap [Firing t]
63+
64+-- Implementation of a TestPlan in terms of ReflexHost
65+newtype Plan t a = Plan (StateT (Schedule t) (HostFrame t) a)
66+
67+deriving instance ReflexHost t => Functor (Plan t)
68+deriving instance ReflexHost t => Applicative (Plan t)
69+deriving instance ReflexHost t => Monad (Plan t)
70+
71+deriving instance ReflexHost t => MonadSample t (Plan t)
72+deriving instance ReflexHost t => MonadHold t (Plan t)
73+deriving instance ReflexHost t => MonadFix (Plan t)
74+
75+
76+instance (ReflexHost t, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => TestPlan t (Plan t) where
77+ plan occurrences = Plan $ do
78+ (e, ref) <- newEventWithTriggerRef
79+ modify (IntMap.unionWith mappend (firings ref))
80+ return e
81+
82+ where
83+ firings ref = IntMap.fromList (makeFiring ref <$> occurrences)
84+ makeFiring ref (t, a) = (fromIntegral t, [Firing ref a])
85+
86+
87+firingTrigger :: (MonadReflexHost t m, MonadIORef m) => Firing t -> m (Maybe (DSum (EventTrigger t) Identity))
88+firingTrigger (Firing ref a) = fmap (:=> Identity a) <$> readRef ref
89+
90+runPlan :: (MonadReflexHost t m) => Plan t a -> m (a, Schedule t)
91+runPlan (Plan p) = runHostFrame $ runStateT p mempty
92+
93+
94+makeDense :: Schedule t -> Schedule t
95+makeDense s = fromMaybe (emptyRange 0) $ do
96+ (end, _) <- fst <$> IntMap.maxViewWithKey s
97+ return $ IntMap.union s (emptyRange end)
98+ where
99+ emptyRange end = IntMap.fromList (zip [0..end + 1] (repeat []))
100+
101+
102+-- For the purposes of testing, we add in a zero frame and extend one frame (to observe changes to behaviors
103+-- after the last event)
104+-- performGC is called at each frame to test for GC issues
105+testSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
106+testSchedule schedule readResult = IntMap.traverseWithKey (\t occs -> liftIO performGC *> triggerFrame readResult t occs) (makeDense schedule)
107+
108+readSchedule :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m (IntMap a)
109+readSchedule schedule readResult = IntMap.traverseWithKey (triggerFrame readResult) schedule
110+
111+readSchedule_ :: (MonadReflexHost t m, MonadIORef m, NFData a) => Schedule t -> ReadPhase m a -> m ()
112+readSchedule_ schedule readResult = mapM_ (uncurry $ triggerFrame readResult) $ IntMap.toList schedule
113+
114+triggerFrame :: (MonadReflexHost t m, MonadIORef m, NFData a) => ReadPhase m a -> Int -> [Firing t] -> m a
115+triggerFrame readResult _ occs = do
116+ triggers <- catMaybes <$> traverse firingTrigger occs
117+ liftIO . evaluate . force =<< fireEventsAndRead triggers readResult
118+
119+readEvent' :: MonadReadEvent t m => EventHandle t a -> m (Maybe a)
120+readEvent' = readEvent >=> sequenceA
121+
122+
123+-- Convenience functions for running tests producing Events/Behaviors
124+runTestB :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Behavior t a) -> m (IntMap a)
125+runTestB p = do
126+ (b, s) <- runPlan p
127+ testSchedule s $ sample b
128+
129+runTestE :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Event t a) -> m (IntMap (Maybe a))
130+runTestE p = do
131+ (e, s) <- runPlan p
132+ h <- subscribeEvent e
133+ testSchedule s (readEvent' h)
134+
135+
test/Reflex/Test.hsnew file+66
@@ -0,0 +1,66 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE RankNTypes #-}
7+
8+module Reflex.Test
9+ ( testAgreement
10+ , compareResult
11+ , runTests
12+
13+ , module Reflex.TestPlan
14+
15+ ) where
16+
17+import Reflex.Spider
18+
19+import Reflex.TestPlan
20+
21+import Reflex.Plan.Pure
22+import Reflex.Plan.Reflex
23+
24+import Control.Monad
25+import Data.Monoid
26+
27+import Data.IntMap (IntMap)
28+
29+--import Data.Foldable
30+import System.Exit
31+
32+import Prelude
33+
34+
35+testAgreement :: TestCase -> IO Bool
36+testAgreement (TestE p) = do
37+ spider <- runSpiderHost $ runTestE p
38+ let results = [("spider", spider)]
39+
40+ compareResult results (testEvent $ runPure p)
41+
42+testAgreement (TestB p) = do
43+ spider <- runSpiderHost $ runTestB p
44+ let results = [("spider", spider)]
45+
46+ compareResult results (testBehavior $ runPure p)
47+
48+
49+compareResult :: (Show a, Eq a) => [(String, IntMap a)] -> IntMap a -> IO Bool
50+compareResult results expected = fmap and $ forM results $ \(name, r) -> do
51+
52+ when (r /= expected) $ do
53+ putStrLn ("Got: " ++ show (name, r))
54+ putStrLn ("Expected: " ++ show expected)
55+ return (r == expected)
56+
57+
58+runTests :: [(String, TestCase)] -> IO ()
59+runTests testCases = do
60+ results <- forM testCases $ \(name, test) -> do
61+ putStrLn $ "Test: " <> name
62+ testAgreement test
63+ exitWith $ if and results
64+ then ExitSuccess
65+ else ExitFailure 1
66+
test/Reflex/Test/CrossImpl.hsnew file+257
@@ -0,0 +1,257 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE ExistentialQuantification #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE FunctionalDependencies #-}
6+{-# LANGUAGE GADTs #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE NoMonomorphismRestriction #-}
9+{-# LANGUAGE RankNTypes #-}
10+{-# LANGUAGE RecursiveDo #-}
11+{-# LANGUAGE ScopedTypeVariables #-}
12+{-# LANGUAGE TypeFamilies #-}
13+{-# LANGUAGE TypeOperators #-}
14+{-# LANGUAGE UndecidableInstances #-}
15+
16+import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_)
17+
18+import Control.Monad.Ref
19+import Reflex.Class
20+import Reflex.Dynamic
21+import Reflex.Host.Class
22+import qualified Reflex.Pure as P
23+import qualified Reflex.Spider.Internal as S
24+
25+import Control.Arrow (second, (&&&))
26+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
27+import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
28+import Data.Dependent.Map (DSum (..))
29+import Data.Foldable
30+import Data.Map.Strict (Map)
31+import qualified Data.Map.Strict as Map
32+import qualified Data.Set as Set
33+import Data.Monoid
34+import Data.Traversable
35+import System.Exit
36+import System.Mem
37+
38+import System.IO.Unsafe
39+
40+mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a
41+mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of
42+ Nothing -> error $ "mapToPureBehavior: no value for time " <> show t
43+ Just (_, v) -> v
44+
45+mapToPureEvent :: Map Int a -> Event PureReflexDomain a
46+mapToPureEvent m = P.Event $ flip Map.lookup m
47+
48+relevantTestingTimes :: (Map Int a, Map Int b) -> [Int]
49+relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of
50+ (Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event
51+ _ -> [] -- Doesn't actually make much sense
52+
53+type PureReflexDomain = P.Pure Int
54+type TimeM = (->) Int
55+
56+testPure :: (t ~ PureReflexDomain, m ~ TimeM) => ((Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
57+testPure builder (b, e) =
58+ let (P.Behavior b', P.Event e') = ($ 0) $ builder (mapToPureBehavior b, mapToPureEvent e)
59+ relevantTimes = relevantTestingTimes (b, e)
60+ e'' = Map.mapMaybe id $ Map.fromList $ map (id &&& e') relevantTimes
61+ b'' = Map.fromList $ map (id &&& b') relevantTimes
62+ in (b'', e'')
63+
64+class MapMSignals a a' t t' | a -> t, a' -> t', a t' -> a', a' t -> a where
65+ mapMSignals :: Monad m => (forall b. Behavior t b -> m (Behavior t' b)) -> (forall b. Event t b -> m (Event t' b)) -> a -> m a'
66+
67+instance MapMSignals (Behavior t a) (Behavior t' a) t t' where
68+ mapMSignals fb _ = fb
69+
70+instance MapMSignals (Event t a) (Event t' a) t t' where
71+ mapMSignals _ fe = fe
72+
73+instance (MapMSignals a a' t t', MapMSignals b b' t t') => MapMSignals (a, b) (a', b') t t' where
74+ mapMSignals fb fe (a, b) = liftM2 (,) (mapMSignals fb fe a) (mapMSignals fb fe b)
75+
76+testSpider :: (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
77+testSpider builder (bMap, eMap) = unsafePerformIO $ S.runSpiderHost $ do
78+ (re, reTrigger) <- newEventWithTriggerRef
79+ (rb, rbTrigger) <- newEventWithTriggerRef
80+ b <- runHostFrame $ hold (error "testSpider: No value for input behavior yet") rb
81+ (b', e') <- runHostFrame $ builder (b, re)
82+ e'Handle <- subscribeEvent e' --TODO: This should be unnecessary
83+ let times = relevantTestingTimes (bMap, eMap)
84+ liftIO performGC
85+ outputs <- forM times $ \t -> do
86+ forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger
87+ bOutput <- sample b'
88+ eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do
89+ mret <- readRef reTrigger
90+ let firing = case mret of
91+ Just ret -> [ret :=> Identity val]
92+ Nothing -> []
93+ fireEventsAndRead firing $ sequence =<< readEvent e'Handle
94+ liftIO performGC
95+ return (t, (bOutput, eOutput))
96+ return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)
97+
98+tracePerf :: Show a => a -> b -> b
99+tracePerf = flip const
100+
101+testAgreement :: (Eq c, Eq d, Show c, Show d) => (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> IO Bool
102+testAgreement builder inputs = do
103+ let identityResult = testPure builder inputs
104+ tracePerf "---------" $ return ()
105+ let spiderResult = testSpider builder inputs
106+ tracePerf "---------" $ return ()
107+ let resultsAgree = identityResult == spiderResult
108+ if resultsAgree
109+ then do --putStrLn "Success:"
110+ --print identityResult
111+ return ()
112+ else do putStrLn "Failure:"
113+ putStrLn $ "Pure result: " <> show identityResult
114+ putStrLn $ "Spider result: " <> show spiderResult
115+ return resultsAgree
116+
117+type TestCaseConstraint t m = (Reflex t, MonadSample t m, MonadHold t m, MonadFix m, MonadFix (PushM t))
118+
119+data TestCase = forall a b c d. (Eq c, Eq d, Show c, Show d) => TestCase (Map Int a, Map Int b) (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d))
120+
121+testCases :: [(String, TestCase)]
122+testCases =
123+ [ (,) "hold" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
124+ b' <- hold "123" e
125+ return (b', e)
126+ , (,) "count" $ TestCase (Map.singleton 0 (), Map.fromList [(1, ()), (2, ()), (3, ())]) $ \(_, e) -> do
127+ e' <- updated <$> count e
128+ b' <- hold (0 :: Int) e'
129+ return (b', e')
130+ , (,) "headE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
131+ e' <- headE $ leftmost [e, e]
132+ return (b, e')
133+ , (,) "switch-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
134+ let e' = fmap (const e) e
135+ b' <- hold never e'
136+ let e'' = switch b'
137+ return (b, e'')
138+ , (,) "switch-2" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
139+ let e' = flip pushAlways e $ const $ do
140+ let eab = splitRecombineEvent e
141+ switch <$> hold eab never
142+ e'' = coincidence e'
143+ return (b, e'')
144+ , (,) "switch-3" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
145+ let e' = flip pushAlways e $ const $ do
146+ let eab = splitRecombineEvent e
147+ switch <$> hold eab (fmap (const e) e)
148+ e'' = coincidence e'
149+ return (b, e'')
150+ , (,) "switch-4" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
151+ let e' = leftmost [e, e]
152+ e'' <- switch <$> hold e' (fmap (const e) e)
153+ return (b, e'')
154+ , (,) "switchHoldPromptly-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
155+ let e' = fmap (const e) e
156+ e'' <- switchHoldPromptly never e'
157+ return (b, e'')
158+ , (,) "switchHoldPromptly-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
159+ let e' = fmap (const e) e
160+ e'' <- switchHoldPromptly never $ leftmost [e', e']
161+ return (b, e'')
162+ , (,) "switchHoldPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
163+ let e' = leftmost [e, e]
164+ e'' <- switchHoldPromptly never (fmap (const e) e')
165+ return (b, e'')
166+ , (,) "switchHoldPromptly-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
167+ let e' = leftmost [e, e]
168+ e'' <- switchHoldPromptly never (fmap (const e') e)
169+ return (b, e'')
170+ , (,) "switch-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
171+ let e' = leftmost [e, e]
172+ e'' <- switch <$> hold never (fmap (const e') e)
173+ return (b, e'')
174+ , (,) "switchHoldPromptly-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
175+ let e' = flip push e $ \_ -> do
176+ Just <$> headE e
177+ e'' <- switchHoldPromptly never e'
178+ return (b, e'')
179+ , (,) "switchHoldPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
180+ let e' = flip pushAlways e $ \_ -> do
181+ switchHoldPromptly e never
182+ e'' <- switchHoldPromptly never e'
183+ return (b, e'')
184+ , (,) "coincidence-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
185+ let e' = flip pushAlways e $ \_ -> return e
186+ e'' = coincidence e'
187+ return (b, e'')
188+ , (,) "coincidence-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
189+ let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]
190+ e'' = coincidence e'
191+ return (b, e'')
192+ , (,) "coincidence-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
193+ let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e
194+ e'' = coincidence e'
195+ return (b, e'')
196+ , (,) "coincidence-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
197+ let e' = flip pushAlways e $ \_ -> headE e
198+ e'' = coincidence e'
199+ return (b, e'')
200+ , (,) "coincidence-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
201+ let eChild = flip pushAlways e $ const $ do
202+ let eNewValues = leftmost [e, e]
203+ return $ coincidence $ fmap (const eNewValues) eNewValues
204+ e' = coincidence eChild
205+ return (b, e')
206+ , (,) "coincidence-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
207+ let eChild = flip pushAlways e $ const $ do
208+ let e' = coincidence $ fmap (const e) e
209+ return $ leftmost [e', e']
210+ e'' = coincidence eChild
211+ return (b, e'')
212+ , (,) "coincidence-7" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
213+ let e' = leftmost [e, e]
214+ eCoincidences = coincidence $ fmap (const e') e
215+ return (b, eCoincidences)
216+ , (,) "holdWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
217+ eo <- headE e
218+ bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo
219+ let b' = pull $ sample =<< sample bb
220+ return (b', e)
221+ , (,) "joinDyn" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
222+ bb <- hold "b" e
223+ bd <- hold never . fmap (const e) =<< headE e
224+ eOuter <- pushAlways sample . fmap (const bb) <$> headE e
225+ let eInner = switch bd
226+ e' = leftmost [eOuter, eInner]
227+ return (b, e')
228+ , (,) "holdUniqDyn-laziness" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList (zip [1 :: Int ..] [1 :: Int, 2, 2, 3, 3, 3, 4, 4, 4, 4])) $ \(_, e :: Event t Int) -> do
229+ rec result <- holdUniqDyn d
230+ d <- holdDyn (0 :: Int) e
231+ return (current result, updated result)
232+
233+
234+
235+ {-
236+ , (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do
237+ x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e
238+ let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)
239+ return (b, e')
240+ -}
241+ ]
242+
243+splitRecombineEvent :: Reflex t => Event t a -> Event t String
244+splitRecombineEvent e =
245+ let ea = "a" <$ e
246+ eb = "b" <$ e
247+ in leftmost [ea, eb]
248+
249+
250+main :: IO ()
251+main = do
252+ results <- forM testCases $ \(name, TestCase inputs builder) -> do
253+ putStrLn $ "Test: " <> name
254+ testAgreement builder inputs
255+ exitWith $ if and results
256+ then ExitSuccess
257+ else ExitFailure 1
test/Reflex/Test/Micro.hsnew file+346
@@ -0,0 +1,346 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE RankNTypes #-}
9+{-# LANGUAGE RecursiveDo #-}
10+
11+module Reflex.Test.Micro (testCases) where
12+
13+import Reflex
14+import Reflex.TestPlan
15+
16+import Control.Applicative
17+import Control.Monad
18+import Control.Monad.Fix
19+import Data.Char
20+import Data.Foldable
21+import Data.Functor.Misc
22+import qualified Data.Map as Map
23+import Data.Monoid
24+
25+import Prelude
26+
27+pushDyn :: (Reflex t, MonadHold t m) => (a -> PushM t b) -> Dynamic t a -> m (Dynamic t b)
28+pushDyn f d = buildDynamic (sample (current d) >>= f) (pushAlways f (updated d))
29+
30+foldedDyn :: (Reflex t, MonadHold t m) => (a -> a -> a) -> Dynamic t a -> m (Dynamic t a)
31+foldedDyn f d = fmap join $ flip buildDynamic never $ do
32+ a <- sample (current d)
33+ foldDyn f a (updated d)
34+
35+scannedDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> m (Dynamic t [a])
36+scannedDyn = fmap (fmap reverse) . foldedDyn (<>) . fmap pure
37+
38+scanInnerDyns :: (Reflex t, MonadHold t m) => Dynamic t (Dynamic t a) -> m (Dynamic t [a])
39+scanInnerDyns d = do
40+ scans <- scannedDyn d
41+ return (join (fmap distributeListOverDynPure scans))
42+
43+
44+
45+{-# ANN testCases "HLint: ignore Functor law" #-}
46+testCases :: [(String, TestCase)]
47+testCases =
48+ [ testB "hold" $ hold "0" =<< events1
49+
50+ , testB "count" $ do
51+ b <- current <$> (count =<< events2)
52+ return $ (+ (0::Int)) <$> b
53+
54+ , testB "pull-1" $ do
55+ b <- hold "0" =<< events1
56+ return (pull $ sample $ pull $ sample b)
57+
58+ , testB "pull-2" $ do
59+ b1 <- behavior1
60+ return (pull $ liftA2 (<>) (sample b1) (sample b1))
61+
62+ , testB "pull-3" $ do
63+ b1 <- behavior1
64+ b2 <- behavior2
65+ return (pull $ liftA2 (<>) (sample b1) (sample b2))
66+
67+ , testB "pull-4" $ do
68+ es <- planList ["a", "b", "c"]
69+ e <- plan [(0, ())]
70+ b <- hold (constant "") $
71+ pushAlways (const $ hold "z" es) e
72+ return (join b)
73+
74+ , testE "id" $ do
75+ events2
76+
77+ , testE "fmap-id" $ do
78+ e <- events2
79+ return $ fmap id e
80+
81+ , testE "tag-1" $ do
82+ b1 <- behavior1
83+ e <- events2
84+ return (tag b1 e)
85+
86+ , testE "tag-2" $ do
87+ b1 <- behavior1
88+ e <- events2
89+ return (tag (map toUpper <$> b1) e)
90+
91+ , testE "attach-1" $ do
92+ b1 <- behavior1
93+ e <- events2
94+ return (attachWith (++) (map toUpper <$> b1) e)
95+
96+ , testE "leftmost" $ liftA2 leftmost2 events1 events2
97+
98+ , testE "appendEvents-1" $ liftA2 mappend events1 events2
99+
100+ , testE "appendEvents-2" $ liftA2 mappend events3 events2
101+
102+ , testE "merge-1" $ do
103+ e <- events1
104+ return $ leftmost ["x" <$ e, "y" <$ e]
105+
106+ , testE "merge-2" $ do
107+ e <- events1
108+ let m = mergeMap $ Map.fromList [(1::Int, "y" <$ e), (2, "z" <$ e)]
109+ let ee = flip pushAlways e $ const $ return m
110+ return $ coincidence ee
111+
112+ , testE "headE-1" $ do
113+ e <- events1
114+ headE $ leftmost [e, e]
115+
116+ , testE "headE-2" $ do
117+ e <- events1
118+ b <- hold never (e <$ e)
119+ headE $ switch b
120+
121+ , testE "switch-1" $ do
122+ e <- events1
123+ b <- hold never (e <$ e)
124+ return $ switch b
125+
126+ , testE "switch-2" $ do
127+ e <- events1
128+ return $ coincidence $ flip pushAlways e $ const $ do
129+ switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) (e <$ e)
130+
131+ , testE "switch-3" $ do
132+ e <- events1
133+ return $ coincidence $ flip pushAlways e $ const $ do
134+ switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) never
135+
136+ , testE "switch-4" $ do
137+ e <- events1
138+ switch <$> hold (deep e) (e <$ e)
139+
140+ , testE "switch-5" $ do
141+ e <- events1
142+ return $ coincidence $ flip pushAlways e $ const $
143+ return $ leftmost ["x" <$ e, "y" <$ e, "z" <$ e]
144+
145+ , testE "switch-6" $ do
146+ e <- events1
147+ return $ coincidence $ flip pushAlways e $ const $ do
148+ switch <$> hold ("x" <$ e) (e <$ e)
149+
150+ , testE "switchHoldPromptly-1" $ do
151+ e <- events1
152+ let e' = e <$ e
153+ switchHoldPromptly never $ e <$ e'
154+
155+ , testE "switchHoldPromptly-2" $ do
156+ e <- events1
157+ switchHoldPromptly never $ deep (e <$ e)
158+
159+ , testE "switchHoldPromptly-3" $ do
160+ e <- events1
161+ switchHoldPromptly never $ (e <$ deep e)
162+
163+ , testE "switchHoldPromptly-4" $ do
164+ e <- events1
165+ switchHoldPromptly never $ (deep e <$ e)
166+
167+ , testE "switch-5" $ do
168+ e <- events1
169+ switch <$> hold never (deep e <$ e)
170+
171+ , testE "switchHoldPromptly-5" $ do
172+ e <- events1
173+ switchHoldPromptly never $ flip push e $
174+ const (Just <$> headE e)
175+
176+ , testE "switchHoldPromptly-6" $ do
177+ e <- events1
178+ switchHoldPromptly never $ flip pushAlways e $
179+ const (switchHoldPromptly e never)
180+
181+ , testE "coincidence-1" $ do
182+ e <- events1
183+ return $ coincidence $ flip pushAlways e $
184+ const $ return e
185+
186+ , testE "coincidence-2" $ do
187+ e <- events1
188+ return $ coincidence $ flip pushAlways e $
189+ const $ return (deep e)
190+
191+ , testE "coincidence-3" $ do
192+ e <- events1
193+ return $ coincidence $ flip pushAlways e $
194+ const $ return (coincidence (e <$ e))
195+
196+ , testE "coincidence-4" $ do
197+ e <- events1
198+ return $ coincidence $ flip pushAlways e $
199+ const (headE e)
200+
201+ , testE "coincidence-5" $ do
202+ e <- events1
203+ return $ coincidence $ flip pushAlways e $ const $ do
204+ let e' = deep e
205+ return (coincidence (e' <$ e'))
206+
207+ , testE "coincidence-6" $ do
208+ e <- events1
209+ return $ coincidence $ flip pushAlways e $ const $ do
210+ let e' = coincidence (e <$ e)
211+ return $ deep e'
212+
213+ , testE "coincidence-7" $ do
214+ e <- events1
215+ return $ coincidence (deep e <$ e)
216+
217+ , testB "holdWhileFiring" $ do
218+ e <- events1
219+ eo <- headE e
220+ bb <- hold (constant "x") $ pushAlways (const $ hold "a" eo) eo
221+ return $ pull $ sample =<< sample bb
222+
223+
224+ , testB "foldDynWhileFiring" $ do
225+ e <- events1
226+ d <- foldDyn (:) [] $
227+ pushAlways (\a -> foldDyn (:) [a] e) e
228+
229+ return $ current (join (fmap distributeListOverDynPure d))
230+
231+ , testE "joinDyn" $ do
232+ e <- events1
233+ bb <- hold "b" e
234+ bd <- hold never . fmap (const e) =<< headE e
235+
236+ eOuter <- pushAlways sample . fmap (const bb) <$> headE e
237+ let eInner = switch bd
238+ return $ leftmost [eOuter, eInner]
239+
240+ , testB "foldDyn" $ do
241+ d <- foldDyn (++) "0" =<< events1
242+ return (current d)
243+
244+ , testB "mapDyn" $ do
245+ d <- foldDyn (++) "0" =<< events1
246+ return $ current $ fmap (map toUpper) d
247+
248+ , testB "combineDyn" $ do
249+ d1 <- foldDyn (++) "0" =<< events1
250+ d2 <- fmap (fmap (map toUpper)) $ foldDyn (++) "0" =<< events2
251+
252+ return $ current $ zipDynWith (<>) d1 d2
253+
254+ , testB "buildDynamicStrictness" $ do
255+ rec
256+ d'' <- pushDyn return d'
257+ d' <- pushDyn return d
258+ d <- holdDyn "0" =<< events1
259+
260+ _ <- sample (current d'')
261+ return (current d'')
262+
263+ , testB "factorDyn" $ do
264+ d <- holdDyn (Left "a") =<< eithers
265+
266+ eithers' <- eitherDyn d
267+ let unFactor = either id id
268+ return $ current (join (fmap unFactor eithers'))
269+
270+ , testB "pushDynDeep" $ do
271+ _ <- events1
272+ _ <- events2
273+
274+ d1 <- holdDyn "d1" =<< events1
275+ d2 <- holdDyn "d2" =<< events2
276+
277+ d <- flip pushDyn d1 $ \a ->
278+ flip pushDyn d2 $ \b ->
279+ flip pushDyn d1 $ \c ->
280+ return (a <> b <> c)
281+
282+ d' <- pushDyn scanInnerDyns d >>= scanInnerDyns
283+ return $ current d'
284+
285+ , testE "fan-1" $ do
286+ e <- fmap toMap <$> events1
287+ let es = select (fanMap e) . Const2 <$> values
288+
289+ return (mergeList es)
290+
291+ , testE "fan-2" $ do
292+ e <- fmap toMap <$> events3
293+ let es = select (fanMap e) . Const2 <$> values
294+
295+ return (mergeList es)
296+
297+ , testE "fan-3" $ do
298+ f <- fanMap . fmap toMap <$> events3
299+ return $ select f (Const2 'c')
300+
301+ , testE "fan-4" $ do
302+ e <- fmap toMap <$> events1
303+ return $ toUpper <$> select (fanMap e) (Const2 'a')
304+
305+ , testE "fan-5" $ do
306+ e <- fmap toMap <$> events2
307+ return $ toUpper <$> select (fanMap e) (Const2 'c')
308+
309+ , testE "fan-6" $ do
310+ f <- fanMap . fmap toMap <$> events1
311+ return $ toList <$> mergeList [ select f (Const2 'b'), select f (Const2 'b'), select f (Const2 'e'), select f (Const2 'e') ]
312+
313+ , testE "difference" $ do
314+ e1 <- events1
315+ e2 <- events2
316+ return $ e1 `difference ` e2
317+
318+ , testE "lazy-hold" $ do
319+ let lazyHold :: forall t m. (Reflex t, MonadHold t m, MonadFix m) => m (Event t ())
320+ lazyHold = do
321+ rec !b <- hold never e
322+ let e = never <$ switch b
323+ return $ void e
324+ lazyHold
325+
326+
327+ ] where
328+
329+ events1, events2, events3 :: TestPlan t m => m (Event t String)
330+ events1 = plan [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")]
331+ events2 = plan [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")]
332+ events3 = liftA2 mappend events1 events2
333+
334+ eithers :: TestPlan t m => m (Event t (Either String String))
335+ eithers = plan [(1, Left "e"), (3, Left "d"), (4, Right "c"), (6, Right "b"), (7, Left "a")]
336+
337+
338+ values = "abcde"
339+ toMap str = Map.fromList $ map (\c -> (c, c)) str
340+
341+ behavior1, behavior2 :: forall t m. TestPlan t m => m (Behavior t String)
342+ behavior1 = hold "1" =<< events1
343+ behavior2 = hold "2" =<< events2
344+
345+ deep e = leftmost [e, e]
346+ leftmost2 e1 e2 = leftmost [e1, e2]
test/Reflex/TestPlan.hsnew file+52
@@ -0,0 +1,52 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE RankNTypes #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE UndecidableInstances #-}
9+module Reflex.TestPlan
10+ ( TestPlan(..)
11+
12+ , TestCase (..)
13+ , testE, testB
14+ , TestE, TestB
15+
16+ , planList
17+
18+ ) where
19+
20+import Control.DeepSeq
21+import Control.Monad.Fix
22+import Data.Word
23+import Reflex.Class
24+
25+
26+import Prelude
27+
28+class (Reflex t, MonadHold t m, MonadFix m) => TestPlan t m where
29+ -- | Specify a plan of an input Event firing
30+ -- Occurrences must be in the future (i.e. Time > 0)
31+ -- Initial specification is
32+
33+ plan :: [(Word, a)] -> m (Event t a)
34+
35+
36+planList :: TestPlan t m => [a] -> m (Event t a)
37+planList xs = plan $ zip [1..] xs
38+
39+type TestE a = forall t m. TestPlan t m => m (Event t a)
40+type TestB a = forall t m. TestPlan t m => m (Behavior t a)
41+
42+data TestCase where
43+ TestE :: (Show a, Eq a, NFData a) => TestE a -> TestCase
44+ TestB :: (Show a, Eq a, NFData a) => TestB a -> TestCase
45+
46+-- Helpers to declare test cases
47+testE :: (Eq a, Show a, NFData a) => String -> TestE a -> (String, TestCase)
48+testE name test = (name, TestE test)
49+
50+testB :: (Eq a, Show a, NFData a) => String -> TestB a -> (String, TestCase)
51+testB name test = (name, TestB test)
52+
test/RequesterT.hsnew file+174
@@ -0,0 +1,174 @@
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.hsnew file+74
@@ -0,0 +1,74 @@
1+{-# LANGUAGE GADTs #-}
2+{-# LANGUAGE LambdaCase #-}
3+module Test.Run where
4+
5+import Control.Monad
6+import Control.Monad.Ref
7+import Data.Dependent.Sum
8+import Data.Functor.Identity
9+import Data.These
10+
11+import Reflex
12+import Reflex.Host.Class
13+
14+data AppIn t b e = AppIn
15+ { _appIn_behavior :: Behavior t b
16+ , _appIn_event :: Event t e
17+ }
18+
19+data AppOut t b e = AppOut
20+ { _appOut_behavior :: Behavior t b
21+ , _appOut_event :: Event t e
22+ }
23+
24+runApp :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
25+ => (AppIn t bIn eIn -> PerformEventT t m (AppOut t bOut eOut))
26+ -> bIn
27+ -> [Maybe (These bIn eIn)]
28+ -> IO [[(bOut, Maybe eOut)]]
29+runApp app b0 input = runSpiderHost $ do
30+ (appInHoldE, pulseHoldTriggerRef) <- newEventWithTriggerRef
31+ (appInE, pulseEventTriggerRef) <- newEventWithTriggerRef
32+ appInB <- hold b0 appInHoldE
33+ (out, FireCommand fire) <- hostPerformEventT $ app $ AppIn
34+ { _appIn_event = appInE
35+ , _appIn_behavior = appInB
36+ }
37+ hnd <- subscribeEvent (_appOut_event out)
38+ mpulseB <- readRef pulseHoldTriggerRef
39+ mpulseE <- readRef pulseEventTriggerRef
40+ let readPhase = do
41+ b <- sample (_appOut_behavior out)
42+ frames <- sequence =<< readEvent hnd
43+ return (b, frames)
44+ forM input $ \case
45+ Nothing ->
46+ fire [] $ readPhase
47+ Just i -> case i of
48+ This b' -> case mpulseB of
49+ Nothing -> error "tried to fire in-behavior but ref was empty"
50+ Just pulseB -> fire [ pulseB :=> Identity b' ] $ readPhase
51+ That e' -> case mpulseE of
52+ Nothing -> error "tried to fire in-event but ref was empty"
53+ Just pulseE -> fire [ pulseE :=> Identity e' ] $ readPhase
54+ These b' e' -> case mpulseB of
55+ Nothing -> error "tried to fire in-behavior but ref was empty"
56+ Just pulseB -> case mpulseE of
57+ Nothing -> error "tried to fire in-event but ref was empty"
58+ Just pulseE -> fire [ pulseB :=> Identity b', pulseE :=> Identity e' ] $ readPhase
59+
60+runApp' :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
61+ => (Event t eIn -> PerformEventT t m (Event t eOut))
62+ -> [Maybe eIn]
63+ -> IO [[Maybe eOut]]
64+runApp' app input = do
65+ let app' = fmap (AppOut (pure ())) . app
66+ map (map snd) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
67+
68+runAppB :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)
69+ => (Event t eIn -> PerformEventT t m (Behavior t bOut))
70+ -> [Maybe eIn]
71+ -> IO [[bOut]]
72+runAppB app input = do
73+ let app' = fmap (flip AppOut never) . app
74+ map (map fst) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
test/hlint.hs+8−2
@@ -1,7 +1,7 @@
11module Main where
22
33import Control.Monad
4−import Language.Haskell.HLint (hlint)
4+import Language.Haskell.HLint3 (hlint)
55import System.Directory
66import System.Exit (exitFailure, exitSuccess)
77import System.FilePath
@@ -23,7 +23,6 @@ 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
2726 ]
2827 recurseInto = and <$> sequence
2928 [ fileType ==? Directory
@@ -31,9 +30,16 @@ main = do
3130 ]
3231 matchFile = and <$> sequence
3332 [ extension ==? ".hs"
33+ , let notElem' = liftOp notElem
34+ in filePath `notElem'` filePathExceptions pwd
3435 ]
3536 files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
3637 ideas <- fmap concat $ forM files $ \f -> do
3738 putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
3839 runHlint f
3940 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.hsnew file+25
@@ -0,0 +1,25 @@
1+import Control.Concurrent
2+import Control.Monad
3+import Data.IORef
4+import Reflex
5+import Reflex.Host.Class
6+import System.Exit
7+import System.Mem
8+
9+main :: IO ()
10+main = do
11+ numSubscriptions <- newIORef 0
12+ replicateM_ 1000 $ do
13+ runSpiderHost $ do
14+ e <- newEventWithTrigger $ \_ -> do
15+ modifyIORef' numSubscriptions succ
16+ return $ modifyIORef' numSubscriptions pred
17+ _ <- hold () e
18+ return ()
19+ replicateM_ 100 $ do
20+ performMajorGC
21+ threadDelay 1
22+ n <- readIORef numSubscriptions
23+ if n == 0
24+ then putStrLn "Succeeded"
25+ else putStrLn "Failed" >> exitFailure
test/semantics.hsnew file+47
@@ -0,0 +1,47 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE RankNTypes #-}
7+
8+module Main (main) where
9+
10+import Reflex.Test
11+
12+import Data.Bifunctor
13+import Data.Functor
14+import Data.List
15+import qualified Reflex.Bench.Focused as Focused
16+import qualified Reflex.Test.Micro as Micro
17+
18+import System.Environment
19+import System.Exit
20+
21+import Prelude
22+
23+matchPrefixes :: [String] -> (String -> Bool)
24+matchPrefixes [] = const True
25+matchPrefixes args = \name -> any (`isPrefixOf` name) args
26+
27+
28+main :: IO ()
29+main = do
30+ args <- getArgs
31+
32+ case args of
33+ ["--list"] -> mapM_ putStrLn (fst <$> allTests) >> exitWith (ExitFailure 1)
34+ _ -> case filter (matchPrefixes args . fst) allTests of
35+ [] -> putStrLn "filter did not match any tests" >> exitWith (ExitFailure 1)
36+ tests -> runTests tests
37+
38+ where
39+ allTests = concat
40+ [ makeGroup "micro" Micro.testCases
41+ , makeGroup "subscribing (100,40)" (Focused.subscribing 100 40)
42+ , makeGroup "firing 1000" (Focused.firing 1000)
43+ , makeGroup "merge 100" (Focused.merging 100)
44+ , makeGroup "fan 50" (Focused.fans 50)
45+ ]
46+
47+ makeGroup name tests = first (\test -> intercalate "/" [name, test]) <$> tests
test/tests.hsdeleted−43
@@ -1,43 +0,0 @@
1−{-# LANGUAGE TemplateHaskell #-}
2−module Main where
3−
4−import Test.HUnit (runTestTT, (~:), assertEqual, errors, failures, test)
5−import Data.Patch ( Patch(apply) )
6−import Data.Patch.MapWithMove ( patchThatChangesMap )
7−import Data.Map as Map ( Map, fromList, singleton )
8−import Hedgehog (checkParallel, discover, Property, property, forAll, PropertyT, (===))
9−import Hedgehog.Gen as Gen ( int )
10−import Hedgehog.Range as Range ( linear )
11−import Control.Monad (replicateM)
12−import System.Exit (exitFailure, exitSuccess)
13−import Data.Sequence as Seq ( foldMapWithIndex, replicateM )
14−
15−main :: IO ()
16−main = do
17− counts <- runTestTT $ test [
18− "Simple Move" ~: (do
19− let mapBefore = Map.fromList [(0,1)]
20− mapAfter = Map.fromList [(0,0),(1,1)]
21− patch = patchThatChangesMap mapBefore mapAfter
22− afterPatch = apply patch mapBefore
23− assertEqual "Patch creates the same Map" (Just mapAfter) afterPatch),
24− "Property Checks" ~: propertyChecks
25− ]
26− if errors counts + failures counts == 0 then exitSuccess else exitFailure
27−
28−propertyChecks :: IO Bool
29−propertyChecks = checkParallel $$(discover)
30−
31−prop_patchThatChangesMap :: Property
32−prop_patchThatChangesMap = property $ do
33− mapBefore <- makeRandomIntMap
34− mapAfter <- makeRandomIntMap
35− let patch = patchThatChangesMap mapBefore mapAfter
36− Just mapAfter === apply patch mapBefore
37−
38−makeRandomIntMap :: Monad m => PropertyT m (Map Int Int)
39−makeRandomIntMap = do
40− let genNum = Gen.int (Range.linear 0 100)
41− length <- forAll genNum
42− listOfNumbers <- forAll $ Seq.replicateM length genNum
43− pure $ Seq.foldMapWithIndex Map.singleton listOfNumbers