on develop help sign in
86 files changed+14578−1790
since splitsnapshots
unifiedsplit
.ghci+1−3 .github/workflows/haskell.yml+41 .gitignore+7 .stylish-haskell.yaml+153 CONTRIBUTING.md+66 ChangeLog.md+151 Quickref.md+315 README.md+23 Setup.hs+2 bench-cbits/checkCapability.c+208 bench/Main.hs+110 bench/RunAll.hs+157 cabal.haskell-ci+23 cabal.project+1 default.nix−12 dep/reflex-platform/default.nix+7 dep/reflex-platform/github.json+7 reflex.cabal+478−26 release.nix+58 src/Control/Monad/ReaderIO.hs+60 src/Control/Monad/Ref.hs−85 src/Control/Monad/TypedId.hs−50 src/Data/AppendMap.hs+84 src/Data/FastMutableIntMap.hs+97 src/Data/FastWeakBag.hs+161 src/Data/Functor/Misc.hs−71 src/Data/Map/Misc.hs+71 src/Data/WeakBag.hs+126 src/Reflex.hs+34−9 src/Reflex/Adjustable/Class.hs+140 src/Reflex/BehaviorWriter/Base.hs+211 src/Reflex/BehaviorWriter/Class.hs+31 src/Reflex/Class.hs+1596−137 src/Reflex/Collection.hs+225 src/Reflex/Dynamic.hs+427−308 src/Reflex/Dynamic/TH.hs+81−14 src/Reflex/Dynamic/Uniq.hs+105 src/Reflex/DynamicWriter.hs+7 src/Reflex/DynamicWriter/Base.hs+246 src/Reflex/DynamicWriter/Class.hs+28 src/Reflex/EventWriter.hs+7 src/Reflex/EventWriter/Base.hs+317 src/Reflex/EventWriter/Class.hs+26 src/Reflex/FastWeak.hs+210 src/Reflex/FunctorMaybe.hs+47 src/Reflex/Host/Class.hs+247−24 src/Reflex/Host/Headless.hs+128 src/Reflex/Network.hs+45 src/Reflex/NotReady/Class.hs+77 src/Reflex/Optimizer.hs+65 src/Reflex/PerformEvent/Base.hs+181 src/Reflex/PerformEvent/Class.hs+68 src/Reflex/PostBuild/Base.hs+198 src/Reflex/PostBuild/Class.hs+40 src/Reflex/Profiled.hs+281 src/Reflex/Pure.hs+217 src/Reflex/Query/Base.hs+346 src/Reflex/Query/Class.hs+158 src/Reflex/Requester/Base.hs+607 src/Reflex/Requester/Class.hs+72 src/Reflex/Spider.hs+18−3 src/Reflex/Spider/Internal.hs+2632−1048 src/Reflex/Time.hs+384 src/Reflex/TriggerEvent/Base.hs+150 src/Reflex/TriggerEvent/Class.hs+55 src/Reflex/Widget/Basic.hs+44 src/Reflex/Workflow.hs+50 stylize+4 test/Adjustable.hs+62 test/DebugCycles.hs+171 test/EventWriterT.hs+134 test/GC.hs+101 test/Headless.hs+10 test/QueryT.hs+142 test/Reflex/Bench/Focused.hs+381 test/Reflex/Plan/Pure.hs+73 test/Reflex/Plan/Reflex.hs+135 test/Reflex/Test.hs+66 test/Reflex/Test/CrossImpl.hs+267 test/Reflex/Test/Micro.hs+352 test/Reflex/TestPlan.hs+52 test/RequesterT.hs+235 test/Test/Run.hs+74 test/hlint.hs+39 test/rootCleanup.hs+25 test/semantics.hs+47
.ghci+1−3
@@ -1,4 +1,2 @@
11:set -isrc
2−:set -hide-package MonadCatchIO-mtl
3−:set -hide-package monads-fd
4−:set -XOverloadedStrings
2+:seti -XOverloadedStrings
.github/workflows/haskell.ymlnew file+41
@@ -0,0 +1,41 @@
1+name: github-action
2+
3+on: [push, pull_request]
4+
5+jobs:
6+ build:
7+ strategy:
8+ matrix:
9+ ghc: ['8.4.4', '8.6.5', '8.8.4', '8.10.2']
10+ os: ['ubuntu-latest', 'macos-latest']
11+ runs-on: ${{ matrix.os }}
12+
13+ name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
14+ steps:
15+ - uses: actions/checkout@v2
16+ - uses: actions/setup-haskell@v1
17+ with:
18+ ghc-version: ${{ matrix.ghc }}
19+ - name: Cache
20+ uses: actions/cache@v1
21+ env:
22+ cache-name: cache-cabal
23+ with:
24+ path: ~/.cabal
25+ key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
26+ restore-keys: |
27+ ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
28+ ${{ runner.os }}-${{ matrix.ghc }}-build-
29+ ${{ runner.os }}-${{ matrix.ghc }}-
30+ ${{ runner.os }}
31+
32+ - name: Install dependencies
33+ run: |
34+ cabal update
35+ cabal build --only-dependencies --enable-tests --enable-benchmarks
36+ - name: Build
37+ run: cabal build --enable-tests --enable-benchmarks all
38+ - name: Run tests
39+ run: cabal test all
40+ - name: Build Docs
41+ run: cabal haddock
.gitignore+7
@@ -1,4 +1,7 @@
11dist
2+cabal.sandbox.config
3+.cabal-sandbox/
4+dist-*
25cabal-dev
36*.o
47*.hi
@@ -29,3 +32,7 @@ tags
2932hsenv.log
3033\#*#
3134.#*
35+/shell.nix
36+/ghci-tmp
37+*.dump-*
38+*.verbose-core2core
.stylish-haskell.yamlnew file+153
@@ -0,0 +1,153 @@
1+# stylish-haskell configuration file
2+# ==================================
3+
4+# The stylish-haskell tool is mainly configured by specifying steps. These steps
5+# are a list, so they have an order, and one specific step may appear more than
6+# once (if needed). Each file is processed by these steps in the given order.
7+steps:
8+ # Convert some ASCII sequences to their Unicode equivalents. This is disabled
9+ # by default.
10+ # - unicode_syntax:
11+ # # In order to make this work, we also need to insert the UnicodeSyntax
12+ # # language pragma. If this flag is set to true, we insert it when it's
13+ # # not already present. You may want to disable it if you configure
14+ # # language extensions using some other method than pragmas. Default:
15+ # # true.
16+ # add_language_pragma: true
17+
18+ # Import cleanup
19+ - imports:
20+ # There are different ways we can align names and lists.
21+ #
22+ # - global: Align the import names and import list throughout the entire
23+ # file.
24+ #
25+ # - file: Like global, but don't add padding when there are no qualified
26+ # imports in the file.
27+ #
28+ # - group: Only align the imports per group (a group is formed by adjacent
29+ # import lines).
30+ #
31+ # - none: Do not perform any alignment.
32+ #
33+ # Default: global.
34+ align: none
35+
36+ # Folowing options affect only import list alignment.
37+ #
38+ # List align has following options:
39+ #
40+ # - after_alias: Import list is aligned with end of import including
41+ # 'as' and 'hiding' keywords.
42+ #
43+ # > import qualified Data.List as List (concat, foldl, foldr, head,
44+ # > init, last, length)
45+ #
46+ # - with_alias: Import list is aligned with start of alias or hiding.
47+ #
48+ # > import qualified Data.List as List (concat, foldl, foldr, head,
49+ # > init, last, length)
50+ #
51+ # - new_line: Import list starts always on new line.
52+ #
53+ # > import qualified Data.List as List
54+ # > (concat, foldl, foldr, head, init, last, length)
55+ #
56+ # Default: after alias
57+ list_align: after_alias
58+
59+ # Long list align style takes effect when import is too long. This is
60+ # determined by 'columns' setting.
61+ #
62+ # - inline: This option will put as much specs on same line as possible.
63+ #
64+ # - new_line: Import list will start on new line.
65+ #
66+ # - new_line_multiline: Import list will start on new line when it's
67+ # short enough to fit to single line. Otherwise it'll be multiline.
68+ #
69+ # - multiline: One line per import list entry.
70+ # Type with contructor list acts like single import.
71+ #
72+ # > import qualified Data.Map as M
73+ # > ( empty
74+ # > , singleton
75+ # > , ...
76+ # > , delete
77+ # > )
78+ #
79+ # Default: inline
80+ long_list_align: inline
81+
82+ # List padding determines indentation of import list on lines after import.
83+ # This option affects 'list_align' and 'long_list_align'.
84+ list_padding: 2
85+
86+ # Separate lists option affects formating of import list for type
87+ # or class. The only difference is single space between type and list
88+ # of constructors, selectors and class functions.
89+ #
90+ # - true: There is single space between Foldable type and list of it's
91+ # functions.
92+ #
93+ # > import Data.Foldable (Foldable (fold, foldl, foldMap))
94+ #
95+ # - false: There is no space between Foldable type and list of it's
96+ # functions.
97+ #
98+ # > import Data.Foldable (Foldable(fold, foldl, foldMap))
99+ #
100+ # Default: true
101+ separate_lists: true
102+
103+ # Language pragmas
104+ - language_pragmas:
105+ # We can generate different styles of language pragma lists.
106+ #
107+ # - vertical: Vertical-spaced language pragmas, one per line.
108+ #
109+ # - compact: A more compact style.
110+ #
111+ # - compact_line: Similar to compact, but wrap each line with
112+ # `{-#LANGUAGE #-}'.
113+ #
114+ # Default: vertical.
115+ style: vertical
116+
117+ # Align affects alignment of closing pragma brackets.
118+ #
119+ # - true: Brackets are aligned in same collumn.
120+ #
121+ # - false: Brackets are not aligned together. There is only one space
122+ # between actual import and closing bracket.
123+ #
124+ # Default: true
125+ align: false
126+
127+ # stylish-haskell can detect redundancy of some language pragmas. If this
128+ # is set to true, it will remove those redundant pragmas. Default: true.
129+ remove_redundant: true
130+
131+ # Align the types in record declarations
132+ # - records: {}
133+
134+ # Replace tabs by spaces. This is disabled by default.
135+ # - tabs:
136+ # # Number of spaces to use for each tab. Default: 8, as specified by the
137+ # # Haskell report.
138+ # spaces: 8
139+
140+ # Remove trailing whitespace
141+ - trailing_whitespace: {}
142+
143+# A common setting is the number of columns (parts of) code will be wrapped
144+# to. Different steps take this into account. Default: 80.
145+columns: 110
146+
147+# Sometimes, language extensions are specified in a cabal file or from the
148+# command line instead of using language pragmas in the file. stylish-haskell
149+# needs to be aware of these, so it can parse the file correctly.
150+#
151+# No language extensions are enabled by default.
152+language_extensions:
153+ - TemplateHaskell
CONTRIBUTING.mdnew file+66
@@ -0,0 +1,66 @@
1+# Contribution Guide
2+
3+Contributions and issue reports are encouraged and appreciated!
4+
5+- [Opening Issues](#opening-issues)
6+- [Submitting Changes](#submitting-changes)
7+ - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
8+ - [Guidelines for Pull Requests](#guidelines-for-pull-requests)
9+ - [Code Quality](#code-quality)
10+ - [Documentation](#documentation)
11+
12+## Opening Issues
13+
14+Before opening an issue, please check whether your issue has already been reported. Assuming it has not:
15+
16+* Describe the issue you're encountering or the suggestion you're making
17+* Include any relevant steps to reproduce or code samples you can. It's always easier for us to debug if we have something that demonstrates the error.
18+* Let us know what version of 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.
20+
21+## Submitting Changes
22+
23+### Guidelines for Commit Messages
24+
25+#### Summary Line
26+The summary line of your commit message should summarize the changes being made. Commit messages should be written in the imperative mood and should describe what happens when the commit is applied.
27+
28+One way to think about it is that your commit message should be able to complete the sentence:
29+"When applied, this commit will..."
30+
31+#### Body
32+For breaking changes, new features, refactors, or other major changes, the body of the commit message should describe the motivation behind the change in greater detail and may include references to the issue tracker. The body shouldn't repeat code/comments from the diff.
33+
34+### Guidelines for Pull Requests
35+
36+Wherever possible, pull requests should add a single feature or fix a single bug. Pull requests should not bundle several unrelated changes.
37+
38+### Code Quality
39+
40+#### Warnings
41+
42+Your pull request should add no new warnings to the project. It should also generally not disable any warnings.
43+
44+#### Build and Test
45+
46+Make sure the project builds and that the tests pass! This will generally also be checked by CI before merge, but trying it yourself first means you'll catch problems earlier and your contribution can be merged that much sooner!
47+
48+#### Dependencies
49+
50+Include version bounds whenever adding a dependency to the library stanza of the cabal file. Note that libraries added to reflex.cabal also need to be added to default.nix.
51+
52+### Documentation
53+
54+#### In the code
55+We're always striving to improve documentation. Please include [haddock](https://haskell-haddock.readthedocs.io/en/latest/index.html) documentation for any added code, and update the documentation for any code you modify.
56+
57+#### In the [Changelog](ChangeLog.md)
58+Add an entry to the changelog when your PR:
59+* Adds a feature
60+* Deprecates something
61+* Includes a breaking change
62+* Makes any other change that will impact users
63+
64+#### In the [Readme](README.md)
65+The readme is the first place a lot of people look for information about the repository. Update any parts of the readme that are affected by your PR.
66+
ChangeLog.mdnew file+151
@@ -0,0 +1,151 @@
1+# Revision history for reflex
2+
3+## 0.8.2.0
4+
5+* Add `matchResponseMapWithRequests`, which it similar to `matchResponsesWithRequests` but allows processing of multiple responses at once.
6+
7+## 0.8.1.1
8+
9+* Allow newer hlint for older GHCs, and add upper bound for newer GHCs
10+
11+## 0.8.1.0
12+
13+* Add support for GHC 8.10
14+* Drop support for GHC < 8.4
15+
16+## 0.8.0.0
17+
18+* Replace 0.7.2.0 with 0.8.0.0 to reflect the `MonadHold` interface change. Deprecates 0.7.2.0.
19+
20+## 0.7.2.0 -- *Deprecated*
21+
22+* ([#416](https://github.com/reflex-frp/reflex/pull/416)) Add `now :: m (Event t ())` to `MonadHold`.
23+* Extend some dependency version bounds
24+* Fix HLint 3 test
25+
26+## 0.7.1.1
27+
28+*Backport release*.
29+Changes do not carry forward to 0.7.2.0.
30+
31+* Add support for GHC 8.10
32+* Drop support for GHC < 8.4
33+* Extend some dependency version bounds
34+* Fix HLint 3 test
35+
36+## 0.7.1.0
37+
38+* ([#413](https://github.com/reflex-frp/reflex/pull/413), [#417](https://github.com/reflex-frp/reflex/pull/417)) Add `Reflex.Host.Headless` module which provides `runHeadlessApp` as an easy way to run a Reflex network in a "headless" environment.
39+* ([#420](https://github.com/reflex-frp/reflex/pull/420)) Add a [`Data.Zip.Unzip`](https://hackage.haskell.org/package/semialign-1.1/docs/Data-Zip.html#t:Unzip) instance for `Event`.
40+* ([#419](https://github.com/reflex-frp/reflex/pull/419)) Add `distributeIntMapOverDynPure` and `joinDynThroughIntMap` as convenience functions for working with `Dynamic` `IntMap`s.
41+
42+
43+## 0.7.0.0
44+
45+* Add lifting instances for most classes to `Reflex.Profiled.Profiled`. ([#398](https://github.com/reflex-frp/reflex/pull/398))
46+* Class `MonadQuery t q m` now has a `Monad m` superclass constraint. ([#400](https://github.com/reflex-frp/reflex/pull/400))
47+* **(Breaking change)** Rename class `MonadBehaviorWriter` -> `BehaviorWriter` for consistency with `EventWriter`/`DynamicWriter`. ([#401](https://github.com/reflex-frp/reflex/pull/401))
48+* Introduce deprecated alias `MonadBehaviorWriter = BehaviorWriter`. ([#401](https://github.com/reflex-frp/reflex/pull/401))
49+* Fix bug in spider where event subscriptions would be prematurely finalized due to over-aggressive inlining. ([#409](https://github.com/reflex-frp/reflex/pull/409))
50+* Add instances of `PerformEvent` and `TriggerEvent` for `MaybeT`. ([#395](https://github.com/reflex-frp/reflex/pull/395))
51+
52+## 0.6.4.1
53+
54+* Fix a bug in the Reflex Profiled transformer where
55+ `Reflex.Class.mergeIncrementalG` and
56+ `Reflex.Class.mergeIncrementalWithMoveG` implementations referenced
57+ itself instead of the inner transformed timeline, causing an
58+ infinite loop.
59+
60+## 0.6.4
61+
62+* Support GHC 8.8
63+
64+* Add `Reflex.Query.Base.mapQueryT`. See that module for documentation
65+
66+* The `Reflex.Patch.*` modules were moved to the `patch` library.
67+ They are `Data.Patch.*` there, but reexported under their old names for backwards compatability here.
68+
69+* Additional instances for `Query` classes for basic types.
70+
71+* Add cabal flags `debug-propagation` and `debug-event-cycles` to build in debugging
72+ code for performance and for cyclic dependencies between events
73+
74+## 0.6.3
75+
76+* `Data.WeakBag.traverse` and `Data.FastWeakBag.traverse` have been deprecated.
77+ They are replaced with `Data.WeakBag.traverse_` and `Data.FastWeakBag.traverse_`, respectively.
78+
79+* Fixes a bug in `Reflex.Patch.MapWithMove.patchThatSortsMapWith` that was producing invalid `PatchMapWithMove`.
80+
81+* Add missing `NotReady` instances:
82+ - `instance NotReady (SpiderTimeline x) (SpiderHost x)`
83+ - `instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x))`
84+
85+## 0.6.2.4
86+
87+* Update to monoidal-containers 0.6
88+
89+## 0.6.2.3
90+
91+* Add an upper-bound to witherable
92+
93+## 0.6.2.2
94+
95+* Support these >= 1. Add `split-these` flag to control whether to use new these/semialign combination or not.
96+
97+* Update version bounds to fix some CI failures
98+
99+* Add travis CI configuration
100+
101+## 0.6.2.1
102+
103+* Generalize `fan` to `fanG` to take a `DMap` with non-`Identity`
104+ functor:
105+ * `fan` to `fanG`
106+ * `EventSelectorG` for `fanG` result selector.
107+
108+* Reduce the amount of unsafeCoerce in coercing newtypes under Event/Dynamic/Behavior.
109+ * Add fused ReaderIO for the purpose of coercion (ReaderT's third argument has nominal role preventing automated coerce)
110+ * Add incrementalCoercion/coerceIncremental to go with dynamicCoercion/coerceDynamic
111+
112+* Generalize merging functions:
113+ `merge` to `mergeG`,
114+ `mergeIncremental` to `mergeIncrementalG`,
115+ `mergeIncrementalWithMove` to `mergeIncrementalWithMoveG`.
116+
117+* Generalize distribute function:
118+ `distributeDMapOverDynPure` to `distributeDMapOverDynPureG`,
119+
120+## 0.6.2.0
121+
122+* Fix `holdDyn` so that it is lazy in its event argument
123+ These produce `DMap`s whose values needn't be `Identity`.
124+
125+* Stop using the now-deprecated `*Tag` classes (e.g., `ShowTag`).
126+
127+* Fix `holdDyn` so that it is lazy in its event argument.
128+
129+## 0.6.1.0
130+
131+* Re-export all of `Data.Map.Monoidal`
132+
133+* Fix `QueryT` and `RequesterT` tests
134+
135+## 0.6.0.0 -- 2019-03-20
136+
137+* Deprecate `FunctorMaybe` in favor of `Data.Witherable.Filterable`. We still export `fmapMaybe`, `ffilter`, etc., but they all rely on `Filterable` now.
138+
139+* Rename `MonadDynamicWriter` to `DynamicWriter` and add a deprecation for the old name.
140+
141+* Remove many deprecated functions.
142+
143+* Add a `Num` instance for `Dynamic`.
144+
145+* Add `matchRequestsWithResponses` to make it easier to use `Requester` with protocols that don't do this matching for you.
146+
147+* Add `withRequesterT` to map functions over the request and response of a `RequesterT`.
148+
149+* Suppress nil patches in `QueryT` as an optimization. The `Query` type must now have an `Eq` instance.
150+
151+* Add `throttleBatchWithLag` to `Reflex.Time`. See that module for details.
Quickref.mdnew file+315
@@ -0,0 +1,315 @@
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+ -- Note align functions from Data.Align in semialign package
58+[ ] mergeWith :: (a -> a -> a) -> [Event a] -> Event a
59+[ ] leftmost :: [Event a] -> Event a
60+[ ] mergeList :: [Event a] -> Event (NonEmpty a)
61+[ ] merge :: GCompare k => DMap k Event -> Event (DMap k Identity)
62+[ ] mergeMap :: Ord k => Map k (Event a) -> Event (Map k a)
63+
64+-- Efficient one-to-many fanout
65+[ ] fanMap :: Ord k => Event (Map k a) -> EventSelector (Const2 k a)
66+[ ] fan :: GCompare k => Event (DMap k Identity) -> EventSelector k
67+[ ] select :: EventSelector k -> k a -> Event a
68+[ ] fanEither :: Event (Either a b) -> (Event a, Event b)
69+[ ] fanThese :: Event (These a b) -> (Event a, Event b)
70+
71+-- Event to Event via function that can sample current values
72+[ ] push :: (a -> m (Maybe b)) -> Event a -> Event b
73+[ ] pushAlways :: (a -> m b ) -> Event a -> Event b
74+ -- Note supplied function operates in [H] context
75+
76+-- Split Event into next occurrence and all other future occurrences, as of now.
77+[H] headE :: Event a -> m (Event a)
78+[H] tailE :: Event a -> m (Event a)
79+[H] headTailE :: Event a -> m (Event a, Event a)
80+```
81+
82+## Functions producing Behavior
83+
84+```haskell
85+-- Trivial Behavior
86+[ ] constant :: a -> Behavior a
87+
88+-- Extract Behavior from Dynamic
89+[ ] current :: Dynamic a -> Behavior a
90+
91+-- Create Behavior with given initial value, updated when the Event fires.
92+[H] hold :: a -> Event a -> m (Behavior a)
93+
94+-- Transform Behavior to Behavior using function
95+[ ] fmap :: (a -> b) -> Behavior a -> Behavior b
96+[ ] ffor :: Behavior a -> (a -> b) -> Behavior b
97+[ ] <*> :: Behavior (a -> b) -> Behavior a -> Behavior b
98+[ ] >>= :: Behavior a -> (a -> Behavior b) -> Behavior b
99+[ ] <> :: Monoid a => Behavior a -> Behavior a -> Behavior a
100+-- ... plus many more due to typeclass membership
101+
102+-- Combine multiple behaviors via applicative instance
103+[ ] ffor2 :: Behavior a -> Behavior b -> (a -> b -> c) -> Behavior c
104+[ ] ffor3 :: Behavior a -> Behavior b -> Behavior c -> (a -> b -> c -> d) -> Behavior d
105+
106+-- Behavior to Behavior by sampling current values
107+[S] sample :: Behavior a -> m a
108+[ ] pull :: m a -> Behavior a
109+ -- Note supplied value is in [S] context
110+```
111+
112+## Functions producing Dynamic
113+
114+```haskell
115+-- Trivial Dynamic
116+[ ] constDyn :: a -> Dynamic a
117+
118+-- Create Dynamic with given initial value, updated (various ways) when the Event fires.
119+[H] holdDyn :: a -> Event a -> m (Dynamic a)
120+[H] foldDyn :: (a -> b -> b ) -> b -> Event a -> m (Dynamic b)
121+[H] foldDynMaybe :: (a -> b -> Maybe b ) -> b -> Event a -> m (Dynamic b)
122+[H] foldDynM :: (a -> b -> m' b ) -> b -> Event a -> m (Dynamic b)
123+[H] foldDynMaybeM :: (a -> b -> m' (Maybe b)) -> b -> Event a -> m (Dynamic b)
124+ -- Note m' supplies [H] context
125+
126+-- Initial value is 0; counts Event firings from now.
127+[H] count :: Num b => Event a -> m (Dynamic b)
128+-- Initial Bool value is supplied; toggles at each Event firing.
129+[H] toggle :: Bool -> Event a -> m (Dynamic Bool)
130+
131+-- Transform Dynamic to Dynamic using function
132+[ ] ffor :: Dynamic a -> (a -> b) -> Dynamic b
133+[ ] fmap :: (a -> b) -> Dynamic a -> Dynamic b
134+[ ] splitDynPure :: Dynamic (a, b) -> (Dynamic a, Dynamic b)
135+
136+-- Combine multiple Dynamics
137+[ ] mconcat :: Monoid a => [Dynamic a] -> Dynamic a
138+[ ] distributeDMapOverDynPure :: GCompare k => DMap (WrapArg Dynamic k) -> Dynamic (DMap k)
139+[ ] <*> :: Dynamic (a -> b) -> Dynamic a -> Dynamic b
140+[ ] >>= :: Dynamic a -> (a -> Dynamic b) -> Dynamic b
141+[ ] zipDynWith :: (a -> b -> c) -> Dynamic a -> Dynamic b -> Dynamic c
142+
143+-- Combine multiple dynamics via applicative instance
144+[ ] ffor2 :: Dynamic a -> Dynamic b -> (a -> b -> c) -> Dynamic c
145+[ ] ffor3 :: Dynamic a -> Dynamic b -> Dynamic c -> (a -> b -> c -> d) -> Dynamic d
146+
147+-- Efficient one-to-many fanout
148+[ ] demux :: Ord k => Dynamic k -> Demux k
149+[ ] demuxed :: Eq k => Demux k -> k -> Dynamic Bool
150+
151+-- Dynamic to Dynamic, removing updates w/o value change
152+[H] holdUniqDyn :: Eq a => Dynamic a -> m (Dynamic a)
153+[H] holdUniqDynBy :: (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
154+
155+-- Dynamic to identical Dynamic with debug trace. (Only prints if Dynamic is ultimately used.)
156+[ ] traceDyn :: Show a => String -> Dynamic a -> Dynamic a
157+[ ] traceDynWith :: (a -> String) -> Dynamic a -> Dynamic a
158+```
159+
160+## Flattening functions
161+
162+These functions flatten nested types such as Event-of-Event, Behavior-of-Event, Event-of-Behavior etc, removing the outer wrapper.
163+
164+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.
165+
166+```haskell
167+-- Flatten Behavior-of-Event to Event. Old Event is used during switchover.
168+[ ] switch :: Behavior (Event a) -> Event a
169+
170+-- Flatten Dynamic-of-Event to Event. New Event is used immediately.
171+[ ] switchDyn :: Dynamic (Event a) -> Event a
172+
173+-- Flatten Event-of-Event to Event that fires when both wrapper AND new Event fire.
174+[ ] coincidence :: Event (Event a) -> Event a
175+
176+-- Flatten Behavior-of-Behavior to Behavior. Behavior is an instance of Monad,
177+-- so the 'join' function from 'Control.Monad' suffices. The output of 'join' is
178+-- a Behavior whose value is equal to the current value of the current value of
179+-- the input.
180+[ ] join :: Behavior (Behavior a) -> Behavior a
181+
182+
183+-- Flatten Dynamic-of-Dynamic to Dynamic. New Dynamic is used immediately.
184+-- Output updated whenever inner OR outer Dynamic updates.
185+[ ] join :: Dynamic (Dynamic a) -> Dynamic a
186+[ ] joinDynThroughMap :: Ord k => Dynamic (Map k (Dynamic a)) -> Dynamic (Map k a)
187+
188+-- Analogous to 'hold': Create a Behavior that is initially identical to the
189+-- supplied Behavior. Updated to track a new Behavior whenever the Event fires.
190+[H] switcher :: Behavior a -> Event (Behavior a) -> m (Behavior a)
191+
192+-- Similar to above, for Events. Created Event initially tracks the first argument.
193+-- At switchover, the output Event immediately tracks the new Event.
194+[H] switchHold :: Event a -> Event (Event a) -> m (Event a)
195+```
196+
197+## Typeclasses to introspect and modify an FRP network.
198+
199+The functions mentioned above are used to create a static FRP network.
200+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.
201+
202+The typeclasses and their associated annotations include:
203+
204+- `PostBuild`
205+ Fire an Event when an FRP network has been set up.
206+ ```haskell
207+ [B] -- Function runs in any monad supporting PostBuild
208+ ```
209+
210+- `Adjustable`
211+ Use Events to add or remove pieces of an FRP network.
212+ ```haskell
213+ [A] -- Function runs in any monad supporting Adjustable
214+ ```
215+
216+- `TriggerEvent`
217+ Create new externally-fired Events from within an FRP network.
218+ ```haskell
219+ [T] -- Function runs in any monad supporting TriggerEvent
220+ ```
221+
222+- `PerformEvent`
223+ Use Events to trigger IO actions and to collect their results.
224+ ```haskell
225+ [P] -- Function runs in any monad supporting PerformEvent
226+ ```
227+
228+## Startup
229+
230+```haskell
231+-- One-shot Event that is triggered once the FRP network has been built
232+[B] getPostBuild :: m (Event ())
233+```
234+
235+## Collection management functions
236+
237+```haskell
238+-- Turn a Dynamic key/value map into a set of dynamically-changing widgets.
239+[H,A,B] listWithKey :: Ord k =>
240+ Dynamic (Map k v) -> (k -> Dynamic v -> m a ) -> m (Dynamic (Map k a))
241+
242+-- Same as above where the widget constructor doesn't care about the key.
243+[H,A,B] list :: Ord k =>
244+ Dynamic (Map k v) -> ( Dynamic v -> m a ) -> m (Dynamic (Map k a))
245+
246+-- Even simpler version where there are no keys and we just use a list.
247+[H,A,B] simpleList ::
248+ Dynamic [v] -> ( Dynamic v -> m a ) -> m (Dynamic [a])
249+
250+-- Like listWithKey specialized for widgets returning (Event a).
251+[H,A,B] listViewWithKey :: Ord k =>
252+ Dynamic (Map k v) -> (k -> Dynamic v -> m (Event a)) -> m (Event (Map k a))
253+
254+-- Create a dynamically-changing set of widgets, one of which is selected at any time.
255+[H,A,B] selectViewListWithKey_ :: Ord k => Dynamic k ->
256+ Dynamic (Map k v) -> (k -> Dynamic v -> Dynamic Bool -> m (Event a)) -> m (Event k)
257+
258+-- Same as listWithKey, but takes initial values and an updates Event instead of a Dynamic.
259+[H,A] listWithKeyShallowDiff :: Ord k =>
260+ Map k v -> Event (Map k (Maybe v)) -> (k -> v -> Event v -> m a) -> m (Dynamic (Map k a))
261+```
262+
263+## Creating new events from within an FRP network.
264+
265+```haskell
266+-- Create a new Event and a function that will cause the Event to fire, from within an FRP network
267+[T] newTriggerEvent :: m (Event a, a -> IO ())
268+```
269+
270+## Connecting to the real world (I/O)
271+
272+```haskell
273+-- Run side-effecting actions in Event when it occurs; returned Event contains
274+-- results. Side effects run in the (Performable m) monad which is associated with
275+-- the (PerformEvent t m) typeclass constraint.
276+-- This allows for working with IO when a ((MonadIO (Performable m)) constraint is available.
277+[P] performEvent :: Event (Performable m a ) -> m (Event a)
278+
279+-- Just run side-effects; no return Event
280+[P] performEvent_ :: Event (Performable m ()) -> m ()
281+
282+-- Actions run asynchronously; actions are given a callback to send return values
283+[P,T] performEventAsync :: Event ((a -> IO ()) -> Performable m ()) -> m (Event a)
284+```
285+
286+### Time
287+
288+```haskell
289+-- Create Event at given interval with given basis time.
290+[P,T] tickLossy :: NominalDiffTime -> UTCTime -> m (Event t TickInfo)
291+
292+-- Delay an Event's occurrences by a given amount in seconds.
293+[P,T] delay :: NominalDiffTime -> Event t a -> m (Event t a)
294+```
295+
296+## Networks
297+
298+```haskell
299+-- Functions from Reflex.Adjustable / Reflex.Network used to deal with Dynamics/Events carrying (m a)
300+
301+[A] runWithReplace :: m a -> Event t (m b) -> m (a, Event t b)
302+
303+-- Given a Dynamic of network-creating actions, create a network that is recreated whenever the Dynamic updates.
304+-- The returned Event of network results occurs when the Dynamic does. Note: Often, the type a is an Event,
305+-- in which case the return value is an Event-of-Events that would typically be flattened (via switchHold).
306+[P,A] networkView :: Dynamic (m a) -> m (Event a)
307+
308+-- Given an initial network and an Event of network-creating actions, create a network that is recreated whenever the
309+-- Event fires. The returned Dynamic of network results occurs when the Event does. Note: Often, the type a is an
310+-- Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
311+[H,A] networkHold :: m a -> Event (m a) -> m (Dynamic a)
312+
313+-- Render a placeholder network to be shown while another network is not yet done building
314+[P,A] untilReady :: m a -> m b -> m (a, Event b)
315+```
README.mdnew file+23
@@ -0,0 +1,23 @@
1+# [Reflex](https://reflex-frp.org/)
2+
3+[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/reflex.svg)](https://hackage.haskell.org/package/reflex) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/reflex/badge)](https://matrix.hackage.haskell.org/#/package/reflex) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/reflex-frp/reflex/blob/master/LICENSE)
4+
5+Interactive programs without callbacks or side-effects. Functional Reactive Programming (FRP) uses composable events and time-varying values to describe interactive systems as pure functions. Just like other pure functional code, functional reactive code is easier to get right on the first try, maintain, and reuse.
6+
7+Reflex is a fully-deterministic, higher-order Functional Reactive Programming interface and an engine that efficiently implements that interface.
8+
9+**Visit https://reflex-frp.org for more information, tutorials, documentation and [examples](https://examples.reflex-frp.org/).**
10+
11+## Resources
12+
13+* [Official Website](https://reflex-frp.org)
14+* [Quick Reference](Quickref.md)
15+* [Reflex-DOM](https://github.com/reflex-frp/reflex-dom): A framework built on Reflex that facilitates the development of web pages, including highly-interactive single-page apps.
16+* [Obelisk](https://github.com/obsidiansystems/obelisk#obelisk): A framework built on Reflex and Reflex-DOM for functional reactive web and mobile applications, with batteries included.
17+* [Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
18+* [/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
19+* [irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
20+
21+## Hacking
22+
23+From the root of a [Reflex Platform](https://github.com/reflex-frp/reflex-platform) checkout, run `./scripts/hack-on haskell-overlays/reflex-packages/dep/reflex`. This will check out the reflex source code into the `haskell-overlays/reflex-packages/dep/reflex` directory. You can then point that checkout at your fork, make changes, etc. Use the `./try-reflex` or `./scripts/work-on` scripts to start a shell in which you can test your changes.
Setup.hsnew file+2
@@ -0,0 +1,2 @@
1+import Distribution.Simple
2+main = defaultMain
bench-cbits/checkCapability.cnew file+208
@@ -0,0 +1,208 @@
1+#include <Rts.h>
2+
3+// The InCall structure represents either a single in-call from C to
4+// Haskell, or a worker thread.
5+typedef struct InCall_ {
6+ StgTSO * tso; // the bound TSO (or NULL for a worker)
7+
8+ StgTSO * suspended_tso; // the TSO is stashed here when we
9+ // make a foreign call (NULL otherwise);
10+
11+ Capability *suspended_cap; // The capability that the
12+ // suspended_tso is on, because
13+ // we can't read this from the TSO
14+ // without owning a Capability in the
15+ // first place.
16+
17+ SchedulerStatus rstat; // return status
18+ StgClosure ** ret; // return value
19+
20+ struct Task_ *task;
21+
22+ // When a Haskell thread makes a foreign call that re-enters
23+ // Haskell, we end up with another Task associated with the
24+ // current thread. We have to remember the whole stack of InCalls
25+ // associated with the current Task so that we can correctly
26+ // save & restore the InCall on entry to and exit from Haskell.
27+ struct InCall_ *prev_stack;
28+
29+ // Links InCalls onto suspended_ccalls, spare_incalls
30+ struct InCall_ *prev;
31+ struct InCall_ *next;
32+} InCall;
33+
34+typedef struct Task_ {
35+#if defined(THREADED_RTS)
36+ OSThreadId id; // The OS Thread ID of this task
37+
38+ Condition cond; // used for sleeping & waking up this task
39+ Mutex lock; // lock for the condition variable
40+
41+ // this flag tells the task whether it should wait on task->cond
42+ // or just continue immediately. It's a workaround for the fact
43+ // that signalling a condition variable doesn't do anything if the
44+ // thread is already running, but we want it to be sticky.
45+ HsBool wakeup;
46+#endif
47+
48+ // This points to the Capability that the Task "belongs" to. If
49+ // the Task owns a Capability, then task->cap points to it. If
50+ // the task does not own a Capability, then either (a) if the task
51+ // is a worker, then task->cap points to the Capability it belongs
52+ // to, or (b) it is returning from a foreign call, then task->cap
53+ // points to the Capability with the returning_worker queue that this
54+ // this Task is on.
55+ //
56+ // When a task goes to sleep, it may be migrated to a different
57+ // Capability. Hence, we always check task->cap on wakeup. To
58+ // syncrhonise between the migrater and the migratee, task->lock
59+ // must be held when modifying task->cap.
60+ struct Capability_ *cap;
61+
62+ // The current top-of-stack InCall
63+ struct InCall_ *incall;
64+
65+ uint32_t n_spare_incalls;
66+ struct InCall_ *spare_incalls;
67+
68+ HsBool worker; // == rtsTrue if this is a worker Task
69+ HsBool stopped; // this task has stopped or exited Haskell
70+
71+ // So that we can detect when a finalizer illegally calls back into Haskell
72+ HsBool running_finalizers;
73+
74+ // Links tasks on the returning_tasks queue of a Capability, and
75+ // on spare_workers.
76+ struct Task_ *next;
77+
78+ // Links tasks on the all_tasks list; need ACQUIRE_LOCK(&all_tasks_mutex)
79+ struct Task_ *all_next;
80+ struct Task_ *all_prev;
81+
82+} Task;
83+
84+struct Capability_ {
85+ // State required by the STG virtual machine when running Haskell
86+ // code. During STG execution, the BaseReg register always points
87+ // to the StgRegTable of the current Capability (&cap->r).
88+ StgFunTable f;
89+ StgRegTable r;
90+
91+ uint32_t no; // capability number.
92+
93+ // The Task currently holding this Capability. This task has
94+ // exclusive access to the contents of this Capability (apart from
95+ // returning_tasks_hd/returning_tasks_tl).
96+ // Locks required: cap->lock.
97+ Task *running_task;
98+
99+ // true if this Capability is running Haskell code, used for
100+ // catching unsafe call-ins.
101+ HsBool in_haskell;
102+
103+ // Has there been any activity on this Capability since the last GC?
104+ uint32_t idle;
105+
106+ HsBool disabled;
107+
108+ // The run queue. The Task owning this Capability has exclusive
109+ // access to its run queue, so can wake up threads without
110+ // taking a lock, and the common path through the scheduler is
111+ // also lock-free.
112+ StgTSO *run_queue_hd;
113+ StgTSO *run_queue_tl;
114+
115+ // Tasks currently making safe foreign calls. Doubly-linked.
116+ // When returning, a task first acquires the Capability before
117+ // removing itself from this list, so that the GC can find all
118+ // the suspended TSOs easily. Hence, when migrating a Task from
119+ // the returning_tasks list, we must also migrate its entry from
120+ // this list.
121+ InCall *suspended_ccalls;
122+
123+ // One mutable list per generation, so we don't need to take any
124+ // locks when updating an old-generation thunk. This also lets us
125+ // keep track of which closures this CPU has been mutating, so we
126+ // can traverse them using the right thread during GC and avoid
127+ // unnecessarily moving the data from one cache to another.
128+ bdescr **mut_lists;
129+ bdescr **saved_mut_lists; // tmp use during GC
130+
131+ // block for allocating pinned objects into
132+ bdescr *pinned_object_block;
133+ // full pinned object blocks allocated since the last GC
134+ bdescr *pinned_object_blocks;
135+
136+ // per-capability weak pointer list associated with nursery (older
137+ // lists stored in generation object)
138+ StgWeak *weak_ptr_list_hd;
139+ StgWeak *weak_ptr_list_tl;
140+
141+ // Context switch flag. When non-zero, this means: stop running
142+ // Haskell code, and switch threads.
143+ int context_switch;
144+
145+ // Interrupt flag. Like the context_switch flag, this also
146+ // indicates that we should stop running Haskell code, but we do
147+ // *not* switch threads. This is used to stop a Capability in
148+ // order to do GC, for example.
149+ //
150+ // The interrupt flag is always reset before we start running
151+ // Haskell code, unlike the context_switch flag which is only
152+ // reset after we have executed the context switch.
153+ int interrupt;
154+
155+ // Total words allocated by this cap since rts start
156+ // See [Note allocation accounting] in Storage.c
157+ W_ total_allocated;
158+
159+#if defined(THREADED_RTS)
160+ // Worker Tasks waiting in the wings. Singly-linked.
161+ Task *spare_workers;
162+ uint32_t n_spare_workers; // count of above
163+
164+ // This lock protects:
165+ // running_task
166+ // returning_tasks_{hd,tl}
167+ // wakeup_queue
168+ // inbox
169+ Mutex lock;
170+
171+ // Tasks waiting to return from a foreign call, or waiting to make
172+ // a new call-in using this Capability (NULL if empty).
173+ // NB. this field needs to be modified by tasks other than the
174+ // running_task, so it requires cap->lock to modify. A task can
175+ // check whether it is NULL without taking the lock, however.
176+ Task *returning_tasks_hd; // Singly-linked, with head/tail
177+ Task *returning_tasks_tl;
178+
179+ // Messages, or END_TSO_QUEUE.
180+ // Locks required: cap->lock
181+ Message *inbox;
182+
183+ SparkPool *sparks;
184+
185+ // Stats on spark creation/conversion
186+ SparkCounters spark_stats;
187+#if !defined(mingw32_HOST_OS)
188+ // IO manager for this cap
189+ int io_manager_control_wr_fd;
190+#endif
191+#endif
192+
193+ // Per-capability STM-related data
194+ StgTVarWatchQueue *free_tvar_watch_queues;
195+ StgTRecChunk *free_trec_chunks;
196+ StgTRecHeader *free_trec_headers;
197+ uint32_t transaction_tokens;
198+} // typedef Capability is defined in RtsAPI.h
199+ // We never want a Capability to overlap a cache line with anything
200+ // else, so round it up to a cache line size:
201+#ifndef mingw32_HOST_OS
202+ ATTRIBUTE_ALIGNED(64)
203+#endif
204+ ;
205+
206+HsBool myCapabilityHasOtherRunnableThreads() {
207+ return rts_unsafeGetMyCapability()->run_queue_hd == END_TSO_QUEUE ? HS_BOOL_FALSE : HS_BOOL_TRUE;
208+}
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+23
@@ -0,0 +1,23 @@
1+distribution: xenial
2+benchmarks: False
3+unconstrained: False
4+installed: -all
5+
6+-- https://github.com/haskell/cabal/issues/6106
7+install-dependencies: False
8+
9+constraint-set no-th
10+ constraints: reflex -use-template-haskell
11+
12+constraint-set old-these
13+ ghc: <8.8
14+ constraints: these <1
15+
16+constraint-set old-witherable
17+ constraints: witherable <0.3.2
18+
19+constraint-set debug-propagation
20+ constraints: reflex +debug-propagation
21+
22+constraint-set debug-cycles
23+ constraints: reflex +debug-cycles
cabal.projectnew file+1
@@ -0,0 +1 @@
1+packages: .
default.nixdeleted−12
@@ -1,12 +0,0 @@
1−{ mkDerivation, dependent-map, dependent-sum, lens
2−, mtl, semigroups, these
3−}:
4−mkDerivation {
5− pname = "reflex";
6− version = "0.1";
7− src = builtins.filterSource (path: type: baseNameOf path != ".git") ./.;
8− buildDepends = [
9− dependent-map dependent-sum lens mtl semigroups these
10− ];
11− license = null;
12−}
dep/reflex-platform/default.nixnew file+7
@@ -0,0 +1,7 @@
1+# DO NOT HAND-EDIT THIS FILE
2+import ((import <nixpkgs> {}).fetchFromGitHub (
3+ let json = builtins.fromJSON (builtins.readFile ./github.json);
4+ in { inherit (json) owner repo rev sha256;
5+ private = json.private or false;
6+ }
7+))
dep/reflex-platform/github.jsonnew file+7
@@ -0,0 +1,7 @@
1+{
2+ "owner": "reflex-frp",
3+ "repo": "reflex-platform",
4+ "branch": "develop",
5+ "rev": "f628398d076243a0851b27e625b37f65dff9b89b",
6+ "sha256": "0sl0hf1glgyb1vmf2mhw4r9ipmcqk1y19d3wsic7dix2jwywzrh9"
7+}
reflex.cabal+478−26
@@ -1,7 +1,17 @@
11Name: reflex
2−Version: 0.0.1
2+Version: 0.8.2.0
33Synopsis: Higher-order Functional Reactive Programming
4−Description: Reflex is a high-performance, deterministic, higher-order Functional Reactive Programming system
4+Description:
5+ Interactive programs without callbacks or side-effects.
6+ Functional Reactive Programming (FRP) uses composable events and time-varying
7+ values to describe interactive systems as pure functions.
8+ Just like other pure functional code, functional reactive code is easier
9+ to get right on the first try, maintain, and reuse.
10+ .
11+ Reflex is a fully-deterministic, higher-order Functional Reactive Programming
12+ interface and an engine that efficiently implements that interface.
13+ .
14+ <https://reflex-frp.org>
515License: BSD3
616License-file: LICENSE
717Author: Ryan Trinkle
@@ -9,40 +19,482 @@ Maintainer: ryan.trinkle@gmail.com
919Stability: Experimental
1020Category: FRP
1121Build-type: Simple
12−Cabal-version: >=1.9.2
13−homepage: https://github.com/ryantrinkle/reflex
14−bug-reports: https://github.com/ryantrinkle/reflex/issues
22+Cabal-version: 1.22
23+homepage: https://reflex-frp.org
24+bug-reports: https://github.com/reflex-frp/reflex/issues
25+extra-source-files:
26+ README.md
27+ Quickref.md
28+ ChangeLog.md
29+
30+tested-with:
31+ GHC ==8.4.4 || ==8.6.5 || ==8.8.1 || ==8.10.2,
32+ GHCJS ==8.6
33+
34+flag use-reflex-optimizer
35+ description: Use the GHC plugin Reflex.Optimizer on some of the modules in the package. This is still experimental.
36+ default: False
37+ manual: True
38+
39+flag use-template-haskell
40+ description: Use template haskell to generate lenses
41+ default: True
42+ manual: True
43+
44+flag debug-trace-events
45+ description: Add instrumentation that outputs the stack trace of the definition of an event whenever it is subscribed to. Warning: It is very slow!
46+ default: False
47+ manual: True
48+
49+flag fast-weak
50+ 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
51+ default: False
52+ manual: True
53+
54+flag debug-propagation
55+ description: Enable debugging of spider internals
56+ default: False
57+ manual: True
58+
59+flag debug-cycles
60+ description: Enable debugging of event cycles
61+ default: False
62+ manual: True
63+
64+flag split-these
65+ description: Use split these/semialign packages
66+ manual: False
67+ default: True
1568
1669library
70+ default-language: Haskell2010
1771 hs-source-dirs: src
1872 build-depends:
19− base >= 4.7 && < 4.9,
20− dependent-sum == 0.2.*,
21− dependent-map == 0.1.*,
22− semigroups == 0.16.*,
23− mtl == 2.2.*,
24− containers == 0.5.*,
25− these == 0.4.*,
26− lens >= 4.7 && < 4.9,
27− primitive == 0.5.*,
28− template-haskell >= 2.9 && < 2.11
73+ MemoTrie == 0.6.*,
74+ base >= 4.11 && < 4.15,
75+ bifunctors >= 5.2 && < 5.6,
76+ comonad >= 5.0.4 && < 5.1,
77+ constraints >= 0.10 && <0.14,
78+ constraints-extras >= 0.3 && < 0.4,
79+ containers >= 0.6 && < 0.7,
80+ data-default >= 0.5 && < 0.8,
81+ dependent-map >= 0.3 && < 0.5,
82+ exception-transformers == 0.4.*,
83+ lens >= 4.7 && < 5,
84+ mmorph >= 1.0 && < 1.2,
85+ monad-control >= 1.0.1 && < 1.1,
86+ mtl >= 2.1 && < 2.3,
87+ patch >= 0.0.1 && < 0.1,
88+ prim-uniq >= 0.1.0.1 && < 0.3,
89+ primitive >= 0.5 && < 0.8,
90+ profunctors >= 5.3 && < 5.7,
91+ random == 1.1.*,
92+ ref-tf == 0.4.*,
93+ reflection == 2.1.*,
94+ semigroupoids >= 4.0 && < 6,
95+ stm >= 2.4 && < 2.6,
96+ syb >= 0.5 && < 0.8,
97+ time >= 1.4 && < 1.10,
98+ transformers >= 0.5.6.0 && < 0.6,
99+ unbounded-delays >= 0.1.0.0 && < 0.2,
100+ witherable >= 0.3 && < 0.5
101+
102+ if flag(split-these)
103+ build-depends: these >= 1 && <1.2,
104+ semialign >=1 && <1.2,
105+ monoidal-containers >= 0.6 && < 0.7
106+ else
107+ build-depends: these >= 0.4 && <0.9,
108+ monoidal-containers == 0.4.0.0
29109
30110 exposed-modules:
111+ Control.Monad.ReaderIO
112+ Data.AppendMap,
113+ Data.FastMutableIntMap,
114+ Data.FastWeakBag,
115+ Data.Map.Misc,
116+ Data.WeakBag,
31117 Reflex,
32− Reflex.Spider,
33− Reflex.Spider.Internal,
34118 Reflex.Class,
119+ Reflex.Adjustable.Class,
120+ Reflex.BehaviorWriter.Base,
121+ Reflex.BehaviorWriter.Class,
122+ Reflex.Collection,
35123 Reflex.Dynamic,
36− Reflex.Dynamic.TH,
124+ Reflex.Dynamic.Uniq,
125+ Reflex.DynamicWriter,
126+ Reflex.DynamicWriter.Base,
127+ Reflex.DynamicWriter.Class,
128+ Reflex.EventWriter,
129+ Reflex.EventWriter.Base,
130+ Reflex.EventWriter.Class,
131+ Reflex.FastWeak,
132+ Reflex.FunctorMaybe,
37133 Reflex.Host.Class,
38− Data.Functor.Misc,
39− Control.Monad.TypedId,
40− Control.Monad.Ref
134+ Reflex.Host.Headless,
135+ Reflex.Network,
136+ Reflex.NotReady.Class,
137+ Reflex.PerformEvent.Base,
138+ Reflex.PerformEvent.Class,
139+ Reflex.PostBuild.Base,
140+ Reflex.PostBuild.Class,
141+ Reflex.Profiled,
142+ Reflex.Pure,
143+ Reflex.Query.Base,
144+ Reflex.Query.Class,
145+ Reflex.Requester.Base,
146+ Reflex.Requester.Class,
147+ Reflex.Spider,
148+ Reflex.Spider.Internal,
149+ Reflex.Time,
150+ Reflex.TriggerEvent.Base,
151+ Reflex.TriggerEvent.Class,
152+ Reflex.Widget.Basic,
153+ Reflex.Workflow
154+
155+ reexported-modules:
156+ patch:Data.Functor.Misc,
157+ patch:Data.Patch as Reflex.Patch,
158+ patch:Data.Patch.Class as Reflex.Patch.Class,
159+ patch:Data.Patch.DMap as Reflex.Patch.DMap,
160+ patch:Data.Patch.DMapWithMove as Reflex.Patch.DMapWithMove,
161+ patch:Data.Patch.IntMap as Reflex.Patch.IntMap,
162+ patch:Data.Patch.Map as Reflex.Patch.Map,
163+ patch:Data.Patch.MapWithMove as Reflex.Patch.MapWithMove
164+
165+ ghc-options: -Wall -fwarn-redundant-constraints -fwarn-tabs -funbox-strict-fields -O2 -fspecialise-aggressively
166+
167+ if flag(debug-trace-events)
168+ cpp-options: -DDEBUG_TRACE_EVENTS
169+ build-depends:
170+ bytestring >= 0.10.8 && < 0.11
171+
172+ if flag(use-reflex-optimizer)
173+ cpp-options: -DUSE_REFLEX_OPTIMIZER
174+ build-depends: ghc
175+ exposed-modules: Reflex.Optimizer
176+
177+ if flag(debug-propagation)
178+ cpp-options: -DDEBUG -DDEBUG_TRACE_PROPAGATION -DDEBUG_TRACE_INVALIDATION
179+
180+ if flag(debug-cycles)
181+ cpp-options: -DDEBUG_CYCLES
182+
183+ if flag(use-template-haskell)
184+ cpp-options: -DUSE_TEMPLATE_HASKELL
185+ build-depends:
186+ dependent-sum >= 0.6 && < 0.8,
187+ haskell-src-exts >= 1.16 && < 1.24,
188+ haskell-src-meta >= 0.6 && < 0.9,
189+ template-haskell >= 2.9 && < 2.17
190+ exposed-modules:
191+ Reflex.Dynamic.TH
192+ other-extensions: TemplateHaskell
193+ else
194+ build-depends:
195+ dependent-sum >= 0.6 && < 0.8
196+
197+ if flag(fast-weak) && impl(ghcjs)
198+ cpp-options: -DGHCJS_FAST_WEAK
199+
200+ if impl(ghcjs)
201+ build-depends:
202+ ghcjs-base == 0.2.*
203+
204+test-suite semantics
205+ default-language: Haskell2010
206+ type: exitcode-stdio-1.0
207+ main-is: semantics.hs
208+ hs-source-dirs: test
209+ ghc-options: -O2 -Wall -rtsopts
210+ build-depends:
211+ base,
212+ bifunctors,
213+ containers,
214+ deepseq,
215+ dependent-map,
216+ dependent-sum,
217+ mtl,
218+ ref-tf,
219+ reflex,
220+ split,
221+ transformers
222+ other-modules:
223+ Reflex.Bench.Focused
224+ Reflex.Plan.Pure
225+ Reflex.Plan.Reflex
226+ Reflex.Test
227+ Reflex.Test.Micro
228+ Reflex.TestPlan
229+
230+test-suite CrossImpl
231+ default-language: Haskell2010
232+ type: exitcode-stdio-1.0
233+ main-is: Reflex/Test/CrossImpl.hs
234+ hs-source-dirs: test
235+ ghc-options: -O2 -Wall -rtsopts
236+ build-depends:
237+ base,
238+ containers,
239+ dependent-map,
240+ dependent-sum,
241+ deepseq,
242+ mtl,
243+ transformers,
244+ ref-tf,
245+ reflex
246+ other-modules:
247+ Reflex.Test
248+ Reflex.TestPlan
249+ Reflex.Plan.Reflex
250+ Reflex.Plan.Pure
41251
42− other-extensions: TemplateHaskell
43− ghc-prof-options: -fprof-auto
44− ghc-options: -threaded -Wall -fwarn-tabs -funbox-strict-fields -O2
252+test-suite hlint
253+ default-language: Haskell2010
254+ type: exitcode-stdio-1.0
255+ main-is: hlint.hs
256+ hs-source-dirs: test
257+ build-depends: base
258+ , directory
259+ , filepath
260+ , filemanip
261+ if impl(ghc >= 8.8)
262+ build-depends: hlint >= 3 && < 4
263+ else
264+ build-depends: hlint (< 2.1 || >= 2.2.2) && < 4
265+ if impl(ghcjs)
266+ buildable: False
267+
268+test-suite EventWriterT
269+ default-language: Haskell2010
270+ type: exitcode-stdio-1.0
271+ main-is: EventWriterT.hs
272+ hs-source-dirs: test
273+ build-depends: base
274+ , containers
275+ , deepseq
276+ , dependent-map
277+ , dependent-sum
278+ , lens
279+ , mtl
280+ , these
281+ , transformers
282+ , reflex
283+ , ref-tf
284+
285+ if flag(split-these)
286+ build-depends: these-lens
287+
288+ other-modules:
289+ Test.Run
290+
291+
292+test-suite DebugCycles
293+ default-language: Haskell2010
294+ type: exitcode-stdio-1.0
295+ main-is: DebugCycles.hs
296+ hs-source-dirs: test
297+ ghc-options: -threaded
298+ build-depends: base
299+ , containers
300+ , deepseq
301+ , dependent-map
302+ , dependent-sum
303+ , hspec
304+ , lens
305+ , mtl
306+ , these
307+ , transformers
308+ , reflex
309+ , ref-tf
310+ , witherable
311+ , proctest
312+
313+
314+ if flag(split-these)
315+ build-depends: these-lens, semialign
316+
317+ other-modules:
318+ Test.Run
319+
320+
321+test-suite RequesterT
322+ default-language: Haskell2010
323+ type: exitcode-stdio-1.0
324+ main-is: RequesterT.hs
325+ hs-source-dirs: test
326+ build-depends: base
327+ , constraints
328+ , constraints-extras
329+ , containers
330+ , deepseq
331+ , dependent-map
332+ , dependent-sum
333+ , lens
334+ , mtl
335+ , ref-tf
336+ , reflex
337+ , text
338+ , these
339+ , transformers
340+
341+ if flag(split-these)
342+ build-depends: these-lens
343+
344+ other-modules:
345+ Reflex.TestPlan
346+ Reflex.Plan.Pure
347+ Test.Run
348+
349+test-suite Headless
350+ default-language: Haskell2010
351+ type: exitcode-stdio-1.0
352+ main-is: Headless.hs
353+ hs-source-dirs: test
354+ build-depends: base
355+ , reflex
356+
357+test-suite Adjustable
358+ default-language: Haskell2010
359+ type: exitcode-stdio-1.0
360+ main-is: Adjustable.hs
361+ hs-source-dirs: test
362+ build-depends: base
363+ , containers
364+ , dependent-sum
365+ , reflex
366+ , ref-tf
367+ , these
368+
369+ other-modules:
370+ Test.Run
371+
372+test-suite QueryT
373+ default-language: Haskell2010
374+ type: exitcode-stdio-1.0
375+ main-is: QueryT.hs
376+ hs-source-dirs: test
377+ build-depends: base
378+ , containers
379+ , dependent-map
380+ , dependent-sum
381+ , deepseq
382+ , lens
383+ , monoidal-containers
384+ , mtl
385+ , patch
386+ , ref-tf
387+ , reflex
388+ , these
389+ , transformers
390+
391+ if flag(split-these)
392+ build-depends: semialign, these-lens
393+
394+ other-modules:
395+ Test.Run
396+ Reflex.TestPlan
397+ Reflex.Plan.Reflex
398+ Reflex.Plan.Pure
399+
400+test-suite GC-Semantics
401+ default-language: Haskell2010
402+ type: exitcode-stdio-1.0
403+ main-is: GC.hs
404+ hs-source-dirs: test
405+ build-depends: base
406+ , containers
407+ , dependent-sum
408+ , dependent-map
409+ , deepseq
410+ , mtl
411+ , patch
412+ , these
413+ , transformers
414+ , reflex
415+ , ref-tf
416+
417+ if flag(split-these)
418+ build-depends: semialign
419+
420+ other-modules:
421+ Reflex.Plan.Pure
422+ Reflex.Plan.Reflex
423+ Reflex.TestPlan
424+ Test.Run
425+
426+test-suite rootCleanup
427+ default-language: Haskell2010
428+ type: exitcode-stdio-1.0
429+ main-is: rootCleanup.hs
430+ hs-source-dirs: test
431+ build-depends: base
432+ , containers
433+ , deepseq
434+ , dependent-sum
435+ , mtl
436+ , reflex
437+ , ref-tf
438+ , these
439+ other-modules:
440+ Reflex.Plan.Pure
441+ Reflex.TestPlan
442+ Test.Run
443+
444+benchmark spider-bench
445+ default-language: Haskell2010
446+ type: exitcode-stdio-1.0
447+ hs-source-dirs: bench test
448+ main-is: Main.hs
449+ ghc-options: -Wall -O2 -rtsopts
450+ build-depends:
451+ base,
452+ containers,
453+ criterion,
454+ deepseq,
455+ dependent-map,
456+ dependent-sum,
457+ ref-tf,
458+ mtl,
459+ primitive,
460+ reflex,
461+ split,
462+ stm,
463+ transformers
464+ other-modules:
465+ Reflex.TestPlan
466+ Reflex.Plan.Reflex
467+ Reflex.Bench.Focused
468+
469+benchmark saulzar-bench
470+ default-language: Haskell2010
471+ type: exitcode-stdio-1.0
472+ hs-source-dirs: bench test
473+ c-sources: bench-cbits/checkCapability.c
474+ main-is: RunAll.hs
475+ ghc-options: -Wall -O2 -rtsopts -threaded
476+ build-depends:
477+ base,
478+ containers,
479+ criterion,
480+ deepseq,
481+ dependent-map,
482+ dependent-sum,
483+ loch-th,
484+ mtl,
485+ primitive,
486+ process,
487+ ref-tf,
488+ reflex,
489+ split,
490+ stm,
491+ time,
492+ transformers
493+ other-modules:
494+ Reflex.TestPlan
495+ Reflex.Plan.Reflex
496+ Reflex.Bench.Focused
45497
46498source-repository head
47− type: git
48− location: https://github.com/ryantrinkle/reflex.git
499+ type: git
500+ location: https://github.com/reflex-frp/reflex
release.nixnew file+58
@@ -0,0 +1,58 @@
1+{ reflex-platform-fun ? import ./dep/reflex-platform
2+, supportedSystems ? ["x86_64-linux" "x86_64-darwin"]
3+}:
4+
5+let
6+ native-reflex-platform = reflex-platform-fun {};
7+ inherit (native-reflex-platform.nixpkgs) lib;
8+
9+ perPlatform = lib.genAttrs supportedSystems (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+ variations = map (v: "reflex" + v) [
21+ "-dontUseTemplateHaskell"
22+ ""
23+ ];
24+ compilerPkgs = lib.genAttrs compilers (ghc: let
25+ variationPkgs = lib.genAttrs variations (variation: let
26+ reflex-platform = reflex-platform-fun {
27+ inherit system;
28+ __useTemplateHaskell = variation == "reflex"; # TODO hack
29+ haskellOverlays = [
30+ # Use this package's source for reflex
31+ (self: super: {
32+ _dep = super._dep // {
33+ reflex = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
34+ "release.nix"
35+ ".git"
36+ "dist"
37+ "cabal.haskell-ci"
38+ "cabal.project"
39+ ".travis.yml"
40+ ])) ./.;
41+ };
42+ })
43+ ];
44+ };
45+ in reflex-platform.${ghc}.reflex);
46+ in variationPkgs // {
47+ cache = reflex-platform.pinBuildInputs "reflex-${system}-${ghc}"
48+ (builtins.attrValues variationPkgs);
49+ });
50+ in compilerPkgs // {
51+ cache = reflex-platform.pinBuildInputs "reflex-${system}"
52+ (map (a: a.cache) (builtins.attrValues compilerPkgs));
53+ });
54+
55+ metaCache = native-reflex-platform.pinBuildInputs "reflex-everywhere"
56+ (map (a: a.cache) (builtins.attrValues perPlatform));
57+
58+in perPlatform // { inherit metaCache; }
src/Control/Monad/ReaderIO.hsnew file+60
@@ -0,0 +1,60 @@
1+{-# language RoleAnnotations #-}
2+{-# language MultiParamTypeClasses #-}
3+{-# language FlexibleInstances #-}
4+{-# language CPP #-}
5+module Control.Monad.ReaderIO
6+ (
7+ ReaderIO (..)
8+ )
9+ where
10+
11+import Control.Monad.Fix
12+#if MIN_VERSION_base(4,10,0)
13+import Control.Applicative
14+#endif
15+import Control.Monad
16+import Control.Monad.Reader.Class
17+import Control.Monad.IO.Class
18+
19+-- | An approximate clone of @RIO@ from the @rio@ package, but not based on
20+-- @ReaderT@. The trouble with @ReaderT@ is that its third type argument has a
21+-- @nominal@ role, so we can't coerce through it when it's wrapped in some
22+-- other @data@ type. Ugh.
23+newtype ReaderIO e a = ReaderIO { runReaderIO :: e -> IO a }
24+type role ReaderIO representational representational
25+
26+instance Functor (ReaderIO e) where
27+ fmap = liftM
28+ {-# INLINE fmap #-}
29+ a <$ m = m >> pure a
30+ {-# INLINE (<$) #-}
31+
32+instance Applicative (ReaderIO e) where
33+ pure a = ReaderIO $ \_ -> pure a
34+ {-# INLINE pure #-}
35+ (<*>) = ap
36+ {-# INLINE (<*>) #-}
37+#if MIN_VERSION_base(4,10,0)
38+ liftA2 = liftM2
39+ {-# INLINE liftA2 #-}
40+#endif
41+ (*>) = (>>)
42+ {-# INLINE (*>) #-}
43+
44+instance Monad (ReaderIO e) where
45+ ReaderIO q >>= f = ReaderIO $ \e -> q e >>= \a -> runReaderIO (f a) e
46+ {-# INLINE (>>=) #-}
47+
48+instance MonadFix (ReaderIO e) where
49+ mfix f = ReaderIO $ \e -> mfix $ \r -> runReaderIO (f r) e
50+ {-# INLINE mfix #-}
51+
52+instance MonadIO (ReaderIO e) where
53+ liftIO m = ReaderIO $ \_ -> m
54+ {-# INLINE liftIO #-}
55+
56+instance MonadReader e (ReaderIO e) where
57+ ask = ReaderIO pure
58+ {-# INLINE ask #-}
59+ local f (ReaderIO m) = ReaderIO (m . f)
60+ {-# INLINE local #-}
src/Control/Monad/Ref.hsdeleted−85
@@ -1,85 +0,0 @@
1−{-# LANGUAGE RecursiveDo, TypeFamilies, LambdaCase #-}
2−module Control.Monad.Ref where
3−
4−import Control.Monad
5−import Control.Monad.Trans
6−import Control.Monad.Reader
7−import Control.Monad.Writer
8−import Data.IORef
9−
10−class Monad m => MonadRef m where
11− type Ref m :: * -> *
12− newRef :: a -> m (Ref m a)
13− readRef :: Ref m a -> m a
14− writeRef :: Ref m a -> a -> m ()
15− atomicModifyRef :: Ref m a -> (a -> (a, b)) -> m b
16−
17−instance MonadRef IO where
18− type Ref IO = IORef
19− {-# INLINE newRef #-}
20− newRef = newIORef
21− {-# INLINE readRef #-}
22− readRef = readIORef
23− {-# INLINE writeRef #-}
24− writeRef = writeIORef
25− {-# INLINE atomicModifyRef #-}
26− atomicModifyRef r f = do
27− result <- atomicModifyIORef' r f
28−-- evaluate =<< readIORef r --TODO: Verify that ghcjs now strictly evaluates the values in atomicModifyIORef', then remove this line
29− return result
30−
31−{-# INLINE cacheM #-}
32−cacheM :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a, m ())
33−cacheM a = do
34− r <- newRef undefined
35− let invalidate = writeRef r $ do
36− result <- a
37− writeRef r $ return result
38− return result
39− invalidate
40− return (join $ readRef r, invalidate)
41−
42−{-# INLINE cacheMWithTry #-}
43−cacheMWithTry :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a, m (Maybe a), m ())
44−cacheMWithTry a = do
45− r <- newRef $ Left a
46− let invalidate = writeRef r $ Left a
47− get = readRef r >>= \case
48− Left a' -> do
49− result <- a'
50− writeRef r $ Right result
51− return result
52− Right result -> return result
53− tryGet = readRef r >>= \case
54− Left _ -> return Nothing
55− Right result -> return $ Just result
56− return (get, tryGet, invalidate)
57−
58−-- | Not thread-safe or reentrant
59−{-# INLINE memoM #-}
60−memoM :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a)
61−memoM = liftM fst . cacheM
62−
63−{-# INLINE replaceRef #-}
64−replaceRef :: MonadRef m => Ref m a -> a -> m a
65−replaceRef r new = atomicModifyRef r $ \old -> (new, old)
66−
67−{-# INLINE modifyRef #-}
68−modifyRef :: MonadRef m => Ref m a -> (a -> a) -> m ()
69−modifyRef r f = atomicModifyRef r $ \a -> (f a, ())
70−
71−instance (Monoid w, MonadRef m) => MonadRef (WriterT w m) where
72− {-# SPECIALIZE instance Monoid w => MonadRef (WriterT w IO) #-}
73− type Ref (WriterT w m) = Ref m
74− newRef = lift . newRef
75− readRef = lift . readRef
76− writeRef r = lift . writeRef r
77− atomicModifyRef r f = lift $ atomicModifyRef r f
78−
79−instance MonadRef m => MonadRef (ReaderT r m) where
80− {-# SPECIALIZE instance MonadRef (ReaderT r IO) #-}
81− type Ref (ReaderT r m) = Ref m
82− newRef = lift . newRef
83− readRef = lift . readRef
84− writeRef r = lift . writeRef r
85− atomicModifyRef r f = lift $ atomicModifyRef r f
src/Control/Monad/TypedId.hsdeleted−50
@@ -1,50 +0,0 @@
1−{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
2−module Control.Monad.TypedId ( MonadTypedId (..)
3− ) where
4−
5−import Data.GADT.Compare
6−import Data.IORef
7−
8−import Control.Monad.State
9−import Control.Monad.Reader
10−
11−import Unsafe.Coerce
12−import System.IO.Unsafe
13−
14−class (Monad m, GCompare (TypedId m)) => MonadTypedId m where
15− type TypedId m :: * -> *
16− getTypedId :: m (TypedId m a)
17−
18−nextTypedIdIO :: IORef Int
19−{-# NOINLINE nextTypedIdIO #-}
20−nextTypedIdIO = unsafePerformIO $ newIORef 1
21−
22−newtype TypedId_IO a = TypedId_IO Int deriving (Show)
23−
24−instance MonadTypedId IO where
25− type TypedId IO = TypedId_IO
26− {-# INLINE getTypedId #-}
27− getTypedId = do
28− n <- atomicModifyIORef' nextTypedIdIO $ \n -> (succ n, n)
29− return $ TypedId_IO n
30−
31−instance GCompare TypedId_IO where
32− {-# INLINE gcompare #-}
33− TypedId_IO a `gcompare` TypedId_IO b = case a `compare` b of
34− LT -> GLT
35− EQ -> unsafeCoerce GEQ
36− GT -> GGT
37−
38−instance GEq TypedId_IO where
39− {-# INLINE geq #-}
40− TypedId_IO a `geq` TypedId_IO b = if a == b then Just $ unsafeCoerce Refl else Nothing
41−
42−instance MonadTypedId m => MonadTypedId (StateT s m) where
43− type TypedId (StateT s m) = TypedId m
44− {-# INLINE getTypedId #-}
45− getTypedId = lift getTypedId
46−
47−instance MonadTypedId m => MonadTypedId (ReaderT r m) where
48− type TypedId (ReaderT r m) = TypedId m
49− {-# INLINE getTypedId #-}
50− getTypedId = lift getTypedId
src/Data/AppendMap.hsnew file+84
@@ -0,0 +1,84 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE PatternSynonyms #-}
6+{-# LANGUAGE RoleAnnotations #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE TypeFamilies #-}
9+{-# OPTIONS_GHC -fno-warn-orphans #-}
10+-- |
11+-- Module:
12+-- Data.AppendMap
13+-- Description:
14+-- Instances and convenience functions for 'Data.Map.Monoidal'. We use
15+-- monoidal-containers to take advantage of its better monoid instance.
16+-- 'Data.Map' has @mappend = union@, which is left-biased. 'MonoidalMap'
17+-- has @mappend = unionWith mappend@ instead.
18+module Data.AppendMap
19+ ( module Data.AppendMap
20+ , module Data.Map.Monoidal
21+ ) where
22+
23+import Prelude hiding (null)
24+
25+import Data.Coerce
26+import Data.Default
27+import Data.Map (Map)
28+#if MIN_VERSION_containers(0,5,11)
29+import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith)
30+#else
31+import qualified Data.Map as Map (showTree, showTreeWith)
32+#endif
33+import qualified Data.Witherable as W
34+import Data.Map.Monoidal
35+import qualified Data.Map.Monoidal as MonoidalMap
36+
37+
38+{-# DEPRECATED AppendMap "Use 'MonoidalMap' instead" #-}
39+-- | AppendMap is a synonym for 'Data.Map.Monoidal.MonoidalMap'
40+type AppendMap = MonoidalMap
41+
42+{-# DEPRECATED _unAppendMap "Use 'getMonoidalMap' instead" #-}
43+-- | A synonym for 'getMonoidalMap'
44+_unAppendMap :: MonoidalMap k v -> Map k v
45+_unAppendMap = getMonoidalMap
46+
47+-- | Pattern synonym for 'MonoidalMap'
48+pattern AppendMap :: Map k v -> MonoidalMap k v
49+pattern AppendMap m = MonoidalMap m
50+
51+#if !MIN_VERSION_witherable(0,3,2)
52+instance W.Filterable (MonoidalMap k) where
53+ mapMaybe = MonoidalMap.mapMaybe
54+#endif
55+
56+-- | Deletes a key, returning 'Nothing' if the result is empty.
57+nonEmptyDelete :: Ord k => k -> MonoidalMap k a -> Maybe (MonoidalMap k a)
58+nonEmptyDelete k vs =
59+ let deleted = delete k vs
60+ in if null deleted
61+ then Nothing
62+ else Just deleted
63+
64+-- | Like 'mapMaybe' but indicates whether the resulting container is empty
65+mapMaybeNoNull :: (a -> Maybe b)
66+ -> MonoidalMap token a
67+ -> Maybe (MonoidalMap token b)
68+mapMaybeNoNull f as =
69+ let bs = mapMaybe f as
70+ in if null bs
71+ then Nothing
72+ else Just bs
73+
74+-- TODO: Move instances to `Data.Patch`
75+-- | Displays a 'MonoidalMap' as a tree. See 'Data.Map.Lazy.showTree' for details.
76+showTree :: forall k a. (Show k, Show a) => MonoidalMap k a -> String
77+showTree = coerce (Map.showTree :: Map k a -> String)
78+
79+-- | Displays a 'MonoidalMap' as a tree, using the supplied function to convert nodes to string.
80+showTreeWith :: forall k a. (k -> a -> String) -> Bool -> Bool -> MonoidalMap k a -> String
81+showTreeWith = coerce (Map.showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String)
82+
83+instance Default (MonoidalMap k a) where
84+ def = empty
src/Data/FastMutableIntMap.hsnew file+97
@@ -0,0 +1,97 @@
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+ , toList
25+ ) where
26+
27+--TODO: Pure JS version
28+--TODO: Fast copy to FastIntMap
29+--TODO: Fast patch type
30+
31+import Prelude hiding (lookup)
32+
33+import Control.Monad.IO.Class
34+import Data.Foldable (traverse_)
35+import Data.IntMap.Strict (IntMap)
36+import qualified Data.IntMap.Strict as IntMap
37+import Data.IORef
38+import Data.Patch.Class
39+import Data.Patch.IntMap
40+
41+-- | A 'FastMutableIntMap' holds a map of values of type @a@ and allows low-overhead modifications via IO.
42+-- Operations on 'FastMutableIntMap' run in IO.
43+newtype FastMutableIntMap a = FastMutableIntMap (IORef (IntMap a))
44+
45+-- | Create a new 'FastMutableIntMap' out of an 'IntMap'
46+new :: IntMap a -> IO (FastMutableIntMap a)
47+new m = FastMutableIntMap <$> newIORef m
48+
49+-- | Create a new empty 'FastMutableIntMap'
50+newEmpty :: IO (FastMutableIntMap a)
51+newEmpty = FastMutableIntMap <$> newIORef IntMap.empty
52+
53+-- | Insert an element into a 'FastMutableIntMap' at the given key
54+insert :: FastMutableIntMap a -> Int -> a -> IO ()
55+insert (FastMutableIntMap r) k v = modifyIORef' r $ IntMap.insert k v
56+
57+-- | Attempt to lookup an element by key in a 'FastMutableIntMap'
58+lookup :: FastMutableIntMap a -> Int -> IO (Maybe a)
59+lookup (FastMutableIntMap r) k = IntMap.lookup k <$> readIORef r
60+
61+-- | Runs the provided action over the intersection of a 'FastMutableIntMap' and an 'IntMap'
62+forIntersectionWithImmutable_ :: MonadIO m => FastMutableIntMap a -> IntMap b -> (a -> b -> m ()) -> m ()
63+forIntersectionWithImmutable_ (FastMutableIntMap r) b f = do
64+ a <- liftIO $ readIORef r
65+ traverse_ (uncurry f) $ IntMap.intersectionWith (,) a b
66+
67+-- | Runs the provided action over the values of a 'FastMutableIntMap'
68+for_ :: MonadIO m => FastMutableIntMap a -> (a -> m ()) -> m ()
69+for_ (FastMutableIntMap r) f = do
70+ a <- liftIO $ readIORef r
71+ traverse_ f a
72+
73+-- | Checks whether a 'FastMutableIntMap' is empty
74+isEmpty :: FastMutableIntMap a -> IO Bool
75+isEmpty (FastMutableIntMap r) = IntMap.null <$> readIORef r
76+
77+-- | Retrieves the size of a 'FastMutableIntMap'
78+size :: FastMutableIntMap a -> IO Int
79+size (FastMutableIntMap r) = IntMap.size <$> readIORef r
80+
81+-- | Make an immutable snapshot of the datastructure and clear it
82+getFrozenAndClear :: FastMutableIntMap a -> IO (IntMap a)
83+getFrozenAndClear (FastMutableIntMap r) = do
84+ result <- readIORef r
85+ writeIORef r IntMap.empty
86+ return result
87+
88+-- | Updates the value of a 'FastMutableIntMap' with the given patch (see 'Data.Patch.IntMap'),
89+-- and returns an 'IntMap' with the modified keys and values.
90+applyPatch :: FastMutableIntMap a -> PatchIntMap a -> IO (IntMap a)
91+applyPatch (FastMutableIntMap r) p@(PatchIntMap m) = do
92+ v <- readIORef r
93+ writeIORef r $! applyAlways p v
94+ return $ IntMap.intersection v m
95+
96+toList :: FastMutableIntMap a -> IO [(Int, a)]
97+toList (FastMutableIntMap r) = IntMap.toList <$> readIORef r
src/Data/FastWeakBag.hsnew file+161
@@ -0,0 +1,161 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ExistentialQuantification #-}
3+#ifdef USE_REFLEX_OPTIMIZER
4+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5+#endif
6+#ifdef GHCJS_FAST_WEAK
7+{-# LANGUAGE ForeignFunctionInterface #-}
8+{-# LANGUAGE JavaScriptFFI #-}
9+#endif
10+-- | This module defines the 'FastWeakBag' type, which represents a mutable
11+-- collection of items that does not cause the items to be retained in memory.
12+-- This is useful for situations where a value needs to be inspected or modified
13+-- if it is still alive, but can be ignored if it is dead.
14+module Data.FastWeakBag
15+ ( FastWeakBag
16+ , FastWeakBagTicket
17+ , empty
18+ , isEmpty
19+ , insert
20+ , traverse
21+ , traverse_
22+ , remove
23+ -- * Internal functions
24+ -- These will not always be available.
25+#ifndef GHCJS_FAST_WEAK
26+ , _weakBag_children --TODO: Don't export this
27+#endif
28+ ) where
29+
30+import Prelude hiding (traverse)
31+
32+import Control.Monad
33+import Control.Monad.IO.Class
34+
35+#ifdef GHCJS_FAST_WEAK
36+import GHCJS.Types
37+import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)
38+#else
39+import Control.Exception
40+import Data.IntMap.Strict (IntMap)
41+import qualified Data.IntMap.Strict as IntMap
42+import Data.IORef
43+import System.Mem.Weak
44+#endif
45+
46+-- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them -
47+-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
48+-- alive, the 'FastWeakBag' will continue to refer to them.
49+#ifdef GHCJS_FAST_WEAK
50+newtype FastWeakBag a = FastWeakBag JSVal
51+#else
52+data FastWeakBag a = FastWeakBag
53+ { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
54+ , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'
55+ }
56+#endif
57+
58+-- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned. If
59+-- the caller retains the ticket, the item is guranteed to stay in memory (and
60+-- thus in the 'FastWeakBag'). The ticket can also be used to remove the item from
61+-- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.
62+#ifdef GHCJS_FAST_WEAK
63+newtype FastWeakBagTicket a = FastWeakBagTicket JSVal
64+#else
65+data FastWeakBagTicket a = FastWeakBagTicket
66+ { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
67+ , _weakBagTicket_item :: {-# NOUNPACK #-} !a
68+ }
69+#endif
70+
71+-- | Insert an item into a 'FastWeakBag'.
72+{-# INLINE insert #-}
73+insert :: a -- ^ The item
74+ -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into
75+ -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item
76+ -- is retained and allows the item to be removed.
77+#ifdef GHCJS_FAST_WEAK
78+insert a wb = js_insert (unsafeToRawJSVal a) wb
79+foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)
80+#else
81+insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do
82+ a' <- evaluate a
83+ myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
84+ let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())
85+ wa <- mkWeakPtr a' $ Just cleanup
86+ atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
87+ return $ FastWeakBagTicket
88+ { _weakBagTicket_weakItem = wa
89+ , _weakBagTicket_item = a'
90+ }
91+#endif
92+
93+-- | Create an empty 'FastWeakBag'.
94+{-# INLINE empty #-}
95+empty :: IO (FastWeakBag a)
96+#ifdef GHCJS_FAST_WEAK
97+empty = js_empty
98+foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)
99+#else
100+empty = {-# SCC "empty" #-} do
101+ nextId <- newIORef 1
102+ children <- newIORef IntMap.empty
103+ let bag = FastWeakBag
104+ { _weakBag_nextId = nextId
105+ , _weakBag_children = children
106+ }
107+ return bag
108+#endif
109+
110+-- | Check whether a 'FastWeakBag' is empty.
111+{-# INLINE isEmpty #-}
112+isEmpty :: FastWeakBag a -> IO Bool
113+#ifdef GHCJS_FAST_WEAK
114+isEmpty = js_isEmpty
115+foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time
116+#else
117+isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)
118+#endif
119+
120+{-# INLINE traverse_ #-}
121+-- | Visit every node in the given list. If new nodes are appended during the
122+-- traversal, they will not be visited. Every live node that was in the list
123+-- when the traversal began will be visited exactly once; however, no guarantee
124+-- is made about the order of the traversal.
125+traverse_ :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
126+#ifdef GHCJS_FAST_WEAK
127+traverse_ wb f = do
128+ let go cursor = when (not $ js_isNull cursor) $ do
129+ val <- liftIO $ js_getTicketValue cursor
130+ f $ unsafeFromRawJSVal val
131+ go =<< liftIO (js_getNext (FastWeakBagTicket cursor))
132+ go =<< liftIO (js_getInitial wb)
133+foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
134+foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal
135+--TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag
136+foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
137+#else
138+traverse_ (FastWeakBag _ children) f = {-# SCC "traverse_" #-} do
139+ cs <- liftIO $ readIORef children
140+ forM_ cs $ \c -> do
141+ ma <- liftIO $ deRefWeak c
142+ mapM_ f ma
143+#endif
144+
145+{-# DEPRECATED traverse "Use 'traverse_' instead" #-}
146+traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
147+traverse = traverse_
148+
149+-- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times
150+-- on the same 'FastWeakBagTicket'.
151+{-# INLINE remove #-}
152+remove :: FastWeakBagTicket a -> IO ()
153+#ifdef GHCJS_FAST_WEAK
154+remove = js_remove
155+foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here
156+#else
157+remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w
158+#endif
159+--TODO: Should 'remove' also drop the reference to the item?
160+
161+--TODO: can/should we provide a null FastWeakBagTicket?
src/Data/Functor/Misc.hsdeleted−71
@@ -1,71 +0,0 @@
1−{-# LANGUAGE KindSignatures, GADTs, DeriveDataTypeable, RankNTypes, ScopedTypeVariables #-}
2−module Data.Functor.Misc where
3−
4−import Data.GADT.Compare
5−import Data.Map (Map)
6−import qualified Data.Map as Map
7−import Data.Dependent.Map (DMap, DSum (..))
8−import qualified Data.Dependent.Map as DMap
9−import Data.Typeable hiding (Refl)
10−import Data.These
11−
12−data WrapArg :: (* -> *) -> (* -> *) -> * -> * where
13− WrapArg :: f a -> WrapArg g f (g a)
14−
15−instance GEq f => GEq (WrapArg g f) where
16− geq (WrapArg a) (WrapArg b) = fmap (\Refl -> Refl) $ geq a b
17−
18−instance GCompare f => GCompare (WrapArg g f) where
19− gcompare (WrapArg a) (WrapArg b) = case gcompare a b of
20− GLT -> GLT
21− GEQ -> GEQ
22− GGT -> GGT
23−
24−data Const2 :: * -> * -> * -> * where
25− Const2 :: k -> Const2 k v v
26− deriving (Typeable)
27−
28−instance Eq k => GEq (Const2 k v) where
29− geq (Const2 a) (Const2 b) =
30− if a == b
31− then Just Refl
32− else Nothing
33−
34−instance Ord k => GCompare (Const2 k v) where
35− gcompare (Const2 a) (Const2 b) = case compare a b of
36− LT -> GLT
37− EQ -> GEQ
38− GT -> GGT
39−
40−{-# INLINE sequenceDmap #-}
41−sequenceDmap :: (Monad m, GCompare f) => DMap (WrapArg m f) -> m (DMap f)
42−sequenceDmap = DMap.foldrWithKey (\(WrapArg k) mv mx -> mx >>= \x -> mv >>= \v -> return $ DMap.insert k v x) (return DMap.empty)
43−
44−{-# INLINE combineDMapsWithKey #-}
45−combineDMapsWithKey :: forall f g h i. GCompare f => (forall a. f a -> These (g a) (h a) -> i a) -> DMap (WrapArg g f) -> DMap (WrapArg h f) -> DMap (WrapArg i f)
46−combineDMapsWithKey f mg mh = DMap.fromList $ go (DMap.toList mg) (DMap.toList mh)
47− where go :: [DSum (WrapArg g f)] -> [DSum (WrapArg h f)] -> [DSum (WrapArg i f)]
48− go [] hs = map (\(WrapArg hk :=> hv) -> WrapArg hk :=> f hk (That hv)) hs
49− go gs [] = map (\(WrapArg gk :=> gv) -> WrapArg gk :=> f gk (This gv)) gs
50− go gs@((WrapArg gk :=> gv) : gs') hs@((WrapArg hk :=> hv) : hs') = case gk `gcompare` hk of
51− GLT -> (WrapArg gk :=> f gk (This gv)) : go gs' hs
52− GEQ -> (WrapArg gk :=> f gk (These gv hv)) : go gs' hs'
53− GGT -> (WrapArg hk :=> f hk (That hv)) : go gs hs'
54−
55−wrapDMap :: (forall a. a -> f a) -> DMap k -> DMap (WrapArg f k)
56−wrapDMap f = DMap.fromDistinctAscList . map (\(k :=> v) -> WrapArg k :=> f v) . DMap.toAscList
57−
58−rewrapDMap :: (forall a. f a -> g a) -> DMap (WrapArg f k) -> DMap (WrapArg g k)
59−rewrapDMap f = DMap.fromDistinctAscList . map (\(WrapArg k :=> v) -> WrapArg k :=> f v) . DMap.toAscList
60−
61−unwrapDMap :: (forall a. f a -> a) -> DMap (WrapArg f k) -> DMap k
62−unwrapDMap f = DMap.fromDistinctAscList . map (\(WrapArg k :=> v) -> k :=> f v) . DMap.toAscList
63−
64−mapToDMap :: Map k v -> DMap (Const2 k v)
65−mapToDMap = DMap.fromDistinctAscList . map (\(k, v) -> Const2 k :=> v) . Map.toAscList
66−
67−mapWithFunctorToDMap :: Map k (f v) -> DMap (WrapArg f (Const2 k v))
68−mapWithFunctorToDMap = DMap.fromDistinctAscList . map (\(k, v) -> WrapArg (Const2 k) :=> v) . Map.toAscList
69−
70−dmapToMap :: DMap (Const2 k v) -> Map k v
71−dmapToMap = Map.fromDistinctAscList . map (\(Const2 k :=> v) -> (k, v)) . DMap.toAscList
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 'Data.Patch.Map' and 'Data.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/WeakBag.hsnew file+126
@@ -0,0 +1,126 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ExistentialQuantification #-}
4+#ifdef USE_REFLEX_OPTIMIZER
5+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
6+#endif
7+-- | This module defines the 'WeakBag' type, which represents a mutable
8+-- collection of items that does not cause the items to be retained in memory.
9+-- This is useful for situations where a value needs to be inspected or modified
10+-- if it is still alive, but can be ignored if it is dead.
11+module Data.WeakBag
12+ ( WeakBag
13+ , WeakBagTicket
14+ , empty
15+ , singleton
16+ , insert
17+ , traverse
18+ , traverse_
19+ , remove
20+ -- * Internal functions
21+ -- These will not always be available.
22+ , _weakBag_children --TODO: Don't export this
23+ ) where
24+
25+import Prelude hiding (traverse)
26+
27+import Control.Exception
28+import Control.Monad
29+import Control.Monad.IO.Class
30+import Data.IntMap.Strict (IntMap)
31+import qualified Data.IntMap.Strict as IntMap
32+import Data.IORef
33+import System.Mem.Weak
34+
35+-- | A 'WeakBag' holds a set of values of type @/a/@, but does not retain them -
36+-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
37+-- alive, the 'WeakBag' will continue to refer to them.
38+data WeakBag a = WeakBag
39+ { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
40+ , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ The items referenced by the WeakBag
41+ }
42+
43+-- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned. If
44+-- the caller retains the ticket, the item is guranteed to stay in memory (and
45+-- thus in the 'WeakBag'). The ticket can also be used to remove the item from
46+-- the 'WeakBag' prematurely (i.e. while it is still alive), using 'remove'.
47+data WeakBagTicket = forall a. WeakBagTicket
48+ { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
49+ , _weakBagTicket_item :: {-# NOUNPACK #-} !a
50+ }
51+
52+-- | Insert an item into a 'WeakBag'.
53+{-# INLINE insert #-}
54+insert :: a -- ^ The item
55+ -> WeakBag a -- ^ The 'WeakBag' to insert into
56+ -> IORef (Weak b) -- ^ An arbitrary value to be used in the following
57+ -- callback
58+ -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed
59+ -- (whether automatically by the item being garbage
60+ -- collected or manually via 'remove')
61+ -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item
62+ -- is retained and allows the item to be removed.
63+insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do
64+ a' <- evaluate a
65+ wbRef' <- evaluate wbRef
66+ myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
67+ let cleanup = do
68+ wb <- readIORef wbRef'
69+ mb <- deRefWeak wb
70+ forM_ mb $ \b -> do
71+ csWithoutMe <- atomicModifyIORef children $ \cs ->
72+ let !csWithoutMe = IntMap.delete myId cs
73+ in (csWithoutMe, csWithoutMe)
74+ when (IntMap.null csWithoutMe) $ finalizer b
75+ wa <- mkWeakPtr a' $ Just cleanup
76+ atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
77+ return $ WeakBagTicket
78+ { _weakBagTicket_weakItem = wa
79+ , _weakBagTicket_item = a'
80+ }
81+
82+-- | Create an empty 'WeakBag'.
83+{-# INLINE empty #-}
84+empty :: IO (WeakBag a)
85+empty = {-# SCC "empty" #-} do
86+ nextId <- newIORef 1
87+ children <- newIORef IntMap.empty
88+ let bag = WeakBag
89+ { _weakBag_nextId = nextId
90+ , _weakBag_children = children
91+ }
92+ return bag
93+
94+-- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with
95+-- 'empty', then using 'insert'.
96+{-# INLINE singleton #-}
97+singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
98+singleton a wbRef finalizer = {-# SCC "singleton" #-} do
99+ bag <- empty
100+ ticket <- insert a bag wbRef finalizer
101+ return (bag, ticket)
102+
103+{-# INLINE traverse_ #-}
104+-- | Visit every node in the given list. If new nodes are appended during the
105+-- traversal, they will not be visited. Every live node that was in the list
106+-- when the traversal began will be visited exactly once; however, no guarantee
107+-- is made about the order of the traversal.
108+traverse_ :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
109+traverse_ (WeakBag _ children) f = {-# SCC "traverse" #-} do
110+ cs <- liftIO $ readIORef children
111+ forM_ cs $ \c -> do
112+ ma <- liftIO $ deRefWeak c
113+ mapM_ f ma
114+
115+{-# DEPRECATED traverse "Use 'traverse_' instead" #-}
116+traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
117+traverse = traverse_
118+
119+-- | Remove an item from the 'WeakBag'; does nothing if invoked multiple times
120+-- on the same 'WeakBagTicket'.
121+{-# INLINE remove #-}
122+remove :: WeakBagTicket -> IO ()
123+remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w
124+--TODO: Should 'remove' also drop the reference to the item?
125+
126+--TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hs+34−9
@@ -1,10 +1,35 @@
1−module Reflex ( module Reflex.Class
2− , module Reflex.Dynamic
3− , module Reflex.Dynamic.TH
4− , module Reflex.Spider
5− ) where
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
67
7−import Reflex.Class
8−import Reflex.Dynamic
9−import Reflex.Dynamic.TH
10−import Reflex.Spider
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+140
@@ -0,0 +1,140 @@
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)
34+import Data.GADT.Compare (GCompare(..))
35+import qualified Data.Dependent.Map as DMap
36+import Data.Functor.Constant
37+import Data.Functor.Misc
38+import Data.IntMap.Strict (IntMap)
39+import qualified Data.IntMap.Strict as IntMap
40+import Data.Map (Map)
41+
42+import Reflex.Class
43+import Data.Patch.DMapWithMove
44+
45+-- | A 'Monad' that supports adjustment over time. After an action has been
46+-- run, if the given events fire, it will adjust itself so that its net effect
47+-- is as though it had originally been run with the new value. Note that there
48+-- is some issue here with persistent side-effects: obviously, IO (and some
49+-- other side-effects) cannot be undone, so it is up to the instance implementer
50+-- to determine what the best meaning for this class is in such cases.
51+class (Reflex t, Monad m) => Adjustable t m | m -> t where
52+ runWithReplace
53+ :: m a
54+ -> Event t (m b)
55+ -> m (a, Event t b)
56+
57+ traverseIntMapWithKeyWithAdjust
58+ :: (IntMap.Key -> v -> m v')
59+ -> IntMap v
60+ -> Event t (PatchIntMap v)
61+ -> m (IntMap v', Event t (PatchIntMap v'))
62+
63+ traverseDMapWithKeyWithAdjust
64+ :: GCompare k
65+ => (forall a. k a -> v a -> m (v' a))
66+ -> DMap k v
67+ -> Event t (PatchDMap k v)
68+ -> m (DMap k v', Event t (PatchDMap k v'))
69+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
70+ traverseDMapWithKeyWithAdjust f dm0 dm' = fmap (fmap (fmap fromPatchWithMove)) $
71+ traverseDMapWithKeyWithAdjustWithMove f dm0 $ fmap toPatchWithMove dm'
72+ where
73+ toPatchWithMove (PatchDMap m) = PatchDMapWithMove $ DMap.map toNodeInfoWithMove m
74+ toNodeInfoWithMove = \case
75+ ComposeMaybe (Just v) -> NodeInfo (From_Insert v) $ ComposeMaybe Nothing
76+ ComposeMaybe Nothing -> NodeInfo From_Delete $ ComposeMaybe Nothing
77+ fromPatchWithMove (PatchDMapWithMove m) = PatchDMap $ DMap.map fromNodeInfoWithMove m
78+ fromNodeInfoWithMove (NodeInfo from _) = ComposeMaybe $ case from of
79+ From_Insert v -> Just v
80+ From_Delete -> Nothing
81+ From_Move _ -> error "traverseDMapWithKeyWithAdjust: implementation of traverseDMapWithKeyWithAdjustWithMove inserted spurious move"
82+
83+ traverseDMapWithKeyWithAdjustWithMove
84+ :: GCompare k
85+ => (forall a. k a -> v a -> m (v' a))
86+ -> DMap k v
87+ -> Event t (PatchDMapWithMove k v)
88+ -> m (DMap k v', Event t (PatchDMapWithMove k v'))
89+
90+instance Adjustable t m => Adjustable t (ReaderT r m) where
91+ runWithReplace a0 a' = do
92+ r <- ask
93+ lift $ runWithReplace (runReaderT a0 r) $ fmap (`runReaderT` r) a'
94+ traverseIntMapWithKeyWithAdjust f dm0 dm' = do
95+ r <- ask
96+ lift $ traverseIntMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm'
97+ traverseDMapWithKeyWithAdjust f dm0 dm' = do
98+ r <- ask
99+ lift $ traverseDMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm'
100+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
101+ r <- ask
102+ lift $ traverseDMapWithKeyWithAdjustWithMove (\k v -> runReaderT (f k v) r) dm0 dm'
103+
104+-- | Traverse a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches
105+-- to the 'DMap' can add, remove, or update values.
106+sequenceDMapWithAdjust
107+ :: (GCompare k, Adjustable t m)
108+ => DMap k m
109+ -> Event t (PatchDMap k m)
110+ -> m (DMap k Identity, Event t (PatchDMap k Identity))
111+sequenceDMapWithAdjust = traverseDMapWithKeyWithAdjust $ \_ -> fmap Identity
112+
113+-- | Traverses a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches
114+-- to the 'DMap' can add, remove, update, move, or swap values.
115+sequenceDMapWithAdjustWithMove
116+ :: (GCompare k, Adjustable t m)
117+ => DMap k m
118+ -> Event t (PatchDMapWithMove k m)
119+ -> m (DMap k Identity, Event t (PatchDMapWithMove k Identity))
120+sequenceDMapWithAdjustWithMove = traverseDMapWithKeyWithAdjustWithMove $ \_ -> fmap Identity
121+
122+-- | Traverses a 'Map', running the provided 'Adjustable' action. The provided 'Event' of patches to the 'Map'
123+-- can add, remove, update, move, or swap values.
124+mapMapWithAdjustWithMove
125+ :: forall t m k v v'. (Adjustable t m, Ord k)
126+ => (k -> v -> m v')
127+ -> Map k v
128+ -> Event t (PatchMapWithMove k v)
129+ -> m (Map k v', Event t (PatchMapWithMove k v'))
130+mapMapWithAdjustWithMove f m0 m' = do
131+ (out0 :: DMap (Const2 k v) (Constant v'), out') <- traverseDMapWithKeyWithAdjustWithMove (\(Const2 k) (Identity v) -> Constant <$> f k v) (mapToDMap m0) (const2PatchDMapWithMoveWith Identity <$> m')
132+ return (dmapToMapWith (\(Constant v') -> v') out0, patchDMapWithMoveToPatchMapWithMoveWith (\(Constant v') -> v') <$> out')
133+
134+--------------------------------------------------------------------------------
135+-- Deprecated functions
136+--------------------------------------------------------------------------------
137+
138+{-# DEPRECATED MonadAdjust "Use Adjustable instead" #-}
139+-- | Synonym for 'Adjustable'
140+type MonadAdjust = Adjustable
src/Reflex/BehaviorWriter/Base.hsnew file+211
@@ -0,0 +1,211 @@
1+{-|
2+Module: Reflex.BehaviorWriter.Base
3+Description: Implementation of BehaviorWriter
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.Morph
28+import Control.Monad.Reader
29+import Control.Monad.Ref
30+import Control.Monad.State.Strict
31+import Data.Dependent.Map (DMap)
32+import qualified Data.Dependent.Map as DMap
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.Some (Some)
39+
40+import Reflex.Class
41+import Reflex.Adjustable.Class
42+import Reflex.BehaviorWriter.Class
43+import Reflex.Host.Class
44+import Reflex.PerformEvent.Class
45+import Reflex.PostBuild.Class
46+import Reflex.Query.Class
47+import Reflex.Requester.Class
48+import Reflex.TriggerEvent.Class
49+
50+-- | A basic implementation of 'BehaviorWriter'.
51+newtype BehaviorWriterT t w m a = BehaviorWriterT { unBehaviorWriterT :: StateT [Behavior t w] m a }
52+ -- The list is kept in reverse order
53+ deriving
54+ ( Functor
55+ , Applicative
56+ , Monad
57+ , MonadTrans
58+ , MFunctor
59+ , MonadIO
60+ , MonadFix
61+ , MonadAsyncException
62+ , MonadException
63+ )
64+
65+-- | Run a 'BehaviorWriterT' action. The behavior writer output will be provided
66+-- along with the result of the action.
67+runBehaviorWriterT :: (Monad m, Reflex t, Monoid w) => BehaviorWriterT t w m a -> m (a, Behavior t w)
68+runBehaviorWriterT (BehaviorWriterT a) = do
69+ (result, ws) <- runStateT a []
70+ return (result, mconcat $ reverse ws)
71+
72+-- | Map a function over the output of a 'BehaviorWriterT'.
73+withBehaviorWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m)
74+ => (w -> w')
75+ -> BehaviorWriterT t w m a
76+ -> BehaviorWriterT t w' m a
77+withBehaviorWriterT f dw = do
78+ (r, d) <- lift $ do
79+ (r, d) <- runBehaviorWriterT dw
80+ let d' = fmap f d
81+ return (r, d')
82+ tellBehavior d
83+ return r
84+
85+deriving instance MonadHold t m => MonadHold t (BehaviorWriterT t w m)
86+deriving instance MonadSample t m => MonadSample t (BehaviorWriterT t w m)
87+
88+instance MonadRef m => MonadRef (BehaviorWriterT t w m) where
89+ type Ref (BehaviorWriterT t w m) = Ref m
90+ newRef = lift . newRef
91+ readRef = lift . readRef
92+ writeRef r = lift . writeRef r
93+
94+instance MonadAtomicRef m => MonadAtomicRef (BehaviorWriterT t w m) where
95+ atomicModifyRef r = lift . atomicModifyRef r
96+
97+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (BehaviorWriterT t w m) where
98+ newEventWithTrigger = lift . newEventWithTrigger
99+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
100+
101+instance (Monad m, Monoid w, Reflex t) => BehaviorWriter t w (BehaviorWriterT t w m) where
102+ tellBehavior w = BehaviorWriterT $ modify (w :)
103+
104+instance MonadReader r m => MonadReader r (BehaviorWriterT t w m) where
105+ ask = lift ask
106+ local f (BehaviorWriterT a) = BehaviorWriterT $ mapStateT (local f) a
107+ reader = lift . reader
108+
109+instance PerformEvent t m => PerformEvent t (BehaviorWriterT t w m) where
110+ type Performable (BehaviorWriterT t w m) = Performable m
111+ performEvent_ = lift . performEvent_
112+ performEvent = lift . performEvent
113+
114+instance TriggerEvent t m => TriggerEvent t (BehaviorWriterT t w m) where
115+ newTriggerEvent = lift newTriggerEvent
116+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
117+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
118+
119+instance PostBuild t m => PostBuild t (BehaviorWriterT t w m) where
120+ getPostBuild = lift getPostBuild
121+
122+instance MonadState s m => MonadState s (BehaviorWriterT t w m) where
123+ get = lift get
124+ put = lift . put
125+
126+instance Requester t m => Requester t (BehaviorWriterT t w m) where
127+ type Request (BehaviorWriterT t w m) = Request m
128+ type Response (BehaviorWriterT t w m) = Response m
129+ requesting = lift . requesting
130+ requesting_ = lift . requesting_
131+
132+instance (MonadQuery t q m, Monad m) => MonadQuery t q (BehaviorWriterT t w m) where
133+ tellQueryIncremental = lift . tellQueryIncremental
134+ askQueryResult = lift askQueryResult
135+ queryIncremental = lift . queryIncremental
136+
137+instance (Adjustable t m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (BehaviorWriterT t w m) where
138+ runWithReplace a0 a' = do
139+ (result0, result') <- lift $ runWithReplace (runBehaviorWriterT a0) $ runBehaviorWriterT <$> a'
140+ tellBehavior . join =<< hold (snd result0) (snd <$> result')
141+ return (fst result0, fst <$> result')
142+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust
143+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith
144+
145+traverseIntMapWithKeyWithAdjustImpl
146+ :: forall t w v' p p' v m.
147+ ( PatchTarget (p' (Behavior t w)) ~ IntMap (Behavior t w)
148+ , Patch (p' (Behavior t w))
149+ , Monoid w
150+ , Reflex t
151+ , MonadHold t m
152+ , Functor p
153+ , p ~ p'
154+ )
155+ => ( (IntMap.Key -> v -> m (v', Behavior t w))
156+ -> IntMap v
157+ -> Event t (p v)
158+ -> m (IntMap (v', Behavior t w), Event t (p (v', Behavior t w)))
159+ )
160+ -> (IntMap.Key -> v -> BehaviorWriterT t w m v')
161+ -> IntMap v
162+ -> Event t (p v)
163+ -> BehaviorWriterT t w m (IntMap v', Event t (p v'))
164+traverseIntMapWithKeyWithAdjustImpl base f (dm0 :: IntMap v) dm' = do
165+ (result0, result') <- lift $ base (\k v -> runBehaviorWriterT $ f k v) dm0 dm'
166+ let liftedResult0 = fmap fst result0
167+ liftedResult' = fmap (fmap fst) result'
168+ liftedWritten0 :: IntMap (Behavior t w)
169+ liftedWritten0 = fmap snd result0
170+ liftedWritten' = fmap (fmap snd) result'
171+ i <- holdIncremental liftedWritten0 liftedWritten'
172+ tellBehavior $ pull $ do
173+ m <- sample $ currentIncremental i
174+ mconcat . IntMap.elems <$> traverse sample m
175+ return (liftedResult0, liftedResult')
176+
177+newtype BehaviorWriterTLoweredResult t w v a = BehaviorWriterTLoweredResult (v a, Behavior t w)
178+
179+traverseDMapWithKeyWithAdjustImpl
180+ :: forall t w k v' p p' v m.
181+ ( PatchTarget (p' (Some k) (Behavior t w)) ~ Map (Some k) (Behavior t w)
182+ , Patch (p' (Some k) (Behavior t w))
183+ , Monoid w
184+ , Reflex t
185+ , MonadHold t m
186+ )
187+ => ( (forall a. k a -> v a -> m (BehaviorWriterTLoweredResult t w v' a))
188+ -> DMap k v
189+ -> Event t (p k v)
190+ -> m (DMap k (BehaviorWriterTLoweredResult t w v'), Event t (p k (BehaviorWriterTLoweredResult t w v')))
191+ )
192+ -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> v' a) -> p k (BehaviorWriterTLoweredResult t w v') -> p k v')
193+ -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> Behavior t w) -> p k (BehaviorWriterTLoweredResult t w v') -> p' (Some k) (Behavior t w))
194+ -> (forall a. k a -> v a -> BehaviorWriterT t w m (v' a))
195+ -> DMap k v
196+ -> Event t (p k v)
197+ -> BehaviorWriterT t w m (DMap k v', Event t (p k v'))
198+traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith f (dm0 :: DMap k v) dm' = do
199+ (result0, result') <- lift $ base (\k v -> fmap BehaviorWriterTLoweredResult $ runBehaviorWriterT $ f k v) dm0 dm'
200+ let getValue (BehaviorWriterTLoweredResult (v, _)) = v
201+ getWritten (BehaviorWriterTLoweredResult (_, w)) = w
202+ liftedResult0 = DMap.map getValue result0
203+ liftedResult' = ffor result' $ mapPatch getValue
204+ liftedWritten0 :: Map (Some k) (Behavior t w)
205+ liftedWritten0 = weakenDMapWith getWritten result0
206+ liftedWritten' = ffor result' $ weakenPatchWith getWritten
207+ i <- holdIncremental liftedWritten0 liftedWritten'
208+ tellBehavior $ pull $ do
209+ m <- sample $ currentIncremental i
210+ mconcat . Map.elems <$> traverse sample m
211+ return (liftedResult0, liftedResult')
src/Reflex/BehaviorWriter/Class.hsnew file+31
@@ -0,0 +1,31 @@
1+{-|
2+Module: Reflex.BehaviorWriter.Class
3+Description: This module defines the 'BehaviorWriter' class
4+-}
5+{-# LANGUAGE CPP #-}
6+{-# LANGUAGE ConstraintKinds #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
9+{-# LANGUAGE UndecidableInstances #-}
10+#ifdef USE_REFLEX_OPTIMIZER
11+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12+#endif
13+module Reflex.BehaviorWriter.Class
14+ ( MonadBehaviorWriter
15+ , BehaviorWriter(..)
16+ ) where
17+
18+import Control.Monad.Reader (ReaderT, lift)
19+import Reflex.Class (Behavior)
20+
21+{-# DEPRECATED MonadBehaviorWriter "Use 'BehaviorWriter' instead" #-}
22+-- | Type synonym for 'BehaviorWriter'
23+type MonadBehaviorWriter = BehaviorWriter
24+
25+-- | 'BehaviorWriter' efficiently collects 'Behavior' values using 'tellBehavior'
26+-- and combines them monoidally to provide a 'Behavior' result.
27+class (Monad m, Monoid w) => BehaviorWriter t w m | m -> t w where
28+ tellBehavior :: Behavior t w -> m ()
29+
30+instance BehaviorWriter t w m => BehaviorWriter t w (ReaderT r m) where
31+ tellBehavior = lift . tellBehavior
src/Reflex/Class.hs+1596−137
@@ -1,62 +1,564 @@
1−{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RankNTypes, GADTs, ScopedTypeVariables, FunctionalDependencies, RecursiveDo, UndecidableInstances, GeneralizedNewtypeDeriving, StandaloneDeriving, EmptyDataDecls, NoMonomorphismRestriction, TypeOperators, DeriveDataTypeable, PackageImports, TemplateHaskell, LambdaCase #-}
2−module Reflex.Class where
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
323
4−import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl)
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 Data.Patch
33+ -- * Primitives
34+ , Reflex (..)
35+ , mergeInt
36+ , coerceBehavior
37+ , coerceEvent
38+ , coerceDynamic
39+ , coerceIncremental
40+ , MonadSample (..)
41+ , MonadHold (..)
42+ -- ** 'fan' related types
43+ , EventSelector (..)
44+ , EventSelectorG (..)
45+ , EventSelectorInt (..)
46+ -- * Convenience functions
47+ , constDyn
48+ , pushAlways
49+ -- ** Combining 'Event's
50+ , leftmost
51+ , merge
52+ , mergeIncremental
53+ , mergeIncrementalWithMove
54+ , mergeMap
55+ , mergeIntMap
56+ , mergeMapIncremental
57+ , mergeMapIncrementalWithMove
58+ , mergeIntMapIncremental
59+ , coincidencePatchMap
60+ , coincidencePatchMapWithMove
61+ , coincidencePatchIntMap
62+ , mergeList
63+ , mergeWith
64+ , difference
65+ , alignEventWithMaybe
66+ -- ** Breaking up 'Event's
67+ , splitE
68+ , fan
69+ , fanEither
70+ , fanThese
71+ , fanMap
72+ , dmapToThese
73+ , EitherTag (..)
74+ , eitherToDSum
75+ , dsumToEither
76+ , factorEvent
77+ , filterEventKey
78+ -- ** Collapsing 'Event . Event'
79+ , switchHold
80+ , switchHoldPromptly
81+ , switchHoldPromptOnly
82+ , switchHoldPromptOnlyIncremental
83+ -- ** Using 'Event's to sample 'Behavior's
84+ , tag
85+ , tagMaybe
86+ , attach
87+ , attachWith
88+ , attachWithMaybe
89+ -- ** Blocking an 'Event' based on a 'Behavior'
90+ , gate
91+ -- ** Combining 'Dynamic's
92+ , distributeDMapOverDynPure
93+ , distributeDMapOverDynPureG
94+ , distributeListOverDyn
95+ , distributeListOverDynWith
96+ , zipDyn
97+ , zipDynWith
98+ -- ** Accumulating state
99+ , Accumulator (..)
100+ , accumDyn
101+ , accumMDyn
102+ , accumMaybeDyn
103+ , accumMaybeMDyn
104+ , mapAccumDyn
105+ , mapAccumMDyn
106+ , mapAccumMaybeDyn
107+ , mapAccumMaybeMDyn
108+ , accumB
109+ , accumMB
110+ , accumMaybeB
111+ , accumMaybeMB
112+ , mapAccumB
113+ , mapAccumMB
114+ , mapAccumMaybeB
115+ , mapAccumMaybeMB
116+ , mapAccum_
117+ , mapAccumM_
118+ , mapAccumMaybe_
119+ , mapAccumMaybeM_
120+ , accumIncremental
121+ , accumMIncremental
122+ , accumMaybeIncremental
123+ , accumMaybeMIncremental
124+ , mapAccumIncremental
125+ , mapAccumMIncremental
126+ , mapAccumMaybeIncremental
127+ , mapAccumMaybeMIncremental
128+ , zipListWithEvent
129+ , numberOccurrences
130+ , numberOccurrencesFrom
131+ , numberOccurrencesFrom_
132+ , (<@>)
133+ , (<@)
134+ , tailE
135+ , headTailE
136+ , takeWhileE
137+ , takeWhileJustE
138+ , dropWhileE
139+ , takeDropWhileJustE
140+ , switcher
141+ -- * Debugging functions
142+ , traceEvent
143+ , traceEventWith
144+ -- * Unsafe functions
145+ , unsafeDynamic
146+ , unsafeMapIncremental
147+ -- * 'Filterable' convenience functions
148+ , FunctorMaybe -- fmapMaybe is purposely not exported from deprecated 'FunctorMaybe' and the new alias is exported instead
149+ , mapMaybe -- Re-exported for convenience
150+ , fmapMaybe
151+ , fforMaybe
152+ , ffilter
153+ , filterLeft
154+ , filterRight
155+ -- * Miscellaneous convenience functions
156+ , ffor
157+ , ffor2
158+ , ffor3
159+ -- * Deprecated functions
160+ , switchPromptly
161+ , switchPromptOnly
162+ -- * "Cheap" functions
163+ , fmapMaybeCheap
164+ , mapMaybeCheap
165+ , fmapCheap
166+ , fforCheap
167+ , fforMaybeCheap
168+ , pushAlwaysCheap
169+ , tagCheap
170+ , mergeWithCheap
171+ , mergeWithCheap'
172+ -- * Slow, but general, implementations
173+ , slowHeadE
174+ ) where
5175
6−import Control.Monad.Identity hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
7−import Control.Monad.State.Strict hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
8−import Control.Monad.Reader hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
9−import Control.Monad.Writer hiding (mapM, mapM_, forM, forM_, sequence, sequence_, (<>))
10−import Data.List.NonEmpty (NonEmpty (..))
11−import Data.These
176+#ifdef MIN_VERSION_semialign
177+import Prelude hiding (zip, zipWith)
178+
179+#if MIN_VERSION_these(0,8,0)
180+import Data.These.Combinators (justThese)
181+#endif
182+#if MIN_VERSION_semialign(1,1,0)
183+import Data.Zip (Zip (..), Unzip (..))
184+#endif
185+#endif
186+
187+import Control.Applicative
188+import Control.Monad.Identity
189+import Control.Monad.Reader
190+import Control.Monad.State.Strict
191+import Control.Monad.Trans.Cont (ContT)
192+import Control.Monad.Trans.Except (ExceptT)
193+import Control.Monad.Trans.RWS (RWST)
194+import Control.Monad.Trans.Writer (WriterT)
12195import Data.Align
13−import Data.GADT.Compare (GEq (..), (:~:) (..))
14−import Data.GADT.Show (GShow (..))
15−import Data.Dependent.Sum (ShowTag (..))
16−import Data.Map (Map)
17−import qualified Data.Map as Map
18−import Data.Dependent.Map (DMap, DSum (..), GCompare (..), GOrdering (..))
196+import Data.Bifunctor
197+import Data.Coerce
198+import Data.Default
199+import Data.Dependent.Map (DMap)
200+import Data.Dependent.Sum (DSum (..))
19201import qualified Data.Dependent.Map as DMap
202+import Data.Functor.Compose
203+import Data.Functor.Product
204+import Data.GADT.Compare (GEq (..), GCompare (..))
205+import Data.FastMutableIntMap (PatchIntMap)
206+import Data.Foldable
207+import Data.Functor.Bind
20208import Data.Functor.Misc
21−import Data.Semigroup
209+import Data.Functor.Plus
210+import Data.IntMap.Strict (IntMap)
211+import qualified Data.IntMap.Strict as IntMap
212+import Data.List.NonEmpty (NonEmpty (..))
213+import Data.Map (Map)
214+import Data.Semigroup (Semigroup (..))
215+import Data.Some (Some(Some))
216+import Data.String
217+import Data.These
218+import Data.Type.Coercion
219+import Data.Type.Equality ((:~:) (..))
220+import Data.Witherable (Filterable(..))
221+import qualified Data.Witherable as W
222+import Reflex.FunctorMaybe (FunctorMaybe)
223+import qualified Reflex.FunctorMaybe
224+import Data.Patch
225+import qualified Data.Patch.MapWithMove as PatchMapWithMove
22226
23227import Debug.Trace (trace)
24228
25−class (MonadHold t (PushM t), MonadSample t (PullM t), Functor (Event t), Functor (Behavior t)) => Reflex t where
26− -- | A container for a value that can change over time. Behaviors can be sampled at will, but it is not possible to be notified when they change
229+-- | The 'Reflex' class contains all the primitive functionality needed for
230+-- Functional Reactive Programming (FRP). The @/t/@ type parameter indicates
231+-- which "timeline" is in use. Timelines are fully-independent FRP contexts,
232+-- and the type of the timeline determines the FRP engine to be used. For most
233+-- purposes, the 'Reflex.Spider' implementation is recommended.
234+class ( MonadHold t (PushM t)
235+ , MonadSample t (PullM t)
236+ , MonadFix (PushM t)
237+ , Functor (Dynamic t)
238+ , Applicative (Dynamic t) -- Necessary for GHC <= 7.8
239+ , Monad (Dynamic t)
240+ ) => Reflex t where
241+ -- | A container for a value that can change over time. 'Behavior's can be
242+ -- sampled at will, but it is not possible to be notified when they change
27243 data Behavior t :: * -> *
28− -- | A stream of occurrences. During any given frame, an Event is either occurring or not occurring; if it is occurring, it will contain a value of the given type (its "occurrence type")
244+ -- | A stream of occurrences. During any given frame, an 'Event' is either
245+ -- occurring or not occurring; if it is occurring, it will contain a value of
246+ -- the given type (its "occurrence type")
29247 data Event t :: * -> *
30− -- | An Event with no occurrences
31− never :: Event t a
32− -- | Create a Behavior that always has the given value
33− constant :: a -> Behavior t a --TODO: Refactor to use 'pure' from Applicative instead; however, we need to make sure that encouraging Applicative-style use of Behaviors doesn't have a negative performance impact
34− -- | Create an Event from another Event; the provided function can sample Behaviors and hold Events, and use the results to produce a occurring (Just) or non-occurring (Nothing) result
35− push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
248+ -- | A container for a value that can change over time and allows
249+ -- notifications on changes. Basically a combination of a 'Behavior' and an
250+ -- 'Event', with a rule that the 'Behavior' will change if and only if the
251+ -- 'Event' fires.
252+ data Dynamic t :: * -> *
253+ -- | An 'Incremental' is a more general form of a 'Dynamic'.
254+ -- Instead of always fully replacing the value, only parts of it can be patched.
255+ -- This is only needed for performance critical code via `mergeIncremental` to make small
256+ -- changes to large values.
257+ data Incremental t :: * -> *
36258 -- | A monad for doing complex push-based calculations efficiently
37259 type PushM t :: * -> *
38− -- | Create a Behavior by reading from other Behaviors; the result will be recomputed whenever any of the read Behaviors changes
39− pull :: PullM t a -> Behavior t a
40260 -- | A monad for doing complex pull-based calculations efficiently
41261 type PullM t :: * -> *
42− -- | Merge a collection of events; the resulting Event will only occur if at least one input event is occuring, and will contain all of the input keys that are occurring simultaneously
43− merge :: GCompare k => DMap (WrapArg (Event t) k) -> Event t (DMap k) --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
44− -- | Efficiently fan-out an event to many destinations. This function should be partially applied, and then the result applied repeatedly to create child events
45− fan :: GCompare k => Event t (DMap k) -> EventSelector t k --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
46− -- | Create an Event that will occur whenever the currently-selected input Event occurs
262+ -- | An 'Event' with no occurrences
263+ never :: Event t a
264+ -- | Create a 'Behavior' that always has the given value
265+ 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
266+ -- | Create an 'Event' from another 'Event'; the provided function can sample
267+ -- 'Behavior's and hold 'Event's, and use the results to produce a occurring
268+ -- (Just) or non-occurring (Nothing) result
269+ push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
270+ -- | 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.
271+ pushCheap :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b
272+ -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be
273+ -- recomputed whenever any of the read 'Behavior's changes
274+ pull :: PullM t a -> Behavior t a
275+ -- | Merge a collection of events; the resulting 'Event' will only occur if at
276+ -- least one input event is occurring, and will contain all of the input keys
277+ -- that are occurring simultaneously
278+
279+ --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty
280+ mergeG :: GCompare k => (forall a. q a -> Event t (v a))
281+ -> DMap k q -> Event t (DMap k v)
282+
283+ -- | Efficiently fan-out an event to many destinations. You should save the
284+ -- result in a @let@-binding, and then repeatedly 'selectG' on the result to
285+ -- create child events
286+ fanG :: GCompare k => Event t (DMap k v) -> EventSelectorG t k v
287+
288+ -- | Create an 'Event' that will occur whenever the currently-selected input
289+ -- 'Event' occurs
47290 switch :: Behavior t (Event t a) -> Event t a
48− -- | Create an Event that will occur whenever the input event is occurring and its occurrence value, another Event, is also occurring
291+ -- | Create an 'Event' that will occur whenever the input event is occurring -- and its occurrence value, another 'Event', is also occurring.
292+ -- You maybe looking for '@switchHold@ @never@' instead.
49293 coincidence :: Event t (Event t a) -> Event t a
294+ -- | Extract the 'Behavior' of a 'Dynamic'.
295+ current :: Dynamic t a -> Behavior t a
296+ -- | Extract the 'Event' of the 'Dynamic'.
297+ updated :: Dynamic t a -> Event t a
298+ -- | Create a new 'Dynamic'. The given 'PullM' must always return the most
299+ -- recent firing of the given 'Event', if any.
300+ unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a
301+ -- | Create a new 'Incremental'. The given "PullM"'s value must always change
302+ -- in the same way that the accumulated application of patches would change
303+ -- that value.
304+ unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p
305+ -- | Create a merge whose parents can change over time
306+ mergeIncrementalG :: GCompare k
307+ => (forall a. q a -> Event t (v a))
308+ -> Incremental t (PatchDMap k q)
309+ -> Event t (DMap k v)
310+ -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
311+ mergeIncrementalWithMoveG :: GCompare k
312+ => (forall a. q a -> Event t (v a))
313+ -> Incremental t (PatchDMapWithMove k q) -> Event t (DMap k v)
314+ -- | Extract the 'Behavior' component of an 'Incremental'
315+ currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)
316+ -- | Extract the 'Event' component of an 'Incremental'
317+ updatedIncremental :: Patch p => Incremental t p -> Event t p
318+ -- | Convert an 'Incremental' to a 'Dynamic'
319+ incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)
320+ -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its
321+ -- occurrence type
322+ behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)
323+ -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its
324+ -- occurrence type
325+ eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)
326+ -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its
327+ -- occurrence type
328+ dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)
329+ -- | Construct a 'Coercion' for an 'Incremental' given 'Coercion's for its
330+ -- patch target and patch types.
331+ incrementalCoercion
332+ :: Coercion (PatchTarget a) (PatchTarget b) -> Coercion a b -> Coercion (Incremental t a) (Incremental t b)
333+ mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
334+ fanInt :: Event t (IntMap a) -> EventSelectorInt t a
335+
336+-- | Efficiently fan-out an event to many destinations. You should save the
337+-- result in a @let@-binding, and then repeatedly 'select' on the result to
338+-- create child events
339+fan :: forall t k. (Reflex t, GCompare k)
340+ => Event t (DMap k Identity) -> EventSelector t k
341+ --TODO: Can we help enforce the partial application discipline here? The combinator is worthless without it
342+fan e = EventSelector (fixup (selectG (fanG e) :: k a -> Event t (Identity a)) :: forall a. k a -> Event t a)
343+ where
344+ fixup :: forall a. (k a -> Event t (Identity a)) -> k a -> Event t a
345+ fixup = case eventCoercion Coercion :: Coercion (Event t (Identity a)) (Event t a) of
346+ Coercion -> coerce
347+
348+--TODO: Specialize this so that we can take advantage of knowing that there's no changing going on
349+-- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple
350+-- keys simultaneously.
351+mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
352+mergeInt m = mergeIntIncremental $ unsafeBuildIncremental (return m) never
353+
354+-- | Coerce a 'Behavior' between representationally-equivalent value types
355+coerceBehavior :: (Reflex t, Coercible a b) => Behavior t a -> Behavior t b
356+coerceBehavior = coerceWith $ behaviorCoercion Coercion
357+
358+-- | Coerce an 'Event' between representationally-equivalent occurrence types
359+coerceEvent :: (Reflex t, Coercible a b) => Event t a -> Event t b
360+coerceEvent = coerceWith $ eventCoercion Coercion
361+
362+-- | Coerce a 'Dynamic' between representationally-equivalent value types
363+coerceDynamic :: (Reflex t, Coercible a b) => Dynamic t a -> Dynamic t b
364+coerceDynamic = coerceWith $ dynamicCoercion Coercion
365+
366+-- | Coerce an 'Incremental' between representationally-equivalent value types
367+coerceIncremental
368+ :: (Reflex t, Coercible a b, Coercible (PatchTarget a) (PatchTarget b))
369+ => Incremental t a -> Incremental t b
370+coerceIncremental = coerceWith $ incrementalCoercion Coercion Coercion
50371
51−class Monad m => MonadSample t m | m -> t where
52− -- | Get the current value in the Behavior
372+-- | Construct a 'Dynamic' from a 'Behavior' and an 'Event'. The 'Behavior'
373+-- __must__ change when and only when the 'Event' fires, such that the
374+-- 'Behavior''s value is always equal to the most recent firing of the 'Event';
375+-- if this is not the case, the resulting 'Dynamic' will behave
376+-- nondeterministically.
377+unsafeDynamic :: Reflex t => Behavior t a -> Event t a -> Dynamic t a
378+unsafeDynamic = unsafeBuildDynamic . sample
379+
380+-- | Construct a 'Dynamic' value that never changes
381+constDyn :: Reflex t => a -> Dynamic t a
382+constDyn = pure
383+
384+instance (Reflex t, Default a) => Default (Dynamic t a) where
385+ def = pure def
386+
387+-- | 'MonadSample' designates monads that can read the current value of a
388+-- 'Behavior'. This includes both 'PullM' and 'PushM'.
389+class (Applicative m, Monad m) => MonadSample t m | m -> t where
390+ -- | Get the current value in the 'Behavior'
53391 sample :: Behavior t a -> m a
54392
393+-- | 'MonadHold' designates monads that can create new 'Behavior's based on
394+-- 'Event's; usually this will be 'PushM' or a monad based on it. 'MonadHold'
395+-- is required to create any stateful computations with Reflex.
55396class MonadSample t m => MonadHold t m where
56− -- | Create a new Behavior whose value will initially be equal to the given value and will be updated whenever the given Event occurs
397+ -- | Create a new 'Behavior' whose value will initially be equal to the given
398+ -- value and will be updated whenever the given 'Event' occurs. The update
399+ -- takes effect immediately after the 'Event' occurs; if the occurrence that
400+ -- sets the 'Behavior' (or one that is simultaneous with it) is used to sample
401+ -- the 'Behavior', it will see the __old__ value of the 'Behavior', not the new
402+ -- one.
57403 hold :: a -> Event t a -> m (Behavior t a)
404+ default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)
405+ hold v0 = lift . hold v0
406+ -- | Create a 'Dynamic' value using the given initial value that changes every
407+ -- time the 'Event' occurs.
408+ holdDyn :: a -> Event t a -> m (Dynamic t a)
409+ default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)
410+ holdDyn v0 = lift . holdDyn v0
411+ -- | Create an 'Incremental' value using the given initial value that changes
412+ -- every time the 'Event' occurs.
413+ holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)
414+ default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)
415+ holdIncremental v0 = lift . holdIncremental v0
416+ buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)
417+ {-
418+ default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)
419+ buildDynamic getV0 = lift . buildDynamic getV0
420+ -}
421+ -- | Create a new 'Event' that only occurs only once, on the first occurrence of
422+ -- the supplied 'Event'.
423+ headE :: Event t a -> m (Event t a)
424+ -- | An event which only occurs at the current moment in time, such that:
425+ --
426+ -- > coincidence (pushAlways (\a -> (a <$) <$> now) e) = e
427+ --
428+ now :: m (Event t ())
429+ default now :: (m ~ f m', MonadTrans f, MonadHold t m') => m (Event t ())
430+ now = lift now
431+
432+-- | Accumulate an 'Incremental' with the supplied initial value and the firings of the provided 'Event',
433+-- using the combining function to produce a patch.
434+accumIncremental
435+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
436+ => (PatchTarget p -> b -> p)
437+ -> PatchTarget p
438+ -> Event t b
439+ -> m (Incremental t p)
440+accumIncremental f = accumMaybeIncremental $ \v o -> Just $ f v o
441+
442+-- | Similar to 'accumIncremental' but the combining function runs in 'PushM'
443+accumMIncremental
444+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
445+ => (PatchTarget p -> b -> PushM t p)
446+ -> PatchTarget p
447+ -> Event t b
448+ -> m (Incremental t p)
449+accumMIncremental f = accumMaybeMIncremental $ \v o -> Just <$> f v o
450+
451+-- | Similar to 'accumIncremental' but allows filtering of updates (by dropping updates when the
452+-- combining function produces @Nothing@)
453+accumMaybeIncremental
454+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
455+ => (PatchTarget p -> b -> Maybe p)
456+ -> PatchTarget p
457+ -> Event t b
458+ -> m (Incremental t p)
459+accumMaybeIncremental f = accumMaybeMIncremental $ \v o -> return $ f v o
460+
461+-- | Similar to 'accumMaybeMIncremental' but the combining function runs in 'PushM'
462+accumMaybeMIncremental
463+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
464+ => (PatchTarget p -> b -> PushM t (Maybe p))
465+ -> PatchTarget p
466+ -> Event t b
467+ -> m (Incremental t p)
468+accumMaybeMIncremental f z e = do
469+ rec let e' = flip push e $ \o -> do
470+ v <- sample $ currentIncremental d'
471+ f v o
472+ d' <- holdIncremental z e'
473+ return d'
474+
475+-- | Accumulate an 'Incremental' by folding occurrences of an 'Event'
476+-- with a function that both accumulates and produces a value to fire
477+-- as an 'Event'. Returns both the accumulated value and the constructed
478+-- 'Event'.
479+mapAccumIncremental
480+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
481+ => (PatchTarget p -> b -> (p, c))
482+ -> PatchTarget p
483+ -> Event t b
484+ -> m (Incremental t p, Event t c)
485+mapAccumIncremental f = mapAccumMaybeIncremental $ \v o -> bimap Just Just $ f v o
486+
487+-- | Like 'mapAccumIncremental' but the combining function runs in 'PushM'
488+mapAccumMIncremental
489+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
490+ => (PatchTarget p -> b -> PushM t (p, c))
491+ -> PatchTarget p
492+ -> Event t b
493+ -> m (Incremental t p, Event t c)
494+mapAccumMIncremental f = mapAccumMaybeMIncremental $ \v o -> bimap Just Just <$> f v o
495+
496+-- | Accumulate an 'Incremental' by folding occurrences of an 'Event' with
497+-- a function that both optionally accumulates and optionally produces
498+-- a value to fire as a separate output 'Event'.
499+-- Note that because 'Nothing's are discarded in both cases, the output
500+-- 'Event' may fire even though the output 'Incremental' has not changed, and
501+-- the output 'Incremental' may update even when the output 'Event' is not firing.
502+mapAccumMaybeIncremental
503+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
504+ => (PatchTarget p -> b -> (Maybe p, Maybe c))
505+ -> PatchTarget p
506+ -> Event t b
507+ -> m (Incremental t p, Event t c)
508+mapAccumMaybeIncremental f = mapAccumMaybeMIncremental $ \v o -> return $ f v o
509+
510+-- | Like 'mapAccumMaybeIncremental' but the combining function is a 'PushM' action
511+mapAccumMaybeMIncremental
512+ :: (Reflex t, Patch p, MonadHold t m, MonadFix m)
513+ => (PatchTarget p -> b -> PushM t (Maybe p, Maybe c))
514+ -> PatchTarget p
515+ -> Event t b
516+ -> m (Incremental t p, Event t c)
517+mapAccumMaybeMIncremental f z e = do
518+ rec let e' = flip push e $ \o -> do
519+ v <- sample $ currentIncremental d'
520+ result <- f v o
521+ return $ case result of
522+ (Nothing, Nothing) -> Nothing
523+ _ -> Just result
524+ d' <- holdIncremental z $ mapMaybe fst e'
525+ return (d', mapMaybe snd e')
58526
59−newtype EventSelector t k = EventSelector { select :: forall a. k a -> Event t a }
527+-- | A somewhat slow implementation of 'headE'
528+slowHeadE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
529+slowHeadE e = do
530+ rec be <- hold e $ fmapCheap (const never) e'
531+ let e' = switch be
532+ return e'
533+
534+-- | An 'EventSelector' allows you to efficiently 'select' an 'Event' based on a
535+-- key. This is much more efficient than filtering for each key with
536+-- 'mapMaybe'.
537+newtype EventSelector t k = EventSelector
538+ { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
539+ -- determined by the type of the key, so this can be used to fan-out
540+ -- 'Event's whose sub-'Event's have different types.
541+ --
542+ -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
543+ -- (but equivalent to) using 'mapMaybe' to select only the relevant
544+ -- occurrences of an 'Event'.
545+ select :: forall a. k a -> Event t a
546+ }
547+
548+newtype EventSelectorG t k v = EventSelectorG
549+ { -- | Retrieve the 'Event' for the given key. The type of the 'Event' is
550+ -- determined by the type of the key, so this can be used to fan-out
551+ -- 'Event's whose sub-'Event's have different types.
552+ --
553+ -- Using 'EventSelector's and the 'fan' primitive is far more efficient than
554+ -- (but equivalent to) using 'mapMaybe' to select only the relevant
555+ -- occurrences of an 'Event'.
556+ selectG :: forall a. k a -> Event t (v a)
557+ }
558+
559+-- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually
560+-- filtering by key.
561+newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }
60562
61563--------------------------------------------------------------------------------
62564-- Instances
@@ -67,174 +569,1131 @@ instance MonadSample t m => MonadSample t (ReaderT r m) where
67569
68570instance MonadHold t m => MonadHold t (ReaderT r m) where
69571 hold a0 = lift . hold a0
572+ holdDyn a0 = lift . holdDyn a0
573+ holdIncremental a0 = lift . holdIncremental a0
574+ buildDynamic a0 = lift . buildDynamic a0
575+ headE = lift . headE
576+ now = lift now
577+
578+instance (MonadSample t m, Monoid r) => MonadSample t (WriterT r m) where
579+ sample = lift . sample
580+
581+instance (MonadHold t m, Monoid r) => MonadHold t (WriterT r m) where
582+ hold a0 = lift . hold a0
583+ holdDyn a0 = lift . holdDyn a0
584+ holdIncremental a0 = lift . holdIncremental a0
585+ buildDynamic a0 = lift . buildDynamic a0
586+ headE = lift . headE
587+ now = lift now
588+
589+instance MonadSample t m => MonadSample t (StateT s m) where
590+ sample = lift . sample
591+
592+instance MonadHold t m => MonadHold t (StateT s m) where
593+ hold a0 = lift . hold a0
594+ holdDyn a0 = lift . holdDyn a0
595+ holdIncremental a0 = lift . holdIncremental a0
596+ buildDynamic a0 = lift . buildDynamic a0
597+ headE = lift . headE
598+ now = lift now
599+
600+instance MonadSample t m => MonadSample t (ExceptT e m) where
601+ sample = lift . sample
602+
603+instance MonadHold t m => MonadHold t (ExceptT e m) where
604+ hold a0 = lift . hold a0
605+ holdDyn a0 = lift . holdDyn a0
606+ holdIncremental a0 = lift . holdIncremental a0
607+ buildDynamic a0 = lift . buildDynamic a0
608+ headE = lift . headE
609+ now = lift now
610+
611+instance (MonadSample t m, Monoid w) => MonadSample t (RWST r w s m) where
612+ sample = lift . sample
613+
614+instance (MonadHold t m, Monoid w) => MonadHold t (RWST r w s m) where
615+ hold a0 = lift . hold a0
616+ holdDyn a0 = lift . holdDyn a0
617+ holdIncremental a0 = lift . holdIncremental a0
618+ buildDynamic a0 = lift . buildDynamic a0
619+ headE = lift . headE
620+ now = lift now
621+
622+instance MonadSample t m => MonadSample t (ContT r m) where
623+ sample = lift . sample
624+
625+instance MonadHold t m => MonadHold t (ContT r m) where
626+ hold a0 = lift . hold a0
627+ holdDyn a0 = lift . holdDyn a0
628+ holdIncremental a0 = lift . holdIncremental a0
629+ buildDynamic a0 = lift . buildDynamic a0
630+ headE = lift . headE
631+ now = lift now
70632
71633--------------------------------------------------------------------------------
72634-- Convenience functions
73635--------------------------------------------------------------------------------
74636
637+-- | Create an 'Event' from another 'Event'. The provided function can sample
638+-- 'Behavior's and hold 'Event's.
75639pushAlways :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
76−pushAlways f e = push (liftM Just . f) e
640+pushAlways f = push (fmap Just . f)
77641
642+-- | Flipped version of 'fmap'.
78643ffor :: Functor f => f a -> (a -> b) -> f b
79644ffor = flip fmap
80645
646+-- | Rotated version of 'liftA2'.
647+ffor2 :: Applicative f => f a -> f b -> (a -> b -> c) -> f c
648+ffor2 a b f = liftA2 f a b
649+
650+-- | Rotated version of 'liftA3'.
651+ffor3 :: Applicative f => f a -> f b -> f c -> (a -> b -> c -> d) -> f d
652+ffor3 a b c f = liftA3 f a b c
653+
654+instance Reflex t => Applicative (Behavior t) where
655+ pure = constant
656+ f <*> x = pull $ sample f `ap` sample x
657+ _ *> b = b
658+ a <* _ = a
659+
660+instance Reflex t => Apply (Behavior t) where
661+ (<.>) = (<*>)
662+
663+instance Reflex t => Bind (Behavior t) where
664+ (>>-) = (>>=)
665+
666+instance (Reflex t, Fractional a) => Fractional (Behavior t a) where
667+ (/) = liftA2 (/)
668+ fromRational = pure . fromRational
669+ recip = fmap recip
670+
81671instance Reflex t => Functor (Behavior t) where
82− fmap f = pull . liftM f . sample
672+ fmap f = pull . fmap f . sample
83673
84−--TODO: See if there's a better class in the standard libraries already
85−class FunctorMaybe f where
86− fmapMaybe :: (a -> Maybe b) -> f a -> f b
674+instance (Reflex t, IsString a) => IsString (Behavior t a) where
675+ fromString = pure . fromString
87676
88−fforMaybe :: FunctorMaybe f => f a -> (a -> Maybe b) -> f b
89−fforMaybe = flip fmapMaybe
677+instance Reflex t => Monad (Behavior t) where
678+ a >>= f = pull $ sample a >>= sample . f
679+ -- 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.
680+ return = constant
681+#if !MIN_VERSION_base(4,13,0)
682+ fail = error "Monad (Behavior t) does not support fail"
683+#endif
90684
91−ffilter :: FunctorMaybe f => (a -> Bool) -> f a -> f a
92−ffilter f = fmapMaybe $ \x -> if f x then Just x else Nothing
685+instance (Reflex t, Monoid a) => Monoid (Behavior t a) where
686+ mempty = constant mempty
687+ mappend a b = pull $ liftM2 mappend (sample a) (sample b)
688+ mconcat = pull . fmap mconcat . mapM sample
93689
94−instance Reflex t => FunctorMaybe (Event t) where
95− fmapMaybe f = push $ return . f
690+instance (Reflex t, Num a) => Num (Behavior t a) where
691+ (+) = liftA2 (+)
692+ (-) = liftA2 (-)
693+ (*) = liftA2 (*)
694+ abs = fmap abs
695+ fromInteger = pure . fromInteger
696+ negate = fmap negate
697+ signum = fmap signum
698+
699+instance (Num a, Reflex t) => Num (Dynamic t a) where
700+ (+) = liftA2 (+)
701+ (*) = liftA2 (*)
702+ abs = fmap abs
703+ signum = fmap signum
704+ fromInteger = pure . fromInteger
705+ negate = fmap negate
706+ (-) = liftA2 (-)
707+
708+instance (Reflex t, Semigroup a) => Semigroup (Behavior t a) where
709+ a <> b = pull $ liftM2 (<>) (sample a) (sample b)
710+ sconcat = pull . fmap sconcat . mapM sample
711+ stimes n = fmap $ stimes n
712+
713+-- | Alias for 'mapMaybe'
714+fmapMaybe :: Filterable f => (a -> Maybe b) -> f a -> f b
715+fmapMaybe = mapMaybe
716+
717+-- | Flipped version of 'mapMaybe'.
718+fforMaybe :: Filterable f => f a -> (a -> Maybe b) -> f b
719+fforMaybe = flip mapMaybe
720+
721+-- | Filter 'f a' using the provided predicate.
722+ffilter :: Filterable f => (a -> Bool) -> f a -> f a
723+ffilter = W.filter
724+
725+-- | Filter 'Left's from 'f (Either a b)' into 'a'.
726+filterLeft :: Filterable f => f (Either a b) -> f a
727+filterLeft = mapMaybe (either Just (const Nothing))
728+
729+-- | Filter 'Right's from 'f (Either a b)' into 'b'.
730+filterRight :: Filterable f => f (Either a b) -> f b
731+filterRight = mapMaybe (either (const Nothing) Just)
732+
733+-- | Left-biased event union (prefers left event on simultaneous
734+-- occurrence).
735+instance Reflex t => Alt (Event t) where
736+ ev1 <!> ev2 = leftmost [ev1, ev2]
737+
738+-- | 'Event' intersection. Only occurs when both events are co-incident.
739+instance Reflex t => Apply (Event t) where
740+ evf <.> evx = mapMaybe f (align evf evx) where
741+ f (These g a) = Just (g a)
742+ f _ = Nothing
743+
744+
745+-- | 'Event' intersection (convenient interface to 'coincidence').
746+instance Reflex t => Bind (Event t) where
747+ evx >>- f = coincidence (f <$> evx)
748+ join = coincidence
96749
97750instance Reflex t => Functor (Event t) where
98− fmap f = fmapMaybe $ Just . f
751+ {-# INLINE fmap #-}
752+ fmap f = mapMaybe $ Just . f
753+ {-# INLINE (<$) #-}
754+ x <$ e = fmapCheap (const x) e
99755
100−zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
101−zipListWithEvent f l e = do
102− rec lb <- hold l eTail
103− let eBoth = flip push e $ \o -> do
104− l' <- sample lb
105− return $ case l' of
106− (h : t) -> Just (f h o, t)
107− [] -> Nothing
108− let eTail = fmap snd eBoth
109− lb `seq` eBoth `seq` eTail `seq` return ()
110− return $ fmap fst eBoth
111−
112−-- | Replace the occurrence value of the Event with the value of the Behavior at the time of the occurrence
756+-- TODO Remove this instance
757+instance Reflex t => FunctorMaybe (Event t) where
758+ {-# INLINE fmapMaybe #-}
759+ fmapMaybe = mapMaybe
760+
761+instance Reflex t => Filterable (Event t) where
762+ {-# INLINE mapMaybe #-}
763+ mapMaybe f = push $ return . f
764+
765+-- | Never: @'zero' = 'never'@.
766+instance Reflex t => Plus (Event t) where
767+ zero = never
768+
769+-- | Replace each occurrence value of the 'Event' with the value of the
770+-- 'Behavior' at the time of that occurrence.
113771tag :: Reflex t => Behavior t b -> Event t a -> Event t b
114772tag b = pushAlways $ \_ -> sample b
115773
116−attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
117−attachWithMaybe f b e = flip push e $ \o -> liftM (flip f o) $ sample b
118−
119−attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
120−attachWith f = attachWithMaybe $ \a b -> Just $ f a b
774+-- | Replace each occurrence value of the 'Event' with the value of the
775+-- 'Behavior' at that time; if it is 'Just', fire with the contained value; if
776+-- it is 'Nothing', drop the occurrence.
777+tagMaybe :: Reflex t => Behavior t (Maybe b) -> Event t a -> Event t b
778+tagMaybe b = push $ \_ -> sample b
121779
780+-- | Create a new 'Event' that combines occurrences of supplied 'Event' with the
781+-- current value of the 'Behavior'.
122782attach :: Reflex t => Behavior t a -> Event t b -> Event t (a, b)
123783attach = attachWith (,)
124784
125−onceE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
126−onceE = headE
785+-- | Create a new 'Event' that occurs when the supplied 'Event' occurs by
786+-- combining it with the current value of the 'Behavior'.
787+attachWith :: Reflex t => (a -> b -> c) -> Behavior t a -> Event t b -> Event t c
788+attachWith f = attachWithMaybe $ \a b -> Just $ f a b
127789
128−headE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
129−headE e = do
130− rec be <- hold e $ fmap (const never) e'
131− let e' = switch be
132− e' `seq` return ()
133− return e'
790+-- | Create a new 'Event' by combining each occurrence with the current value of
791+-- the 'Behavior'. The occurrence is discarded if the combining function returns
792+-- Nothing
793+attachWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Behavior t a -> Event t b -> Event t c
794+attachWithMaybe f b e = flip push e $ \o -> (`f` o) <$> sample b
134795
135−tailE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a)
136−tailE e = liftM snd $ headTailE e
796+-- | Create a new 'Event' that occurs on all but the first occurrence of the
797+-- supplied 'Event'.
798+tailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a)
799+tailE e = snd <$> headTailE e
137800
138−headTailE :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> m (Event t a, Event t a)
801+-- | Create a tuple of two 'Event's with the first one occurring only the first
802+-- time the supplied 'Event' occurs and the second occurring on all but the first
803+-- occurrence.
804+headTailE :: (Reflex t, MonadHold t m) => Event t a -> m (Event t a, Event t a)
139805headTailE e = do
140806 eHead <- headE e
141807 be <- hold never $ fmap (const e) eHead
142808 return (eHead, switch be)
143809
810+-- | Take the streak of occurrences starting at the current time for which the
811+-- event returns 'True'.
812+--
813+-- Starting at the current time, fire all the occurrences of the 'Event' for
814+-- which the given predicate returns 'True'. When first 'False' is returned,
815+-- do not fire, and permanently stop firing, even if 'True' values would have
816+-- been encountered later.
817+takeWhileE
818+ :: forall t m a
819+ . (Reflex t, MonadFix m, MonadHold t m)
820+ => (a -> Bool)
821+ -> Event t a
822+ -> m (Event t a)
823+takeWhileE f = takeWhileJustE $ \v -> guard (f v) $> v
824+
825+-- | Take the streak of occurrences starting at the current time for which the
826+-- event returns 'Just b'.
827+--
828+-- Starting at the current time, fire all the occurrences of the 'Event' for
829+-- which the given predicate returns 'Just b'. When first 'Nothing' is returned,
830+-- do not fire, and permanently stop firing, even if 'Just b' values would have
831+-- been encountered later.
832+takeWhileJustE
833+ :: forall t m a b
834+ . (Reflex t, MonadFix m, MonadHold t m)
835+ => (a -> Maybe b)
836+ -> Event t a
837+ -> m (Event t b)
838+takeWhileJustE f e = do
839+ rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of
840+ Nothing -> Left never
841+ Just b -> Right b
842+ eFirstBad <- headE eBad
843+ e' <- switchHold e eFirstBad
844+ return eTrue
845+
846+-- | Drop the streak of occurrences starting at the current time for which the
847+-- event returns 'True'.
848+--
849+-- Starting at the current time, do not fire all the occurrences of the 'Event'
850+-- for which the given predicate returns 'True'. When 'False' is first
851+-- returned, do fire, and permanently continue firing, even if 'True' values
852+-- would have been encountered later.
853+dropWhileE
854+ :: forall t m a
855+ . (Reflex t, MonadFix m, MonadHold t m)
856+ => (a -> Bool)
857+ -> Event t a
858+ -> m (Event t a)
859+dropWhileE f e = snd <$> takeDropWhileJustE (\v -> guard (f v) $> v) e
860+
861+-- | Both take and drop the streak of occurrences starting at the current time
862+-- for which the event returns 'Just b'.
863+--
864+-- For the left event, starting at the current time, fire all the occurrences
865+-- of the 'Event' for which the given function returns 'Just b'. When
866+-- 'Nothing' is returned, do not fire, and permanently stop firing, even if
867+-- 'Just b' values would have been encountered later.
868+--
869+-- For the right event, do not fire until the first occurrence where the given
870+-- function returns 'Nothing', and fire that one and all subsequent
871+-- occurrences. Even if the function would have again returned 'Just b', keep
872+-- on firing.
873+takeDropWhileJustE
874+ :: forall t m a b
875+ . (Reflex t, MonadFix m, MonadHold t m)
876+ => (a -> Maybe b)
877+ -> Event t a
878+ -> m (Event t b, Event t a)
879+takeDropWhileJustE f e = do
880+ rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of
881+ Nothing -> Left ()
882+ Just b -> Right b
883+ eFirstBad <- headE eBad
884+ e' <- switchHold e (never <$ eFirstBad)
885+ eRest <- switchHoldPromptOnly never (e <$ eFirstBad)
886+ return (eGood, eRest)
887+
888+-- | Split the supplied 'Event' into two individual 'Event's occurring at the
889+-- same time with the respective values from the tuple.
144890splitE :: Reflex t => Event t (a, b) -> (Event t a, Event t b)
145891splitE e = (fmap fst e, fmap snd e)
146892
893+-- | Print the supplied 'String' and the value of the 'Event' on each
894+-- occurrence. This should /only/ be used for debugging.
895+--
896+-- Note: As with Debug.Trace.trace, the message will only be printed if the
897+-- 'Event' is actually used.
147898traceEvent :: (Reflex t, Show a) => String -> Event t a -> Event t a
148899traceEvent s = traceEventWith $ \x -> s <> ": " <> show x
149900
901+-- | Print the output of the supplied function on each occurrence of the
902+-- 'Event'. This should /only/ be used for debugging.
903+--
904+-- Note: As with Debug.Trace.trace, the message will only be printed if the
905+-- 'Event' is actually used.
150906traceEventWith :: Reflex t => (a -> String) -> Event t a -> Event t a
151907traceEventWith f = push $ \x -> trace (f x) $ return $ Just x
152908
153−data EitherTag l r a where
154− LeftTag :: EitherTag l r l
155− RightTag :: EitherTag l r r
156−
157−instance GEq (EitherTag l r) where
158− geq a b = case (a, b) of
159− (LeftTag, LeftTag) -> Just Refl
160− (RightTag, RightTag) -> Just Refl
161− _ -> Nothing
162−
163−instance GCompare (EitherTag l r) where
164− gcompare a b = case (a, b) of
165− (LeftTag, LeftTag) -> GEQ
166− (LeftTag, RightTag) -> GLT
167− (RightTag, LeftTag) -> GGT
168− (RightTag, RightTag) -> GEQ
169−
170−instance GShow (EitherTag l r) where
171− gshowsPrec _ a = case a of
172− LeftTag -> showString "LeftTag"
173− RightTag -> showString "RightTag"
174−
175−instance (Show l, Show r) => ShowTag (EitherTag l r) where
176− showTaggedPrec t n a = case t of
177− LeftTag -> showsPrec n a
178− RightTag -> showsPrec n a
179−
180−eitherToDSum :: Either a b -> DSum (EitherTag a b)
181−eitherToDSum = \case
182− Left a -> LeftTag :=> a
183− Right b -> RightTag :=> b
184−
185−dsumToEither :: DSum (EitherTag a b) -> Either a b
186−dsumToEither = \case
187− LeftTag :=> a -> Left a
188− RightTag :=> b -> Right b
189−
190−dmapToThese :: DMap (EitherTag a b) -> Maybe (These a b)
191−dmapToThese m = case (DMap.lookup LeftTag m, DMap.lookup RightTag m) of
192− (Nothing, Nothing) -> Nothing
193− (Just a, Nothing) -> Just $ This a
194− (Nothing, Just b) -> Just $ That b
195− (Just a, Just b) -> Just $ These a b
196−
197−appendEvents :: (Reflex t, Monoid a) => Event t a -> Event t a -> Event t a
198−appendEvents e1 e2 = fmap (mergeThese mappend) $ align e1 e2
199−
200−sequenceThese :: Monad m => These (m a) (m b) -> m (These a b)
201−sequenceThese t = case t of
202− This ma -> liftM This ma
203− These ma mb -> liftM2 These ma mb
204− That mb -> liftM That mb
909+instance (Semigroup a, Reflex t) => Semigroup (Event t a) where
910+ (<>) = alignWith (mergeThese (<>))
911+ sconcat = fmap sconcat . mergeList . toList
912+ stimes n = fmap $ stimes n
205913
206914instance (Semigroup a, Reflex t) => Monoid (Event t a) where
207915 mempty = never
208− mappend a b = mconcat [a, b]
916+ mappend = (<>)
209917 mconcat = fmap sconcat . mergeList
210918
919+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
920+-- list occurs. If multiple occur at the same time they are folded from the left
921+-- with the given function.
922+{-# INLINE mergeWith #-}
211923mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
212−mergeWith f es = fmap (Prelude.foldl1 f . map (\(Const2 _ :=> v) -> v) . DMap.toList) $ merge $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es
924+mergeWith = mergeWith' id
213925
926+{-# INLINE mergeWith' #-}
927+mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
928+mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)
929+ . mergeInt
930+ . IntMap.fromDistinctAscList
931+ $ zip [0 :: Int ..] es
932+
933+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
934+-- list occurs. If multiple occur at the same time the value is the value of the
935+-- leftmost event.
936+{-# INLINE leftmost #-}
214937leftmost :: Reflex t => [Event t a] -> Event t a
215938leftmost = mergeWith const
216939
940+-- | Create a new 'Event' that occurs if at least one of the 'Event's in the
941+-- list occurs and has a list of the values of all 'Event's occurring at that
942+-- time.
217943mergeList :: Reflex t => [Event t a] -> Event t (NonEmpty a)
218944mergeList [] = never
219−mergeList es = mergeWith (<>) $ map (fmap (:|[])) es
945+mergeList es = mergeWithFoldCheap' id es
946+
947+unsafeMapIncremental
948+ :: (Reflex t, Patch p, Patch p')
949+ => (PatchTarget p -> PatchTarget p')
950+ -> (p -> p')
951+ -> Incremental t p
952+ -> Incremental t p'
953+unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
220954
955+-- | Create a new 'Event' combining the map of 'Event's into an 'Event' that
956+-- occurs if at least one of them occurs and has a map of values of all 'Event's
957+-- occurring at that time.
221958mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a)
222959mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap
223960
961+-- | Like 'mergeMap' but for 'IntMap'.
962+mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)
963+mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap
964+
965+-- | Create a merge whose parents can change over time
966+mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a)
967+mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id)
968+
969+-- | Create a merge whose parents can change over time
970+mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)
971+mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)
972+
973+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
974+mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a)
975+mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id)
976+
977+-- | Split the event into separate events for 'Left' and 'Right' values.
978+fanEither :: Reflex t => Event t (Either a b) -> (Event t a, Event t b)
979+fanEither e =
980+ let justLeft = either Just (const Nothing)
981+ justRight = either (const Nothing) Just
982+ in (mapMaybe justLeft e, mapMaybe justRight e)
983+
984+-- | Split the event into separate events for 'This' and 'That' values,
985+-- allowing them to fire simultaneously when the input value is 'These'.
986+fanThese :: Reflex t => Event t (These a b) -> (Event t a, Event t b)
987+fanThese e =
988+ let this (This x) = Just x
989+ this (These x _) = Just x
990+ this _ = Nothing
991+ that (That y) = Just y
992+ that (These _ y) = Just y
993+ that _ = Nothing
994+ in (mapMaybe this e, mapMaybe that e)
995+
996+-- | Split the event into an 'EventSelector' that allows efficient selection of
997+-- the individual 'Event's.
224998fanMap :: (Reflex t, Ord k) => Event t (Map k a) -> EventSelector t (Const2 k a)
225999fanMap = fan . fmap mapToDMap
2261000
227−-- | Switches to the new event whenever it receives one; the new event is used immediately, on the same frame that it is switched to
228−switchPromptly :: forall t m a. (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
229−switchPromptly ea0 eea = do
1001+-- | Switches to the new event whenever it receives one. Only the old event is
1002+-- considered the moment a new one is switched in; the output event will fire at
1003+-- that moment only if the old event does.
1004+--
1005+-- Because the simultaneous firing case is irrelevant, this function imposes
1006+-- laxer "timing requirements" on the overall circuit, avoiding many potential
1007+-- cyclic dependency / metastability failures. It's also more performant. Use
1008+-- this rather than 'switchHoldPromptly' and 'switchHoldPromptOnly' unless you
1009+-- are absolutely sure you need to act on the new event in the coincidental
1010+-- case.
1011+switchHold :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1012+switchHold ea0 eea = switch <$> hold ea0 eea
1013+
1014+-- | Switches to the new event whenever it receives one. Whenever a new event is
1015+-- provided, if it is firing, its value will be the resulting event's value; if
1016+-- it is not firing, but the old one is, the old one's value will be used.
1017+--
1018+-- 'switchHold', by always forwarding the old event the moment it is switched
1019+-- out, avoids many potential cyclic dependency problems / metastability
1020+-- problems. It's also more performant. Use it instead unless you are sure you
1021+-- cannot.
1022+switchHoldPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1023+switchHoldPromptly ea0 eea = do
2301024 bea <- hold ea0 eea
2311025 let eLag = switch bea
2321026 eCoincidences = coincidence eea
2331027 return $ leftmost [eCoincidences, eLag]
2341028
1029+-- | switches to a new event whenever it receives one. At the moment of
1030+-- switching, the old event will be ignored if it fires, and the new one will be
1031+-- used if it fires; this is the opposite of 'switch', which will use only the
1032+-- old value.
1033+--
1034+-- 'switchHold', by always forwarding the old event the moment it is switched
1035+-- out, avoids many potential cyclic dependency problems / metastability
1036+-- problems. It's also more performant. Use it instead unless you are sure you
1037+-- cannot.
1038+switchHoldPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1039+switchHoldPromptOnly e0 e' = do
1040+ eLag <- switch <$> hold e0 e'
1041+ return $ coincidence $ leftmost [e', eLag <$ eLag]
1042+
1043+-- | When the given outer event fires, condense the inner events into the contained patch. Non-firing inner events will be replaced with deletions.
1044+coincidencePatchMap :: (Reflex t, Ord k) => Event t (PatchMap k (Event t v)) -> Event t (PatchMap k v)
1045+coincidencePatchMap e = fmapCheap PatchMap $ coincidence $ ffor e $ \(PatchMap m) -> mergeMap $ ffor m $ \case
1046+ Nothing -> fmapCheap (const Nothing) e
1047+ Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1048+
1049+-- | See 'coincidencePatchMap'
1050+coincidencePatchIntMap :: Reflex t => Event t (PatchIntMap (Event t v)) -> Event t (PatchIntMap v)
1051+coincidencePatchIntMap e = fmapCheap PatchIntMap $ coincidence $ ffor e $ \(PatchIntMap m) -> mergeIntMap $ ffor m $ \case
1052+ Nothing -> fmapCheap (const Nothing) e
1053+ Just ev -> leftmost [fmapCheap Just ev, fmapCheap (const Nothing) e]
1054+
1055+-- | See 'coincidencePatchMap'
1056+coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v)
1057+coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of
1058+ PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->
1059+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1060+ PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->
1061+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }
1062+ PatchMapWithMove.From_Insert ev -> leftmost
1063+ [ fforCheap ev $ \v ->
1064+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }
1065+ , fforCheap e $ \_ ->
1066+ ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }
1067+ ]
1068+
1069+-- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es
1070+-- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that
1071+-- fires with the patched value.
1072+switchHoldPromptOnlyIncremental
1073+ :: forall t m p pt w
1074+ . ( Reflex t
1075+ , MonadHold t m
1076+ , Patch (p (Event t w))
1077+ , PatchTarget (p (Event t w)) ~ pt (Event t w)
1078+ , Patch (p w)
1079+ , PatchTarget (p w) ~ pt w
1080+ , Monoid (pt w)
1081+ )
1082+ => (Incremental t (p (Event t w)) -> Event t (pt w))
1083+ -> (Event t (p (Event t w)) -> Event t (p w))
1084+ -> pt (Event t w)
1085+ -> Event t (p (Event t w))
1086+ -> m (Event t (pt w))
1087+switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch e0 e' = do
1088+ lag <- mergePatchIncremental <$> holdIncremental e0 e'
1089+ pure $ ffor (align lag (coincidencePatch e')) $ \case
1090+ This old -> old
1091+ That new -> new `applyAlways` mempty
1092+ These old new -> new `applyAlways` old
1093+
2351094instance Reflex t => Align (Event t) where
2361095 nil = never
237− align ea eb = fmapMaybe dmapToThese $ merge $ DMap.fromList [WrapArg LeftTag :=> ea, WrapArg RightTag :=> eb]
1096+#if MIN_VERSION_these(0, 8, 0)
1097+instance Reflex t => Semialign (Event t) where
1098+#endif
1099+ align = alignEventWithMaybe Just
1100+
1101+#ifdef MIN_VERSION_semialign
1102+#if MIN_VERSION_semialign(1,1,0)
1103+instance Reflex t => Zip (Event t) where
1104+#endif
1105+ zip x y = mapMaybe justThese $ align x y
1106+#endif
2381107
1108+#ifdef MIN_VERSION_semialign
1109+#if MIN_VERSION_semialign(1,1,0)
1110+instance Reflex t => Unzip (Event t) where
1111+ unzip = splitE
1112+#endif
1113+#endif
1114+
1115+-- | Create a new 'Event' that only occurs if the supplied 'Event' occurs and
1116+-- the 'Behavior' is true at the time of occurrence.
2391117gate :: Reflex t => Behavior t Bool -> Event t a -> Event t a
2401118gate = attachWithMaybe $ \allow a -> if allow then Just a else Nothing
1119+
1120+-- | Create a new behavior given a starting behavior and switch to the behavior
1121+-- carried by the event when it fires.
1122+switcher :: (Reflex t, MonadHold t m)
1123+ => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)
1124+switcher b eb = pull . (sample <=< sample) <$> hold b eb
1125+
1126+instance (Reflex t, IsString a) => IsString (Dynamic t a) where
1127+ fromString = pure . fromString
1128+
1129+-- | Combine two 'Dynamic's. The result will change whenever either (or both)
1130+-- input 'Dynamic' changes. Equivalent to @zipDynWith (,)@.
1131+zipDyn :: Reflex t => Dynamic t a -> Dynamic t b -> Dynamic t (a, b)
1132+zipDyn = zipDynWith (,)
1133+
1134+-- | Combine two 'Dynamic's with a combining function. The result will change
1135+-- whenever either (or both) input 'Dynamic' changes.
1136+-- More efficient than 'liftA2'.
1137+zipDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> Dynamic t c
1138+zipDynWith f da db =
1139+ let eab = align (updated da) (updated db)
1140+ ec = flip push eab $ \o -> do
1141+ (a, b) <- case o of
1142+ This a -> do
1143+ b <- sample $ current db
1144+ return (a, b)
1145+ That b -> do
1146+ a <- sample $ current da
1147+ return (a, b)
1148+ These a b -> return (a, b)
1149+ return $ Just $ f a b
1150+ in unsafeBuildDynamic (f <$> sample (current da) <*> sample (current db)) ec
1151+
1152+instance (Reflex t, Semigroup a) => Semigroup (Dynamic t a) where
1153+ (<>) = zipDynWith (<>)
1154+ stimes n = fmap $ stimes n
1155+
1156+instance (Reflex t, Monoid a) => Monoid (Dynamic t a) where
1157+ mconcat = distributeListOverDynWith mconcat
1158+ mempty = constDyn mempty
1159+ mappend = zipDynWith mappend
1160+
1161+-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1162+-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1163+-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1164+distributeDMapOverDynPure :: forall t k. (Reflex t, GCompare k) => DMap k (Dynamic t) -> Dynamic t (DMap k Identity)
1165+distributeDMapOverDynPure = distributeDMapOverDynPureG coerceDynamic
1166+
1167+-- | This function converts a 'DMap' whose elements are 'Dynamic's into a
1168+-- 'Dynamic' 'DMap'. Its implementation is more efficient than doing the same
1169+-- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators.
1170+distributeDMapOverDynPureG
1171+ :: forall t k q v. (Reflex t, GCompare k)
1172+ => (forall a. q a -> Dynamic t (v a))
1173+ -> DMap k q -> Dynamic t (DMap k v)
1174+distributeDMapOverDynPureG nt dm = case DMap.toList dm of
1175+ [] -> constDyn DMap.empty
1176+ [k :=> v] -> DMap.singleton k <$> nt v
1177+ _ ->
1178+ let getInitial = DMap.traverseWithKey (\_ -> sample . current . nt) dm
1179+ edmPre = mergeG getCompose $ DMap.map (Compose . updated . nt) dm
1180+ result = unsafeBuildDynamic getInitial $ flip pushAlways edmPre $ \news -> do
1181+ olds <- sample $ current result
1182+ return $ DMap.unionWithKey (\_ _ new -> new) olds news
1183+ in result
1184+
1185+-- | Convert a list of 'Dynamic's into a 'Dynamic' list.
1186+distributeListOverDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
1187+distributeListOverDyn = distributeListOverDynWith id
1188+
1189+-- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's
1190+distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b
1191+distributeListOverDynWith f =
1192+ fmap (f . map fromDSum . DMap.toAscList) .
1193+ distributeDMapOverDynPure .
1194+ DMap.fromDistinctAscList .
1195+ zipWith toDSum [0..]
1196+ where
1197+ toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
1198+ toDSum k v = Const2 k :=> v
1199+ fromDSum :: DSum (Const2 Int a) Identity -> a
1200+ fromDSum (Const2 _ :=> Identity v) = v
1201+
1202+-- | Create a new 'Event' that occurs when the first supplied 'Event' occurs
1203+-- unless the second supplied 'Event' occurs simultaneously.
1204+difference :: Reflex t => Event t a -> Event t b -> Event t a
1205+difference = alignEventWithMaybe $ \case
1206+ This a -> Just a
1207+ _ -> Nothing
1208+
1209+-- | Zips two values by taking the union of their shapes and combining with the provided function.
1210+-- 'Nothing' values are dropped.
1211+alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c
1212+alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $
1213+ merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1214+
1215+-- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that
1216+-- matches the provided key.
1217+filterEventKey
1218+ :: forall t m k v a.
1219+ ( Reflex t
1220+ , MonadFix m
1221+ , MonadHold t m
1222+ , GEq k
1223+ )
1224+ => k a
1225+ -> Event t (DSum k v)
1226+ -> m (Event t (v a))
1227+filterEventKey k kv' = do
1228+ let f :: DSum k v -> Maybe (v a)
1229+ f (newK :=> newV) = case newK `geq` k of
1230+ Just Refl -> Just newV
1231+ Nothing -> Nothing
1232+ takeWhileJustE f kv'
1233+
1234+-- | "Factor" the input 'DSum' 'Event' to produce an 'Event' which
1235+-- fires when the 'DSum' key changes and contains both the value of the
1236+-- 'DSum' at switchover and an 'Event' of values produced by subsequent
1237+-- firings of the input 'Event' that do not change the 'DSum' key.
1238+factorEvent
1239+ :: forall t m k v a.
1240+ ( Reflex t
1241+ , MonadFix m
1242+ , MonadHold t m
1243+ , GEq k
1244+ )
1245+ => k a
1246+ -> Event t (DSum k v)
1247+ -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v))))
1248+factorEvent k0 kv' = do
1249+ key :: Behavior t (Some k) <- hold (Some k0) $ fmapCheap (\(k :=> _) -> Some k) kv'
1250+ let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case
1251+ Some oldKey -> case newKey `geq` oldKey of
1252+ Just Refl -> return Nothing
1253+ Nothing -> do
1254+ newInner <- filterEventKey newKey kv'
1255+ return $ Just $ newKey :=> Pair newVal (Compose newInner)
1256+ eInitial <- filterEventKey k0 kv'
1257+ return (eInitial, update)
1258+
1259+--------------------------------------------------------------------------------
1260+-- Accumulator
1261+--------------------------------------------------------------------------------
1262+
1263+-- | An 'Accumulator' type can be built by accumulating occurrences of an
1264+-- 'Event'.
1265+#if __GLASGOW_HASKELL__ < 802
1266+{-# WARNING accum "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1267+{-# WARNING accumM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1268+{-# WARNING accumMaybe "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1269+{-# WARNING accumMaybeM "ghc < 8.2.1 doesn't seem to be able to specialize functions in this class, which can lead to poor performance" #-}
1270+#endif
1271+class Reflex t => Accumulator t f | f -> t where
1272+ accum :: (MonadHold t m, MonadFix m) => (a -> b -> a) -> a -> Event t b -> m (f a)
1273+ accum f = accumMaybe $ \v o -> Just $ f v o
1274+ accumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t a) -> a -> Event t b -> m (f a)
1275+ accumM f = accumMaybeM $ \v o -> Just <$> f v o
1276+ accumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> Maybe a) -> a -> Event t b -> m (f a)
1277+ accumMaybe f = accumMaybeM $ \v o -> return $ f v o
1278+ accumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (f a)
1279+ mapAccum :: (MonadHold t m, MonadFix m) => (a -> b -> (a, c)) -> a -> Event t b -> m (f a, Event t c)
1280+ mapAccum f = mapAccumMaybe $ \v o -> bimap Just Just $ f v o
1281+ mapAccumM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (a, c)) -> a -> Event t b -> m (f a, Event t c)
1282+ mapAccumM f = mapAccumMaybeM $ \v o -> bimap Just Just <$> f v o
1283+ mapAccumMaybe :: (MonadHold t m, MonadFix m) => (a -> b -> (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1284+ mapAccumMaybe f = mapAccumMaybeM $ \v o -> return $ f v o
1285+ mapAccumMaybeM :: (MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a, Maybe c)) -> a -> Event t b -> m (f a, Event t c)
1286+
1287+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1288+-- with the provided function. See 'foldDyn'.
1289+accumDyn
1290+ :: (Reflex t, MonadHold t m, MonadFix m)
1291+ => (a -> b -> a)
1292+ -> a
1293+ -> Event t b
1294+ -> m (Dynamic t a)
1295+accumDyn f = accumMaybeDyn $ \v o -> Just $ f v o
1296+
1297+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1298+-- with the provided 'PushM' action.
1299+accumMDyn
1300+ :: (Reflex t, MonadHold t m, MonadFix m)
1301+ => (a -> b -> PushM t a)
1302+ -> a
1303+ -> Event t b
1304+ -> m (Dynamic t a)
1305+accumMDyn f = accumMaybeMDyn $ \v o -> Just <$> f v o
1306+
1307+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1308+-- with the provided function, discarding 'Nothing' results.
1309+accumMaybeDyn
1310+ :: (Reflex t, MonadHold t m, MonadFix m)
1311+ => (a -> b -> Maybe a)
1312+ -> a
1313+ -> Event t b
1314+ -> m (Dynamic t a)
1315+accumMaybeDyn f = accumMaybeMDyn $ \v o -> return $ f v o
1316+
1317+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1318+-- with the provided 'PushM' action, discarding 'Nothing' results.
1319+accumMaybeMDyn
1320+ :: (Reflex t, MonadHold t m, MonadFix m)
1321+ => (a -> b -> PushM t (Maybe a))
1322+ -> a
1323+ -> Event t b
1324+ -> m (Dynamic t a)
1325+accumMaybeMDyn f z e = do
1326+ rec let e' = flip push e $ \o -> do
1327+ v <- sample $ current d'
1328+ f v o
1329+ d' <- holdDyn z e'
1330+ return d'
1331+
1332+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event'
1333+-- with a function that both accumulates and produces a value to fire
1334+-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1335+mapAccumDyn
1336+ :: (Reflex t, MonadHold t m, MonadFix m)
1337+ => (a -> b -> (a, c))
1338+ -> a
1339+ -> Event t b
1340+ -> m (Dynamic t a, Event t c)
1341+mapAccumDyn f = mapAccumMaybeDyn $ \v o -> bimap Just Just $ f v o
1342+
1343+-- | Similar to 'mapAccumDyn' except that the combining function is a
1344+-- 'PushM' action.
1345+mapAccumMDyn
1346+ :: (Reflex t, MonadHold t m, MonadFix m)
1347+ => (a -> b -> PushM t (a, c))
1348+ -> a
1349+ -> Event t b
1350+ -> m (Dynamic t a, Event t c)
1351+mapAccumMDyn f = mapAccumMaybeMDyn $ \v o -> bimap Just Just <$> f v o
1352+
1353+-- | Accumulate a 'Dynamic' by folding occurrences of an 'Event' with
1354+-- a function that both optionally accumulates and optionally produces
1355+-- a value to fire as a separate output 'Event'.
1356+-- Note that because 'Nothing's are discarded in both cases, the output
1357+-- 'Event' may fire even though the output 'Dynamic' has not changed, and
1358+-- the output 'Dynamic' may update even when the output 'Event' is not firing.
1359+mapAccumMaybeDyn
1360+ :: (Reflex t, MonadHold t m, MonadFix m)
1361+ => (a -> b -> (Maybe a, Maybe c))
1362+ -> a
1363+ -> Event t b
1364+ -> m (Dynamic t a, Event t c)
1365+mapAccumMaybeDyn f = mapAccumMaybeMDyn $ \v o -> return $ f v o
1366+
1367+-- | Like 'mapAccumMaybeDyn' except that the combining function is a
1368+-- 'PushM' action.
1369+mapAccumMaybeMDyn
1370+ :: (Reflex t, MonadHold t m, MonadFix m)
1371+ => (a -> b -> PushM t (Maybe a, Maybe c))
1372+ -> a
1373+ -> Event t b
1374+ -> m (Dynamic t a, Event t c)
1375+mapAccumMaybeMDyn f z e = do
1376+ rec let e' = flip push e $ \o -> do
1377+ v <- sample $ current d'
1378+ result <- f v o
1379+ return $ case result of
1380+ (Nothing, Nothing) -> Nothing
1381+ _ -> Just result
1382+ d' <- holdDyn z $ mapMaybe fst e'
1383+ return (d', mapMaybe snd e')
1384+
1385+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1386+-- with the provided function.
1387+{-# INLINE accumB #-}
1388+accumB
1389+ :: (Reflex t, MonadHold t m, MonadFix m)
1390+ => (a -> b -> a)
1391+ -> a
1392+ -> Event t b
1393+ -> m (Behavior t a)
1394+accumB f = accumMaybeB $ \v o -> Just $ f v o
1395+
1396+-- | Like 'accumB' except that the combining function is a 'PushM' action.
1397+{-# INLINE accumMB #-}
1398+accumMB
1399+ :: (Reflex t, MonadHold t m, MonadFix m)
1400+ => (a -> b -> PushM t a)
1401+ -> a
1402+ -> Event t b
1403+ -> m (Behavior t a)
1404+accumMB f = accumMaybeMB $ \v o -> Just <$> f v o
1405+
1406+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1407+-- with the provided function, discarding 'Nothing' results.
1408+{-# INLINE accumMaybeB #-}
1409+accumMaybeB
1410+ :: (Reflex t, MonadHold t m, MonadFix m)
1411+ => (a -> b -> Maybe a)
1412+ -> a
1413+ -> Event t b
1414+ -> m (Behavior t a)
1415+accumMaybeB f = accumMaybeMB $ \v o -> return $ f v o
1416+
1417+-- | Like 'accumMaybeB' except that the combining function is a 'PushM' action.
1418+{-# INLINE accumMaybeMB #-}
1419+accumMaybeMB :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe a)) -> a -> Event t b -> m (Behavior t a)
1420+accumMaybeMB f z e = do
1421+ rec let e' = flip push e $ \o -> do
1422+ v <- sample d'
1423+ f v o
1424+ d' <- hold z e'
1425+ return d'
1426+
1427+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event'
1428+-- with a function that both accumulates and produces a value to fire
1429+-- as an 'Event'. Returns both the accumulated value and an 'Event'.
1430+{-# INLINE mapAccumB #-}
1431+mapAccumB
1432+ :: (Reflex t, MonadHold t m, MonadFix m)
1433+ => (a -> b -> (a, c))
1434+ -> a
1435+ -> Event t b
1436+ -> m (Behavior t a, Event t c)
1437+mapAccumB f = mapAccumMaybeB $ \v o -> bimap Just Just $ f v o
1438+
1439+-- | Like 'mapAccumB' except that the combining function is a 'PushM' action.
1440+{-# INLINE mapAccumMB #-}
1441+mapAccumMB
1442+ :: (Reflex t, MonadHold t m, MonadFix m)
1443+ => (a -> b -> PushM t (a, c))
1444+ -> a
1445+ -> Event t b
1446+ -> m (Behavior t a, Event t c)
1447+mapAccumMB f = mapAccumMaybeMB $ \v o -> bimap Just Just <$> f v o
1448+
1449+-- | Accumulate a 'Behavior' by folding occurrences of an 'Event' with
1450+-- a function that both optionally accumulates and optionally produces
1451+-- a value to fire as a separate output 'Event'. 'Nothing's are discarded.
1452+{-# INLINE mapAccumMaybeB #-}
1453+mapAccumMaybeB
1454+ :: (Reflex t, MonadHold t m, MonadFix m)
1455+ => (a -> b -> (Maybe a, Maybe c))
1456+ -> a
1457+ -> Event t b
1458+ -> m (Behavior t a, Event t c)
1459+mapAccumMaybeB f = mapAccumMaybeMB $ \v o -> return $ f v o
1460+
1461+-- | Like 'mapAccumMaybeB' except that the combining function is a 'PushM' action.
1462+{-# INLINE mapAccumMaybeMB #-}
1463+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)
1464+mapAccumMaybeMB f z e = do
1465+ rec let e' = flip push e $ \o -> do
1466+ v <- sample d'
1467+ result <- f v o
1468+ return $ case result of
1469+ (Nothing, Nothing) -> Nothing
1470+ _ -> Just result
1471+ d' <- hold z $ mapMaybe fst e'
1472+ return (d', mapMaybe snd e')
1473+
1474+-- | Accumulate occurrences of an 'Event', producing an output occurrence each
1475+-- time. Discard the underlying 'Accumulator'.
1476+{-# INLINE mapAccum_ #-}
1477+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)
1478+mapAccum_ f z e = do
1479+ (_, result) <- mapAccumB f z e
1480+ return result
1481+
1482+-- | Accumulate occurrences of an 'Event', possibly producing an output
1483+-- occurrence each time. Discard the underlying 'Accumulator'.
1484+{-# INLINE mapAccumMaybe_ #-}
1485+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)
1486+mapAccumMaybe_ f z e = do
1487+ (_, result) <- mapAccumMaybeB f z e
1488+ return result
1489+
1490+-- | Accumulate occurrences of an 'Event', using a 'PushM' action and producing
1491+-- an output occurrence each time. Discard the underlying 'Accumulator'.
1492+{-# INLINE mapAccumM_ #-}
1493+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)
1494+mapAccumM_ f z e = do
1495+ (_, result) <- mapAccumMB f z e
1496+ return result
1497+
1498+-- | Accumulate occurrences of an 'Event', using a 'PushM' action and possibly
1499+-- producing an output occurrence each time. Discard the underlying
1500+-- 'Accumulator'.
1501+{-# INLINE mapAccumMaybeM_ #-}
1502+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)
1503+mapAccumMaybeM_ f z e = do
1504+ (_, result) <- mapAccumMaybeMB f z e
1505+ return result
1506+
1507+instance Reflex t => Accumulator t (Dynamic t) where
1508+ accumMaybeM = accumMaybeMDyn
1509+ mapAccumMaybeM = mapAccumMaybeMDyn
1510+
1511+instance Reflex t => Accumulator t (Behavior t) where
1512+ accumMaybeM = accumMaybeMB
1513+ mapAccumMaybeM = mapAccumMaybeMB
1514+
1515+instance Reflex t => Accumulator t (Event t) where
1516+ accumMaybeM f z e = updated <$> accumMaybeM f z e
1517+ mapAccumMaybeM f z e = first updated <$> mapAccumMaybeM f z e
1518+
1519+-- | Create a new 'Event' by combining each occurrence with the next value of the
1520+-- list using the supplied function. If the list runs out of items, all
1521+-- subsequent 'Event' occurrences will be ignored.
1522+zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c)
1523+zipListWithEvent f l e = do
1524+ let f' a b = case a of
1525+ h:t -> (Just t, Just $ f h b)
1526+ _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?
1527+ mapAccumMaybe_ f' l e
1528+
1529+-- | Assign a number to each occurrence of the given 'Event', starting from 0
1530+{-# INLINE numberOccurrences #-}
1531+numberOccurrences :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Event t (b, a))
1532+numberOccurrences = numberOccurrencesFrom 0
1533+
1534+-- | Assign a number to each occurrence of the given 'Event'
1535+{-# INLINE numberOccurrencesFrom #-}
1536+numberOccurrencesFrom :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t (b, a))
1537+numberOccurrencesFrom = mapAccum_ (\n a -> let !next = n + 1 in (next, (n, a)))
1538+
1539+-- | Assign a number to each occurrence of the given 'Event'; discard the occurrences' values
1540+{-# INLINE numberOccurrencesFrom_ #-}
1541+numberOccurrencesFrom_ :: (Reflex t, MonadHold t m, MonadFix m, Num b) => b -> Event t a -> m (Event t b)
1542+numberOccurrencesFrom_ = mapAccum_ (\n _ -> let !next = n + 1 in (next, n))
1543+
1544+-- | This is used to sample the value of a 'Behavior' using an 'Event'.
1545+--
1546+-- The '<@>' operator is intended to be used in conjunction with
1547+-- the 'Applicative' instance for 'Behavior'.
1548+--
1549+-- This is useful when we want to combine the values of one 'Event' and
1550+-- the value of several 'Behavior's at the time the 'Event' is firing.
1551+--
1552+-- If we have:
1553+--
1554+-- > f :: a -> b -> c -> d
1555+-- > b1 :: Behavior t a
1556+-- > b2 :: Behavior t b
1557+-- > e :: Event t c
1558+--
1559+-- then we can do:
1560+--
1561+-- > f <$> b1 <*> b2 <@> e :: Event t d
1562+--
1563+-- in order to apply the function 'f' to the relevant values.
1564+--
1565+-- The alternative would be something like:
1566+--
1567+-- > attachWith (\(x1, x2) y -> f x1 x2 y) ((,) <$> b1 <*> b2) e :: Event t d
1568+--
1569+-- or a variation involing a custom data type to hold the combination of
1570+-- 'Behavior's even when that combination might only ever be used by 'f'.
1571+--
1572+-- A more suggestive example might be:
1573+--
1574+-- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)
1575+--
1576+(<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b
1577+(<@>) b = push $ \x -> do
1578+ f <- sample b
1579+ return . Just . f $ x
1580+infixl 4 <@>
1581+
1582+-- | An version of '<@>' that does not use the value of the 'Event'.
1583+--
1584+-- Alternatively, it is 'tag' in operator form.
1585+--
1586+-- This is useful when we want to combine the values of several
1587+-- 'Behavior's at particular points in time using an 'Applicative'
1588+-- style syntax.
1589+--
1590+-- If we have:
1591+--
1592+-- > g :: a -> b -> d
1593+-- > b1 :: Behavior t a
1594+-- > b2 :: Behavior t b
1595+-- > e :: Event t c
1596+--
1597+-- where 'e' is firing at the points in time of interest.
1598+--
1599+-- Then we can use '<@':
1600+--
1601+-- > g <$> b1 <*> b2 <@ e :: Event t d
1602+--
1603+-- to combine the values of 'b1' and 'b2' at each of those points of time,
1604+-- with the function 'g' being used to combine the values.
1605+--
1606+-- This is the same as '<@>' except that the 'Event' is being used only
1607+-- to act as a trigger.
1608+(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b
1609+(<@) = tag
1610+infixl 4 <@
1611+
1612+------------------
1613+-- Cheap Functions
1614+------------------
1615+
1616+-- | A "cheap" version of 'pushAlways'. See the performance note on 'pushCheap'.
1617+{-# INLINE pushAlwaysCheap #-}
1618+pushAlwaysCheap :: Reflex t => (a -> PushM t b) -> Event t a -> Event t b
1619+pushAlwaysCheap f = pushCheap (fmap Just . f)
1620+
1621+-- | A "cheap" version of 'mapMaybe'. See the performance note on 'pushCheap'.
1622+{-# INLINE mapMaybeCheap #-}
1623+mapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1624+mapMaybeCheap f = pushCheap $ return . f
1625+
1626+-- | An alias for 'mapMaybeCheap'
1627+{-# INLINE fmapMaybeCheap #-}
1628+fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b
1629+fmapMaybeCheap = mapMaybeCheap
1630+
1631+
1632+-- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'.
1633+{-# INLINE fforMaybeCheap #-}
1634+fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b
1635+fforMaybeCheap = flip mapMaybeCheap
1636+
1637+-- | A "cheap" version of 'ffor'. See the performance note on 'pushCheap'.
1638+{-# INLINE fforCheap #-}
1639+fforCheap :: Reflex t => Event t a -> (a -> b) -> Event t b
1640+fforCheap = flip fmapCheap
1641+
1642+-- | A "cheap" version of 'fmap'. See the performance note on 'pushCheap'.
1643+{-# INLINE fmapCheap #-}
1644+fmapCheap :: Reflex t => (a -> b) -> Event t a -> Event t b
1645+fmapCheap f = pushCheap $ return . Just . f
1646+
1647+-- | A "cheap" version of 'tag'. See the performance note on 'pushCheap'.
1648+{-# INLINE tagCheap #-}
1649+tagCheap :: Reflex t => Behavior t b -> Event t a -> Event t b
1650+tagCheap b = pushAlwaysCheap $ \_ -> sample b
1651+
1652+-- | Merge a collection of events; the resulting 'Event' will only occur if at
1653+-- least one input event is occurring, and will contain all of the input keys
1654+-- that are occurring simultaneously
1655+merge :: (Reflex t, GCompare k) => DMap k (Event t) -> Event t (DMap k Identity)
1656+merge = mergeG coerceEvent
1657+{-# INLINE merge #-}
1658+
1659+-- | Create a merge whose parents can change over time
1660+mergeIncremental :: (Reflex t, GCompare k)
1661+ => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity)
1662+mergeIncremental = mergeIncrementalG coerceEvent
1663+
1664+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental
1665+mergeIncrementalWithMove :: (Reflex t, GCompare k)
1666+ => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity)
1667+mergeIncrementalWithMove = mergeIncrementalWithMoveG coerceEvent
1668+
1669+-- | A "cheap" version of 'mergeWithCheap'. See the performance note on 'pushCheap'.
1670+{-# INLINE mergeWithCheap #-}
1671+mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a
1672+mergeWithCheap = mergeWithCheap' id
1673+
1674+-- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'.
1675+{-# INLINE mergeWithCheap' #-}
1676+mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b
1677+mergeWithCheap' f g = mergeWithFoldCheap' $ foldl1 g . fmap f
1678+
1679+-- | A "cheap" version of 'mergeWithFoldCheap''. See the performance note on 'pushCheap'.
1680+{-# INLINE mergeWithFoldCheap' #-}
1681+mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b
1682+mergeWithFoldCheap' f es =
1683+ fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)
1684+ . mergeInt
1685+ . IntMap.fromDistinctAscList
1686+ $ zip [0 :: Int ..] es
1687+
1688+--------------------------------------------------------------------------------
1689+-- Deprecated functions
1690+--------------------------------------------------------------------------------
1691+
1692+{-# 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'. " #-}
1693+-- | See 'switchHoldPromptly'
1694+switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1695+switchPromptly = switchHoldPromptly
1696+{-# 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'. " #-}
1697+-- | See 'switchHoldPromptOnly'
1698+switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a)
1699+switchPromptOnly = switchHoldPromptOnly
src/Reflex/Collection.hsnew file+225
@@ -0,0 +1,225 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE LambdaCase #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE RankNTypes #-}
6+{-# LANGUAGE RecursiveDo #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE TypeFamilies #-}
9+{-# LANGUAGE UndecidableInstances #-}
10+#ifdef USE_REFLEX_OPTIMIZER
11+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12+#endif
13+-- |
14+-- Module:
15+-- Reflex.Collection
16+module Reflex.Collection
17+ (
18+ -- * Widgets on Collections
19+ listHoldWithKey
20+ , listWithKey
21+ , listWithKeyShallowDiff
22+ , listViewWithKey
23+ , selectViewListWithKey
24+ , selectViewListWithKey_
25+ -- * List Utils
26+ , list
27+ , simpleList
28+ ) where
29+
30+#ifdef MIN_VERSION_semialign
31+import Prelude hiding (zip, zipWith)
32+#if MIN_VERSION_semialign(1,1,0)
33+import Data.Zip (Zip (..))
34+#endif
35+#endif
36+
37+import Control.Monad.Identity
38+import Data.Align
39+import Data.Functor.Misc
40+import Data.Map (Map)
41+import qualified Data.Map as Map
42+import Data.Map.Misc
43+import Data.These
44+
45+import Reflex.Class
46+import Reflex.Adjustable.Class
47+import Reflex.Dynamic
48+import Reflex.PostBuild.Class
49+
50+-- | Create a set of widgets based on the provided 'Map'. When the
51+-- input 'Event' fires, remove widgets for keys with the value 'Nothing'
52+-- and add/replace widgets for keys with 'Just' values.
53+listHoldWithKey
54+ :: forall t m k v a
55+ . (Ord k, Adjustable t m, MonadHold t m)
56+ => Map k v
57+ -> Event t (Map k (Maybe v))
58+ -> (k -> v -> m a)
59+ -> m (Dynamic t (Map k a))
60+listHoldWithKey m0 m' f = do
61+ let dm0 = mapWithFunctorToDMap $ Map.mapWithKey f m0
62+ dm' = fmap
63+ (PatchDMap . mapWithFunctorToDMap . Map.mapWithKey
64+ (\k v -> ComposeMaybe $ fmap (f k) v)
65+ )
66+ m'
67+ (a0, a') <- sequenceDMapWithAdjust dm0 dm'
68+
69+ --TODO: Move the dmapToMap to the righthand side so it doesn't get
70+ --fully redone every time
71+ fmap dmapToMap . incrementalToDynamic <$> holdIncremental a0 a'
72+
73+--TODO: Something better than Dynamic t (Map k v) - we want something
74+--where the Events carry diffs, not the whole value
75+listWithKey
76+ :: forall t k v m a
77+ . (Ord k, Adjustable t m, PostBuild t m, MonadFix m, MonadHold t m)
78+ => Dynamic t (Map k v)
79+ -> (k -> Dynamic t v -> m a)
80+ -> m (Dynamic t (Map k a))
81+listWithKey vals mkChild = do
82+ postBuild <- getPostBuild
83+ let childValChangedSelector = fanMap $ updated vals
84+
85+ -- We keep track of changes to children values in the mkChild
86+ -- function we pass to listHoldWithKey The other changes we need
87+ -- to keep track of are child insertions and
88+ -- deletions. diffOnlyKeyChanges keeps track of insertions and
89+ -- deletions but ignores value changes, since they're already
90+ -- accounted for.
91+ diffOnlyKeyChanges olds news =
92+ flip Map.mapMaybe (align olds news) $ \case
93+ This _ -> Just Nothing
94+ These _ _ -> Nothing
95+ That new -> Just $ Just new
96+ rec sentVals :: Dynamic t (Map k v) <- foldDyn applyMap Map.empty changeVals
97+ let changeVals :: Event t (Map k (Maybe v))
98+ changeVals =
99+ attachWith diffOnlyKeyChanges (current sentVals) $ leftmost
100+ [ updated vals
101+
102+ -- TODO: This should probably be added to the
103+ -- attachWith, not to the updated; if we were using
104+ -- diffMap instead of diffMapNoEq, I think it might not
105+ -- work
106+ , tag (current vals) postBuild
107+ ]
108+ listHoldWithKey Map.empty changeVals $ \k v ->
109+ mkChild k =<< holdDyn v (select childValChangedSelector $ Const2 k)
110+
111+-- | Display the given map of items (in key order) using the builder
112+-- function provided, and update it with the given event. 'Nothing'
113+-- update entries will delete the corresponding children, and 'Just'
114+-- entries will create them if they do not exist or send an update
115+-- event to them if they do.
116+listWithKeyShallowDiff
117+ :: (Ord k, Adjustable t m, MonadFix m, MonadHold t m)
118+ => Map k v
119+ -> Event t (Map k (Maybe v))
120+ -> (k -> v -> Event t v -> m a)
121+ -> m (Dynamic t (Map k a))
122+listWithKeyShallowDiff initialVals valsChanged mkChild = do
123+ let childValChangedSelector = fanMap $ fmap (Map.mapMaybe id) valsChanged
124+ sentVals <- foldDyn applyMap (void initialVals) $ fmap (fmap void) valsChanged
125+ let relevantPatch patch _ = case patch of
126+
127+ -- Even if we let a Nothing through when the element doesn't
128+ -- already exist, this doesn't cause a problem because it is
129+ -- ignored
130+ Nothing -> Just Nothing
131+
132+ -- We don't want to let spurious re-creations of items through
133+ Just _ -> Nothing
134+ listHoldWithKey
135+ initialVals
136+ (attachWith (flip (Map.differenceWith relevantPatch))
137+ (current sentVals)
138+ valsChanged
139+ )
140+ $ \k v -> mkChild k v $ select childValChangedSelector $ Const2 k
141+
142+--TODO: Something better than Dynamic t (Map k v) - we want something
143+--where the Events carry diffs, not the whole value
144+-- | Create a dynamically-changing set of Event-valued widgets. This
145+-- is like 'listWithKey', specialized for widgets returning @/Event t a/@.
146+-- 'listWithKey' would return @/Dynamic t (Map k (Event t a))/@ in
147+-- this scenario, but 'listViewWithKey' flattens this to
148+-- @/Event t (Map k a)/@ via 'switch'.
149+listViewWithKey
150+ :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
151+ => Dynamic t (Map k v)
152+ -> (k -> Dynamic t v -> m (Event t a))
153+ -> m (Event t (Map k a))
154+listViewWithKey vals mkChild =
155+ switch . fmap mergeMap <$> listViewWithKey' vals mkChild
156+
157+listViewWithKey'
158+ :: (Ord k, Adjustable t m, PostBuild t m, MonadHold t m, MonadFix m)
159+ => Dynamic t (Map k v)
160+ -> (k -> Dynamic t v -> m a)
161+ -> m (Behavior t (Map k a))
162+listViewWithKey' vals mkChild = current <$> listWithKey vals mkChild
163+
164+-- | Create a dynamically-changing set of widgets, one of which is
165+-- selected at any time.
166+selectViewListWithKey
167+ :: forall t m k v a
168+ . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
169+ => Dynamic t k
170+ -- ^ Current selection key
171+ -> Dynamic t (Map k v)
172+ -- ^ Dynamic key/value map
173+ -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
174+ -- ^ Function to create a widget for a given key from Dynamic value
175+ -- and Dynamic Bool indicating if this widget is currently selected
176+ -> m (Event t (k, a))
177+ -- ^ Event that fires when any child's return Event fires. Contains
178+ -- key of an arbitrary firing widget.
179+selectViewListWithKey selection vals mkChild = do
180+ -- For good performance, this value must be shared across all children
181+ let selectionDemux = demux selection
182+ selectChild <- listWithKey vals $ \k v -> do
183+ let selected = demuxed selectionDemux k
184+ selectSelf <- mkChild k v selected
185+ return $ fmap ((,) k) selectSelf
186+ return $ switchPromptlyDyn $ leftmost . Map.elems <$> selectChild
187+
188+-- | Like 'selectViewListWithKey' but discards the value of the list
189+-- item widget's output 'Event'.
190+selectViewListWithKey_
191+ :: forall t m k v a
192+ . (Adjustable t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
193+ => Dynamic t k
194+ -- ^ Current selection key
195+ -> Dynamic t (Map k v)
196+ -- ^ Dynamic key/value map
197+ -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a))
198+ -- ^ Function to create a widget for a given key from Dynamic value
199+ -- and Dynamic Bool indicating if this widget is currently selected
200+ -> m (Event t k)
201+ -- ^ Event that fires when any child's return Event fires. Contains
202+ -- key of an arbitrary firing widget.
203+selectViewListWithKey_ selection vals mkChild =
204+ fmap fst <$> selectViewListWithKey selection vals mkChild
205+
206+-- | Create a dynamically-changing set of widgets from a Dynamic
207+-- key/value map. Unlike the 'withKey' variants, the child widgets
208+-- are insensitive to which key they're associated with.
209+list
210+ :: (Ord k, Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
211+ => Dynamic t (Map k v)
212+ -> (Dynamic t v -> m a)
213+ -> m (Dynamic t (Map k a))
214+list dm mkChild = listWithKey dm (\_ dv -> mkChild dv)
215+
216+-- | Create a dynamically-changing set of widgets from a Dynamic list.
217+simpleList
218+ :: (Adjustable t m, MonadHold t m, PostBuild t m, MonadFix m)
219+ => Dynamic t [v]
220+ -> (Dynamic t v -> m a)
221+ -> m (Dynamic t [a])
222+simpleList xs mkChild =
223+ fmap (fmap (map snd . Map.toList)) $ flip list mkChild $ fmap
224+ (Map.fromList . zip [(1 :: Int) ..])
225+ xs
src/Reflex/Dynamic.hs+427−308
@@ -1,308 +1,376 @@
1−{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RankNTypes, GADTs, ScopedTypeVariables, FunctionalDependencies, RecursiveDo, UndecidableInstances, GeneralizedNewtypeDeriving, StandaloneDeriving, EmptyDataDecls, NoMonomorphismRestriction, TypeOperators, DeriveDataTypeable, PackageImports, TemplateHaskell, LambdaCase, DataKinds, PolyKinds #-}
2−module Reflex.Dynamic ( Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update
3− , current
4− , updated
5− , constDyn
6− , holdDyn
7− , nubDyn
8− , count
9− , toggle
10− , switchPromptlyDyn
11− , tagDyn
12− , attachDyn
13− , attachDynWith
14− , attachDynWithMaybe
15− , mapDyn
16− , forDyn
17− , mapDynM
18− , foldDyn
19− , foldDynM
20− , combineDyn
21− , collectDyn
22− , mconcatDyn
23− , distributeDMapOverDyn
24− , joinDyn
25− , joinDynThroughMap
26− , traceDyn
27− , traceDynWith
28− , splitDyn
29− , Demux
30− , demux
31− , getDemuxed
32− -- Things that probably aren't very useful:
33− , HList (..)
34− , FHList (..)
35− , distributeFHListOverDyn
36− -- Unsafe
37− , unsafeDynamic
38− ) where
39−
40−import Prelude hiding (mapM, mapM_)
41−
42−import Reflex.Class
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+ , joinDynThroughIntMap
57+ , traceDyn
58+ , traceDynWith
59+ , splitDynPure
60+ , distributeMapOverDynPure
61+ , distributeIntMapOverDynPure
62+ , distributeDMapOverDynPure
63+ , distributeListOverDynPure
64+ , Demux
65+ , demux
66+ , demuxed
67+ -- * Miscellaneous
68+ -- Things that probably aren't very useful:
69+ , HList (..)
70+ , FHList (..)
71+ , collectDynPure
72+ , RebuildSortedHList (..)
73+ , IsHList (..)
74+ , AllAreFunctors (..)
75+ , HListPtr (..)
76+ , distributeFHListOverDynPure
77+ -- * Unsafe
78+ , unsafeDynamic
79+ ) where
80+
81+import Data.Functor.Compose
4382import Data.Functor.Misc
83+import Reflex.Class
4484
45−import Control.Monad hiding (mapM, mapM_, forM, forM_)
85+import Control.Monad
4686import Control.Monad.Fix
47−import Control.Monad.Identity hiding (mapM, mapM_, forM, forM_)
48−import Data.These
49−import Data.Traversable (mapM, forM)
87+import Control.Monad.Identity
5088import Data.Align
51−import Data.Map (Map)
52−import qualified Data.Map as Map
5389import Data.Dependent.Map (DMap)
5490import qualified Data.Dependent.Map as DMap
5591import Data.Dependent.Sum (DSum (..))
56−import Data.GADT.Compare (GCompare (..), GEq (..), (:~:) (..), GOrdering (..))
57−import Data.Monoid
58−--import Data.HList (HList (..), hBuild)
59−
60−data HList (l::[*]) where
61− HNil :: HList '[]
62− HCons :: e -> HList l -> HList (e ': l)
63−
64−infixr 2 `HCons`
65−
66−type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
67−type instance HRevApp '[] l = l
68−type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
69−
70−hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
71−hRevApp HNil l = l
72−hRevApp (HCons x l) l' = hRevApp l (HCons x l')
73−
74−hReverse l = hRevApp l HNil
75−
76−hEnd :: HList l -> HList l
77−hEnd = id
78−
79−hBuild :: (HBuild' '[] r) => r
80−hBuild = hBuild' HNil
81−
82−class HBuild' l r where
83− hBuild' :: HList l -> r
84−
85−instance (l' ~ HRevApp l '[])
86− => HBuild' l (HList l') where
87− hBuild' l = hReverse l
88−
89−instance HBuild' (a ': l) r
90− => HBuild' l (a->r) where
91− hBuild' l x = hBuild' (HCons x l)
92−
93−
94−data Dynamic t a
95− = Dynamic (Behavior t a) (Event t a)
96−
97−unsafeDynamic :: Behavior t a -> Event t a -> Dynamic t a
98−unsafeDynamic = Dynamic
99−
100−current :: Dynamic t a -> Behavior t a
101−current (Dynamic b _) = b
102−
103−updated :: Dynamic t a -> Event t a
104−updated (Dynamic _ e) = e
105−
106−constDyn :: Reflex t => a -> Dynamic t a
107−constDyn x = Dynamic (constant x) never
108−
109−holdDyn :: MonadHold t m => a -> Event t a -> m (Dynamic t a)
110−holdDyn v0 e = do
111− b <- hold v0 e
112− return $ Dynamic b e
113−
114−nubDyn :: (Reflex t, Eq a) => Dynamic t a -> Dynamic t a
115−nubDyn d =
116− let e' = attachWithMaybe (\x x' -> if x' == x then Nothing else Just x') (current d) (updated d)
117− in Dynamic (current d) e' --TODO: Avoid invalidating the outgoing Behavior
118−
119−{-
120−instance Reflex t => Functor (Dynamic t) where
121− fmap f d =
122− let e' = fmap f $ updated d
123− eb' = push (\b' -> liftM Just $ constant b') e'
124− b0 = fmap f $ current d
125−
126−-}
127−
128−mapDyn :: (Reflex t, MonadHold t m) => (a -> b) -> Dynamic t a -> m (Dynamic t b)
129−mapDyn f = mapDynM $ return . f
92+import Data.GADT.Compare (GCompare (..), GEq (..), GOrdering (..))
93+import Data.IntMap (IntMap)
94+import qualified Data.IntMap as IntMap
95+import Data.Map (Map)
96+import Data.Maybe
97+import Data.Monoid ((<>))
98+import Data.These
99+import Data.Type.Equality ((:~:) (..))
130100
131−forDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> (a -> b) -> m (Dynamic t b)
132−forDyn = flip mapDyn
101+import Debug.Trace
133102
134−{-# INLINE mapDynM #-}
103+-- | Map a sampling function over a 'Dynamic'.
135104mapDynM :: 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)
136−mapDynM f d = do
137− let e' = push (liftM Just . f :: a -> PushM t (Maybe b)) $ updated d
138− eb' = fmap constant e'
139− v0 = pull $ f =<< sample (current d)
140− bb' :: Behavior t (Behavior t b) <- hold v0 eb'
141− let b' = pull $ sample =<< sample bb'
142− return $ Dynamic b' e'
143−
105+mapDynM f d = buildDynamic (f =<< sample (current d)) $ pushAlways f (updated d)
106+
107+-- | Flipped version of 'mapDynM'
108+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)
109+forDynM d f = mapDynM f d
110+
111+-- | Create a new 'Dynamic' that only signals changes if the values actually
112+-- changed.
113+holdUniqDyn :: (Reflex t, MonadHold t m, MonadFix m, Eq a) => Dynamic t a -> m (Dynamic t a)
114+holdUniqDyn = holdUniqDynBy (==)
115+
116+-- | Create a new 'Dynamic' that changes only when the underlying 'Dynamic'
117+-- changes and the given function returns 'False' when given both the old and
118+-- the new values.
119+holdUniqDynBy :: (Reflex t, MonadHold t m, MonadFix m) => (a -> a -> Bool) -> Dynamic t a -> m (Dynamic t a)
120+holdUniqDynBy eq = scanDynMaybe id (\new old -> if new `eq` old then Nothing else Just new)
121+
122+-- | @/Dynamic Maybe/@ that can only update from @/Nothing/@ to @/Just/@ or @/Just/@ to @/Just/@ (i.e., cannot revert to @/Nothing/@)
123+improvingMaybe :: (Reflex t, MonadHold t m, MonadFix m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe a))
124+improvingMaybe = scanDynMaybe id (\new _ -> if isJust new then Just new else Nothing)
125+
126+-- | Create a 'Dynamic' that accumulates values from another 'Dynamic'. This
127+-- function does not force its input 'Dynamic' until the output 'Dynamic' is
128+-- forced.
129+scanDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> b) -> Dynamic t a -> m (Dynamic t b)
130+scanDyn z f = scanDynMaybe z (\a b -> Just $ f a b)
131+
132+-- | Like 'scanDyn', but the the accumulator function may decline to update the
133+-- result 'Dynamic''s value.
134+scanDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b) -> (a -> b -> Maybe b) -> Dynamic t a -> m (Dynamic t b)
135+scanDynMaybe z f d = do
136+ rec d' <- buildDynamic (z <$> sample (current d)) $ flip push (updated d) $ \a -> do
137+ b <- sample $ current d'
138+ return $ f a b
139+ return d'
140+
141+-- | Create a 'Dynamic' using the initial value and change it each time the
142+-- 'Event' occurs using a folding function on the previous value and the value
143+-- of the 'Event'.
144144foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b)
145−foldDyn f = foldDynM (\o v -> return $ f o v)
145+foldDyn = accumDyn . flip
146146
147+-- | Like 'foldDyn', but the combining function is a 'PushM' action, so it
148+-- can 'sample' existing 'Behaviors' and 'hold' new ones.
147149foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b)
148−foldDynM f z e = do
149− rec let e' = flip push e $ \o -> do
150− v <- sample b'
151− liftM Just $ f o v
152− b' <- hold z e'
153− return $ Dynamic b' e'
154−
150+foldDynM = accumMDyn . flip
151+
152+-- | Create a 'Dynamic' using the provided initial value and change it each time
153+-- the provided 'Event' occurs, using a function to combine the old value with
154+-- the 'Event''s value. If the function returns 'Nothing', the value is not
155+-- changed; this is distinct from returning 'Just' the old value, since the
156+-- 'Dynamic''s 'updated' 'Event' will fire in the 'Just' case, and will not fire
157+-- in the 'Nothing' case.
158+foldDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> Maybe b) -> b -> Event t a -> m (Dynamic t b)
159+foldDynMaybe = accumMaybeDyn . flip
160+
161+-- | Like 'foldDynMaybe', but the combining function is a 'PushM' action, so it
162+-- can 'sample' existing 'Behaviors' and 'hold' new ones.
163+foldDynMaybeM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe b)) -> b -> Event t a -> m (Dynamic t b)
164+foldDynMaybeM = accumMaybeMDyn . flip
165+
166+-- | Create a new 'Dynamic' that counts the occurrences of the 'Event'.
155167count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)
156168count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e
157169
170+-- | Create a new 'Dynamic' using the initial value that flips its
171+-- value every time the 'Event' occurs.
158172toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool)
159173toggle = foldDyn (const not)
160174
161−-- | Switches to the new event whenever it receives one. Switching occurs *before* occurring the inner event.
175+-- | Switches to the new 'Event' whenever it receives one. Only the old event is
176+-- considered the moment a new one is switched in; the output event will fire at
177+-- that moment if only if the old event does.
178+--
179+-- Prefer this to 'switchPromptlyDyn' where possible. The lack of doing double
180+-- work when the outer and (new) inner fires means this imposes fewer "timing
181+-- requirements" and thus is far more easy to use without introducing fresh
182+-- failure cases. 'switchDyn' is also more performant.
183+switchDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
184+switchDyn d = switch (current d)
185+
186+-- | Switches to the new 'Event' whenever it receives one. Switching occurs
187+-- __before__ the inner 'Event' fires - so if the 'Dynamic' changes and both the
188+-- old and new inner Events fire simultaneously, the output will fire with the
189+-- value of the __new__ 'Event'.
190+--
191+-- Prefer 'switchDyn' to this where possible. The timing requirements that
192+-- switching before imposes are likely to bring down your app unless you are
193+-- very careful. 'switchDyn' is also more performant.
162194switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a
163195switchPromptlyDyn de =
164196 let eLag = switch $ current de
165197 eCoincidences = coincidence $ updated de
166198 in leftmost [eCoincidences, eLag]
167199
168−{-
169−
170−mergeEventsWith :: Reflex t m => (a -> a -> a) -> Event t a -> Event t a -> m (Event t a)
171−mergeEventsWith f ea eb = mapE (mergeThese f) =<< alignEvents ea eb
172−
173−firstE :: (Reflex t m) => [Event t a] -> m (Event t a)
174−firstE [] = return never
175−firstE (h:t) = mergeEventsLeftBiased h =<< firstE t
176−
177−concatEventsWith :: (Reflex t m) => (a -> a -> a) -> [Event t a] -> m (Event t a)
178−concatEventsWith _ [] = return never
179−concatEventsWith _ [e] = return e
180−concatEventsWith f es = mapEM (liftM (foldl1 f . map (\(Const2 _ :=> v) -> v) . DMap.toList) . sequenceDmap) <=< mergeEventDMap $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es
181−--concatEventsWith f (h:t) = mergeEventsWith f h =<< concatEventsWith f t
182−
183−mconcatE :: (Reflex t m, Monoid a) => [Event t a] -> m (Event t a)
184−mconcatE = concatEventsWith mappend
185−-}
186−
187−splitDyn :: (Reflex t, MonadHold t m) => Dynamic t (a, b) -> m (Dynamic t a, Dynamic t b)
188−splitDyn d = liftM2 (,) (mapDyn fst d) (mapDyn snd d)
189−
190−mconcatDyn :: forall t m a. (Reflex t, MonadHold t m, Monoid a) => [Dynamic t a] -> m (Dynamic t a)
191−mconcatDyn es = do
192− ddm :: Dynamic t (DMap (Const2 Int a)) <- distributeDMapOverDyn $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es
193− mapDyn (mconcat . map (\(Const2 _ :=> v) -> v) . DMap.toList) ddm
194−
195−distributeDMapOverDyn :: forall t m k. (Reflex t, MonadHold t m, GCompare k) => DMap (WrapArg (Dynamic t) k) -> m (Dynamic t (DMap k))
196−distributeDMapOverDyn dm = case DMap.toList dm of
197− [] -> return $ constDyn DMap.empty
198− [WrapArg k :=> v] -> mapDyn (DMap.singleton k) v
199− _ -> do
200− let edmPre = merge $ rewrapDMap updated dm
201− edm :: Event t (DMap k) = flip push edmPre $ \o -> return . Just =<< do
202− let f _ = \case
203− This origDyn -> sample $ current origDyn
204− That _ -> error "distributeDMapOverDyn: should be impossible to have an event occurring that is not present in the original DMap"
205− These _ (Identity newVal) -> return newVal
206− sequenceDmap $ combineDMapsWithKey f dm (wrapDMap Identity o)
207− dm0 :: Behavior t (DMap k) = pull $ do
208− liftM DMap.fromList $ forM (DMap.toList dm) $ \(WrapArg k :=> dv) -> liftM (k :=>) $ sample $ current dv
209− bbdm :: Behavior t (Behavior t (DMap k)) <- hold dm0 $ fmap constant edm
210− let bdm = pull $ sample =<< sample bbdm
211− return $ Dynamic bdm edm
212−
213−combineDyn :: forall t m a b c. (Reflex t, MonadHold t m) => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> m (Dynamic t c)
214−combineDyn f da db = do
215− let eab = align (updated da) (updated db)
216− ec = flip push eab $ \o -> do
217− (a, b) <- case o of
218− This a -> do
219− b <- sample $ current db
220− return (a, b)
221− That b -> do
222− a <- sample $ current da
223− return (a, b)
224− These a b -> return (a, b)
225− return $ Just $ f a b
226− c0 :: Behavior t c = pull $ liftM2 f (sample $ current da) (sample $ current db)
227− bbc :: Behavior t (Behavior t c) <- hold c0 $ fmap constant ec
228− let bc :: Behavior t c = pull $ sample =<< sample bbc
229− return $ Dynamic bc ec
230−
231−{-
232−tagInnerDyn :: Reflex t => Event t (Dynamic t a) -> Event t a
233−tagInnerDyn e =
234− let eSlow = push (liftM Just . sample . current) e
235− eFast = coincidence $ fmap updated e
236− in leftmost [eFast, eSlow]
237−-}
238−
239−joinDyn :: forall t a. (Reflex t) => Dynamic t (Dynamic t a) -> Dynamic t a
240−joinDyn dd =
241− let b' = pull $ sample . current =<< sample (current dd)
242− eOuter :: Event t a = pushAlways (sample . current) $ updated dd
243− eInner :: Event t a = switch $ fmap updated (current dd)
244− eBoth :: Event t a = coincidence $ fmap updated (updated dd)
245− e' = leftmost [eBoth, eOuter, eInner]
246− in Dynamic b' e'
200+-- | Split a 'Dynamic' pair into a pair of 'Dynamic's
201+splitDynPure :: Reflex t => Dynamic t (a, b) -> (Dynamic t a, Dynamic t b)
202+splitDynPure d = (fmap fst d, fmap snd d)
203+
204+-- | Convert a 'Map' with 'Dynamic' elements into a 'Dynamic' of a 'Map' with
205+-- non-'Dynamic' elements.
206+distributeMapOverDynPure :: (Reflex t, Ord k) => Map k (Dynamic t v) -> Dynamic t (Map k v)
207+distributeMapOverDynPure = fmap dmapToMap . distributeDMapOverDynPure . mapWithFunctorToDMap
208+
209+-- | Convert an 'IntMap' with 'Dynamic' elements into a 'Dynamic' of an 'IntMap' with
210+-- non-'Dynamic' elements.
211+distributeIntMapOverDynPure :: (Reflex t) => IntMap (Dynamic t v) -> Dynamic t (IntMap v)
212+distributeIntMapOverDynPure = fmap dmapToIntMap . distributeDMapOverDynPure . intMapWithFunctorToDMap
213+
214+-- | Convert a list with 'Dynamic' elements into a 'Dynamic' of a list with
215+-- non-'Dynamic' elements, preserving the order of the elements.
216+{-# DEPRECATED distributeListOverDynPure "Use 'distributeListOverDyn' instead" #-}
217+distributeListOverDynPure :: Reflex t => [Dynamic t v] -> Dynamic t [v]
218+distributeListOverDynPure = distributeListOverDyn
247219
248220--TODO: Generalize this to functors other than Maps
221+-- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic'
222+-- with the current values of the 'Dynamic's in a map.
249223joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)
250−joinDynThroughMap dd =
251− let b' = pull $ mapM (sample . current) =<< sample (current dd)
252− eOuter :: Event t (Map k a) = pushAlways (mapM (sample . current)) $ updated dd
253− eInner :: Event t (Map k a) = attachWith (flip Map.union) b' $ switch $ fmap (mergeMap . fmap updated) (current dd) --Note: the flip is important because Map.union is left-biased
254− readNonFiring :: MonadSample t m => These (Dynamic t a) a -> m a
255− readNonFiring = \case
256− This d -> sample $ current d
257− That a -> return a
258− These _ a -> return a
259− eBoth :: Event t (Map k a) = coincidence $ fmap (\m -> pushAlways (mapM readNonFiring . align m) $ mergeMap $ fmap updated m) (updated dd)
260− e' = leftmost [eBoth, eOuter, eInner]
261− in Dynamic b' e'
262−
224+joinDynThroughMap = (distributeMapOverDynPure =<<)
225+
226+-- | Combine a 'Dynamic' of an 'IntMap' of 'Dynamic's into a 'Dynamic'
227+-- with the current values of the 'Dynamic's in a map.
228+joinDynThroughIntMap :: forall t a. (Reflex t) => Dynamic t (IntMap (Dynamic t a)) -> Dynamic t (IntMap a)
229+joinDynThroughIntMap = (distributeIntMapOverDynPure =<<)
230+
231+-- | Print the value of the 'Dynamic' when it is first read and on each
232+-- subsequent change that is observed (as 'traceEvent'), prefixed with the
233+-- provided string. This should /only/ be used for debugging.
234+--
235+-- Note: Just like Debug.Trace.trace, the value will only be shown if something
236+-- else in the system is depending on it.
263237traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a
264238traceDyn s = traceDynWith $ \x -> s <> ": " <> show x
265239
240+-- | Print the result of applying the provided function to the value
241+-- of the 'Dynamic' when it is first read and on each subsequent change
242+-- that is observed (as 'traceEvent'). This should /only/ be used for
243+-- debugging.
244+--
245+-- Note: Just like Debug.Trace.trace, the value will only be shown if something
246+-- else in the system is depending on it.
266247traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a
267248traceDynWith f d =
268249 let e' = traceEventWith f $ updated d
269− in Dynamic (current d) e'
270−
271−tagDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
272−tagDyn = attachDynWith const
273−
274−attachDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
275−attachDyn = attachDynWith (,)
276−
277−attachDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
278−attachDynWith f = attachDynWithMaybe $ \a b -> Just $ f a b
279−
280−attachDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
281−attachDynWithMaybe f d e =
250+ getV0 = do
251+ x <- sample $ current d
252+ trace (f x) $ return x
253+ in unsafeBuildDynamic getV0 e'
254+
255+-- | Replace the value of the 'Event' with the current value of the 'Dynamic'
256+-- each time the 'Event' occurs.
257+--
258+-- Note: @/tagPromptlyDyn d e/@ differs from @/tag (current d) e/@ in the case that @/e/@ is firing
259+-- at the same time that @/d/@ is changing. With @/tagPromptlyDyn d e/@, the __new__ value of @/d/@
260+-- will replace the value of @/e/@, whereas with @/tag (current d) e/@, the __old__ value
261+-- will be used, since the 'Behavior' won't be updated until the end of the frame.
262+-- Additionally, this means that the output 'Event' may not be used to directly change
263+-- the input 'Dynamic', because that would mean its value depends on itself. __When creating__
264+-- __cyclic data flows, generally @/tag (current d) e/@ is preferred.__
265+tagPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a
266+tagPromptlyDyn = attachPromptlyDynWith const
267+
268+-- | Attach the current value of the 'Dynamic' to the value of the
269+-- 'Event' each time it occurs.
270+--
271+-- Note: @/attachPromptlyDyn d/@ is not the same as @/attach (current d)/@. See 'tagPromptlyDyn' for details.
272+attachPromptlyDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b)
273+attachPromptlyDyn = attachPromptlyDynWith (,)
274+
275+-- | Combine the current value of the 'Dynamic' with the value of the
276+-- 'Event' each time it occurs.
277+--
278+-- Note: @/attachPromptlyDynWith f d/@ is not the same as @/attachWith f (current d)/@. See 'tagPromptlyDyn' for details.
279+attachPromptlyDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c
280+attachPromptlyDynWith f = attachPromptlyDynWithMaybe $ \a b -> Just $ f a b
281+
282+-- | Create a new 'Event' by combining the value at each occurrence with the
283+-- current value of the 'Dynamic' value and possibly filtering if the combining
284+-- function returns 'Nothing'.
285+--
286+-- Note: @/attachPromptlyDynWithMaybe f d/@ is not the same as @/attachWithMaybe f (current d)/@. See 'tagPromptlyDyn' for details.
287+attachPromptlyDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c
288+attachPromptlyDynWithMaybe f d e =
282289 let e' = attach (current d) e
283290 in fforMaybe (align e' $ updated d) $ \case
284291 This (a, b) -> f a b -- Only the tagging event is firing, so use that
285292 These (_, b) a -> f a b -- Both events are firing, so use the newer value
286293 That _ -> Nothing -- The tagging event isn't firing, so don't fire
287294
295+-- | Factor a @/Dynamic t (Maybe a)/@ into a @/Dynamic t (Maybe (Dynamic t a))/@,
296+-- such that the outer 'Dynamic' is updated only when the "Maybe"'s constructor
297+-- chages from 'Nothing' to 'Just' or vice-versa. Whenever the constructor
298+-- becomes 'Just', an inner 'Dynamic' will be provided, whose value will track
299+-- the 'a' inside the 'Just'; when the constructor becomes 'Nothing', the
300+-- existing inner 'Dynamic' will become constant, and will not change when the
301+-- outer constructor changes back to 'Nothing'.
302+maybeDyn :: forall t a m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe (Dynamic t a)))
303+maybeDyn = fmap (fmap unpack) . eitherDyn . fmap pack
304+ where pack = \case
305+ Nothing -> Left ()
306+ Just a -> Right a
307+ unpack = \case
308+ Left _ -> Nothing
309+ Right a -> Just a
310+
311+-- | Turns a 'Dynamic t (Either a b)' into a 'Dynamic t (Either (Dynamic t a) (Dynamic t b))' such that
312+-- the outer 'Dynamic' is updated only when the 'Either' constructor changes (e.g., from 'Left' to 'Right').
313+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)))
314+eitherDyn = fmap (fmap unpack) . factorDyn . fmap eitherToDSum
315+ where unpack :: DSum (EitherTag a b) (Compose (Dynamic t) Identity) -> Either (Dynamic t a) (Dynamic t b)
316+ unpack = \case
317+ LeftTag :=> Compose a -> Left $ coerceDynamic a
318+ RightTag :=> Compose b -> Right $ coerceDynamic b
319+
320+-- | Factor a 'Dynamic t DSum' into a 'Dynamic' 'DSum' containing nested 'Dynamic' values.
321+-- The outer 'Dynamic' updates only when the key of the 'DSum' changes, while the update of the inner
322+-- 'Dynamic' represents updates within the current key.
323+factorDyn :: forall t m k v. (Reflex t, MonadHold t m, GEq k)
324+ => Dynamic t (DSum k v) -> m (Dynamic t (DSum k (Compose (Dynamic t) v)))
325+factorDyn d = buildDynamic (sample (current d) >>= holdKey) update where
326+ update :: Event t (DSum k (Compose (Dynamic t) v))
327+ update = flip push (updated d) $ \(newKey :=> newVal) -> do
328+ (oldKey :=> _) <- sample (current d)
329+ case newKey `geq` oldKey of
330+ Just Refl -> return Nothing
331+ Nothing -> Just <$> holdKey (newKey :=> newVal)
332+
333+ holdKey (k :=> v) = do
334+ inner' <- filterEventKey k (updated d)
335+ inner <- holdDyn v inner'
336+ return $ k :=> Compose inner
337+
288338--------------------------------------------------------------------------------
289339-- Demux
290340--------------------------------------------------------------------------------
291341
342+-- | Represents a time changing value together with an 'EventSelector' that can
343+-- efficiently detect when the underlying 'Dynamic' has a particular value.
344+-- This is useful for representing data like the current selection of a long
345+-- list.
346+--
347+-- Semantically,
348+--
349+-- > demuxed (demux d) k === fmap (== k) d
350+--
351+-- However, when 'demuxed' is used multiple times, the complexity is only
352+-- /O(log(n))/, rather than /O(n)/ for fmap.
292353data Demux t k = Demux { demuxValue :: Behavior t k
293354 , demuxSelector :: EventSelector t (Const2 k Bool)
294355 }
295356
357+-- | Demultiplex an input value to a 'Demux' with many outputs. At any given
358+-- time, whichever output is indicated by the given 'Dynamic' will be 'True'.
296359demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k
297−demux k = Demux (current k) (fan $ attachWith (\k0 k1 -> if k0 == k1 then DMap.empty else DMap.fromList [Const2 k0 :=> False, Const2 k1 :=> True]) (current k) (updated k))
298−
299−--TODO: The pattern of using hold (sample b0) can be reused in various places as a safe way of building certain kinds of Dynamics; see if we can factor this out
300−getDemuxed :: (Reflex t, MonadHold t m, Eq k) => Demux t k -> k -> m (Dynamic t Bool)
301−getDemuxed d k = do
360+demux k = Demux (current k)
361+ (fan $ attachWith (\k0 k1 -> if k0 == k1
362+ then DMap.empty
363+ else DMap.fromList [Const2 k0 :=> Identity False,
364+ Const2 k1 :=> Identity True])
365+ (current k) (updated k))
366+
367+-- | Select a particular output of the 'Demux'; this is equivalent to (but much
368+-- faster than) mapping over the original 'Dynamic' and checking whether it is
369+-- equal to the given key.
370+demuxed :: (Reflex t, Eq k) => Demux t k -> k -> Dynamic t Bool
371+demuxed d k =
302372 let e = select (demuxSelector d) (Const2 k)
303− bb <- hold (liftM (==k) $ sample $ demuxValue d) $ fmap return e
304− let b = pull $ join $ sample bb
305− return $ Dynamic b e
373+ in unsafeBuildDynamic (fmap (==k) $ sample $ demuxValue d) e
306374
307375--------------------------------------------------------------------------------
308376-- collectDyn
@@ -310,23 +378,45 @@ getDemuxed d k = do
310378
311379--TODO: This whole section is badly in need of cleanup
312380
381+-- | A heterogeneous list whose type and length are fixed statically. This is
382+-- reproduced from the 'HList' package due to integration issues, and because
383+-- very little other functionality from that library is needed.
384+data HList (l::[*]) where
385+ HNil :: HList '[]
386+ HCons :: e -> HList l -> HList (e ': l)
387+
388+infixr 2 `HCons`
389+
390+type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k]
391+type instance HRevApp '[] l = l
392+type instance HRevApp (e ': l) l' = HRevApp l (e ': l')
393+
394+hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2)
395+hRevApp HNil l = l
396+hRevApp (HCons x l) l' = hRevApp l (HCons x l')
397+
398+hReverse :: HList l -> HList (HRevApp l '[])
399+hReverse l = hRevApp l HNil
400+
401+hBuild :: (HBuild' '[] r) => r
402+hBuild = hBuild' HNil
403+
404+class HBuild' l r where
405+ hBuild' :: HList l -> r
406+
407+instance (l' ~ HRevApp l '[])
408+ => HBuild' l (HList l') where
409+ hBuild' = hReverse
410+
411+instance HBuild' (a ': l) r
412+ => HBuild' l (a->r) where
413+ hBuild' l x = hBuild' (HCons x l)
414+
415+-- | Like 'HList', but with a functor wrapping each element.
313416data FHList f l where
314417 FHNil :: FHList f '[]
315418 FHCons :: f e -> FHList f l -> FHList f (e ': l)
316419
317−natMap :: (forall a. f a -> g a) -> FHList f l -> FHList g l
318−natMap f = \case
319− FHNil -> FHNil
320− h `FHCons` t -> f h `FHCons` natMap f t
321−
322−sequenceFHList :: Monad m => FHList m l -> m (HList l)
323−sequenceFHList = \case
324− FHNil -> return HNil
325− h `FHCons` t -> do
326− hResult <- h
327− tResult <- sequenceFHList t
328− return $ hResult `HCons` tResult
329−
330420instance GEq (HListPtr l) where
331421 HHeadPtr `geq` HHeadPtr = Just Refl
332422 HHeadPtr `geq` HTailPtr _ = Nothing
@@ -339,47 +429,54 @@ instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dma
339429 HTailPtr _ `gcompare` HHeadPtr = GGT
340430 HTailPtr a `gcompare` HTailPtr b = a `gcompare` b
341431
432+-- | A typed index into a typed heterogeneous list.
342433data HListPtr l a where
343434 HHeadPtr :: HListPtr (h ': t) h
344435 HTailPtr :: HListPtr t a -> HListPtr (h ': t) a
345436
346−fhlistToDMap :: forall f l. FHList f l -> DMap (WrapArg f (HListPtr l))
437+deriving instance Eq (HListPtr l a)
438+deriving instance Ord (HListPtr l a)
439+
440+fhlistToDMap :: forall (f :: * -> *) l. FHList f l -> DMap (HListPtr l) f
347441fhlistToDMap = DMap.fromList . go
348− where go :: forall l'. FHList f l' -> [DSum (WrapArg f (HListPtr l'))]
442+ where go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]
349443 go = \case
350444 FHNil -> []
351− FHCons h t -> (WrapArg HHeadPtr :=> h) : map (\(WrapArg p :=> v) -> WrapArg (HTailPtr p) :=> v) (go t)
445+ FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)
352446
447+-- | This class allows 'HList's and 'FHlist's to be built from regular lists;
448+-- they must be contiguous and sorted.
353449class RebuildSortedHList l where
354− rebuildSortedFHList :: [DSum (WrapArg f (HListPtr l))] -> FHList f l
355− rebuildSortedHList :: [DSum (HListPtr l)] -> HList l
450+ rebuildSortedFHList :: [DSum (HListPtr l) f] -> FHList f l
451+ rebuildSortedHList :: [DSum (HListPtr l) Identity] -> HList l
356452
357453instance RebuildSortedHList '[] where
358− rebuildSortedFHList [] = FHNil
359− rebuildSortedHList [] = HNil
454+ rebuildSortedFHList l = case l of
455+ [] -> FHNil
456+ _ : _ -> error "rebuildSortedFHList{'[]}: empty list expected"
457+ rebuildSortedHList l = case l of
458+ [] -> HNil
459+ _ : _ -> error "rebuildSortedHList{'[]}: empty list expected"
360460
361461instance RebuildSortedHList t => RebuildSortedHList (h ': t) where
362− rebuildSortedFHList ((WrapArg HHeadPtr :=> h) : t) = FHCons h $ rebuildSortedFHList $ map (\(WrapArg (HTailPtr p) :=> v) -> WrapArg p :=> v) t
363− rebuildSortedHList ((HHeadPtr :=> h) : t) = HCons h $ rebuildSortedHList $ map (\(HTailPtr p :=> v) -> p :=> v) t
364−
365−
366−dmapToFHList :: forall f l. RebuildSortedHList l => DMap (WrapArg f (HListPtr l)) -> FHList f l
367−dmapToFHList = rebuildSortedFHList . DMap.toList
368−
369−dmapToHList :: forall f l. RebuildSortedHList l => DMap (HListPtr l) -> HList l
462+ rebuildSortedFHList l = case l of
463+ ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
464+ _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected"
465+ rebuildSortedHList l = case l of
466+ ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t
467+ _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected"
468+
469+dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) Identity -> HList l
370470dmapToHList = rebuildSortedHList . DMap.toList
371471
372−distributeFHListOverDyn :: forall t m l. (Reflex t, MonadHold t m, RebuildSortedHList l) => FHList (Dynamic t) l -> m (Dynamic t (HList l))
373−distributeFHListOverDyn l = mapDyn dmapToHList =<< distributeDMapOverDyn (fhlistToDMap l)
374−{-
375−distributeFHListOverDyn l = do
376− let ec = undefined
377− c0 = pull $ sequenceFHList $ natMap (sample . current) l
378− bbc <- hold c0 $ fmap constant ec
379− let bc = pull $ sample =<< sample bbc
380− return $ Dynamic bc ec
381−-}
472+-- | Collect a hetereogeneous list whose elements are all 'Dynamic's into a
473+-- single 'Dynamic' whose value represents the current values of all of the
474+-- input 'Dynamic's.
475+distributeFHListOverDynPure :: (Reflex t, RebuildSortedHList l) => FHList (Dynamic t) l -> Dynamic t (HList l)
476+distributeFHListOverDynPure l = fmap dmapToHList $ distributeDMapOverDynPure $ fhlistToDMap l
382477
478+-- | Indicates that all elements in a type-level list are applications of the
479+-- same functor.
383480class AllAreFunctors (f :: a -> *) (l :: [a]) where
384481 type FunctorList f l :: [*]
385482 toFHList :: HList (FunctorList f l) -> FHList f l
@@ -387,24 +484,34 @@ class AllAreFunctors (f :: a -> *) (l :: [a]) where
387484
388485instance AllAreFunctors f '[] where
389486 type FunctorList f '[] = '[]
390− toFHList HNil = FHNil
487+ toFHList l = case l of
488+ HNil -> FHNil
489+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
490+ _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
491+#endif
391492 fromFHList FHNil = HNil
392493
393494instance AllAreFunctors f t => AllAreFunctors f (h ': t) where
394495 type FunctorList f (h ': t) = f h ': FunctorList f t
395− toFHList (a `HCons` b) = a `FHCons` toFHList b
496+ toFHList l = case l of
497+ a `HCons` b -> a `FHCons` toFHList b
498+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
499+ _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
500+#endif
396501 fromFHList (a `FHCons` b) = a `HCons` fromFHList b
397502
398−collectDyn :: ( RebuildSortedHList (HListElems b)
399− , IsHList a, IsHList b
400− , AllAreFunctors (Dynamic t) (HListElems b)
401− , Reflex t, MonadHold t m
402− , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
403− ) => a -> m (Dynamic t b)
404−collectDyn ds =
405− mapDyn fromHList =<< distributeFHListOverDyn (toFHList $ toHList ds)
406−
407−-- Poor man's Generic
503+-- | Convert a datastructure whose constituent parts are all 'Dynamic's into a
504+-- single 'Dynamic' whose value represents all the current values of the input's
505+-- constituent 'Dynamic's.
506+collectDynPure :: ( RebuildSortedHList (HListElems b)
507+ , IsHList a, IsHList b
508+ , AllAreFunctors (Dynamic t) (HListElems b)
509+ , Reflex t
510+ , HListElems a ~ FunctorList (Dynamic t) (HListElems b)
511+ ) => a -> Dynamic t b
512+collectDynPure ds = fmap fromHList $ distributeFHListOverDynPure $ toFHList $ toHList ds
513+
514+-- | Poor man's 'Generic's for product types only.
408515class IsHList a where
409516 type HListElems a :: [*]
410517 toHList :: a -> HList (HListElems a)
@@ -413,14 +520,26 @@ class IsHList a where
413520instance IsHList (a, b) where
414521 type HListElems (a, b) = [a, b]
415522 toHList (a, b) = hBuild a b
416− fromHList (a `HCons` b `HCons` HNil) = (a, b)
523+ fromHList l = case l of
524+ a `HCons` b `HCons` HNil -> (a, b)
525+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
526+ _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
527+#endif
417528
418529instance IsHList (a, b, c, d) where
419530 type HListElems (a, b, c, d) = [a, b, c, d]
420531 toHList (a, b, c, d) = hBuild a b c d
421− fromHList (a `HCons` b `HCons` c `HCons` d `HCons` HNil) = (a, b, c, d)
532+ fromHList l = case l of
533+ a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d)
534+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
535+ _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
536+#endif
422537
423538instance IsHList (a, b, c, d, e, f) where
424539 type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]
425540 toHList (a, b, c, d, e, f) = hBuild a b c d e f
426− fromHList (a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil) = (a, b, c, d, e, f)
541+ fromHList l = case l of
542+ a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f)
543+#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800
544+ _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
545+#endif
src/Reflex/Dynamic/TH.hs+81−14
@@ -1,39 +1,106 @@
1−{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, TypeOperators, GADTs, EmptyDataDecls #-}
2−module Reflex.Dynamic.TH (qDyn, unqDyn) where
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
317
418import Reflex.Dynamic
519
6−import Language.Haskell.TH
7−import Data.Data
8−import Control.Monad
920import 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
1029
11−-- | Quote a Dynamic expression. Within the quoted expression, you can use '$(unqDyn [| x |])' to refer to any expression 'x' of type 'Dynamic t a'; the unquoted result will be of type 'a'
12−qDyn :: Q Exp -> Q Exp
13−qDyn qe = do
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
1435 e <- qe
1536 let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d
1637 f d = case eqT of
1738 Just (Refl :: d :~: Exp)
1839 | AppE (VarE m) eInner <- d
1940 , m == 'unqMarker
20− -> do n <- lift $ newName "dyn"
41+ -> do n <- lift $ newName "dynamicQuotedExpressionVariable"
2142 modify ((n, eInner):)
2243 return $ VarE n
2344 _ -> gmapM f d
2445 (e', exprsReversed) <- runStateT (gmapM f e) []
2546 let exprs = reverse exprsReversed
26− arg = foldr (\a b -> ConE 'FHCons `AppE` a `AppE` b) (ConE 'FHNil) $ map snd exprs
27− param = foldr (\a b -> ConP 'HCons [VarP a, b]) (ConP 'HNil []) $ map fst exprs
28− [| mapDyn $(return $ LamE [param] e') =<< distributeFHListOverDyn $(return arg) |]
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) |]
2950
51+-- | Antiquote a 'Dynamic' expression. This can /only/ be used inside of a
52+-- 'qDyn' quotation.
3053unqDyn :: Q Exp -> Q Exp
3154unqDyn e = [| unqMarker $e |]
3255
33−-- | This type represents an occurrence of unqDyn before it has been processed by qDyn. If you see it in a type error, it probably means that unqDyn has been used outside of a qDyn context.
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.
3459data UnqDyn
3560
36−-- unqMarker must not be exported; it is used only as a way of smuggling data from unqDyn to qDyn
61+-- unqMarker must not be exported; it is used only as a way of smuggling data
62+-- from unqDyn to qDyn
63+
3764--TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery
3865unqMarker :: a -> UnqDyn
3966unqMarker = 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+246
@@ -0,0 +1,246 @@
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.Morph
26+import Control.Monad.Primitive
27+import Control.Monad.Reader
28+import Control.Monad.Ref
29+import Control.Monad.State.Strict
30+import Data.Align
31+import Data.Dependent.Map (DMap)
32+import qualified Data.Dependent.Map as DMap
33+import Data.FastMutableIntMap
34+import Data.Functor.Misc
35+import Data.IntMap (IntMap)
36+import qualified Data.IntMap as IntMap
37+import Data.Map (Map)
38+import qualified Data.Map as Map
39+import Data.Semigroup (Semigroup(..))
40+import Data.Some (Some)
41+import Data.These
42+
43+import Reflex.Adjustable.Class
44+import Reflex.Class
45+import Reflex.DynamicWriter.Class
46+import Reflex.EventWriter.Class (EventWriter, tellEvent)
47+import Reflex.Host.Class
48+import qualified Data.Patch.MapWithMove as MapWithMove
49+import Reflex.PerformEvent.Class
50+import Reflex.PostBuild.Class
51+import Reflex.Query.Class
52+import Reflex.Requester.Class
53+import Reflex.TriggerEvent.Class
54+
55+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')
56+mapIncrementalMapValues f = unsafeMapIncremental (fmap f) (fmap f)
57+
58+mergeDynIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Dynamic t v)) -> Incremental t (PatchMap k v)
59+mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
60+ where changedValues = fmap (PatchMap . fmap Just) $ mergeMapIncremental $ mapIncrementalMapValues updated a
61+ addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m
62+
63+mergeIntMapDynIncremental :: Reflex t => Incremental t (PatchIntMap (Dynamic t v)) -> Incremental t (PatchIntMap v)
64+mergeIntMapDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
65+ where changedValues = fmap (PatchIntMap . fmap Just) $ mergeIntMapIncremental $ mapIncrementalMapValues updated a
66+ addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchIntMap m) -> PatchIntMap <$> mapM (mapM (sample . current)) m
67+
68+mergeDynIncrementalWithMove :: forall t k v. (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Dynamic t v)) -> Incremental t (PatchMapWithMove k v)
69+mergeDynIncrementalWithMove a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ alignWith f addedAndRemovedValues changedValues
70+ where changedValues = mergeMapIncrementalWithMove $ mapIncrementalMapValues updated a
71+ addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ fmap unsafePatchMapWithMove . mapM (mapM (sample . current)) . unPatchMapWithMove
72+ f :: These (PatchMapWithMove k v) (Map k v) -> PatchMapWithMove k v
73+ f x = unsafePatchMapWithMove $
74+ let (p, changed) = case x of
75+ This p_ -> (unPatchMapWithMove p_, mempty)
76+ That c -> (mempty, c)
77+ These p_ c -> (unPatchMapWithMove p_, c)
78+ (pWithNewVals, noLongerMoved) = flip runState [] $ forM p $ MapWithMove.nodeInfoMapMFrom $ \case
79+ MapWithMove.From_Insert v -> return $ MapWithMove.From_Insert v
80+ MapWithMove.From_Delete -> return MapWithMove.From_Delete
81+ MapWithMove.From_Move k -> case Map.lookup k changed of
82+ Nothing -> return $ MapWithMove.From_Move k
83+ Just v -> do
84+ modify (k:)
85+ return $ MapWithMove.From_Insert v
86+ noLongerMovedMap = Map.fromList $ fmap (, ()) noLongerMoved
87+ in Map.differenceWith (\e _ -> Just $ MapWithMove.nodeInfoSetTo Nothing e) pWithNewVals noLongerMovedMap --TODO: Check if any in the second map are not covered?
88+
89+-- | A basic implementation of 'DynamicWriter'.
90+newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT [Dynamic t w] m a }
91+ -- The list is kept in reverse order
92+ deriving
93+ ( Functor
94+ , Applicative
95+ , Monad
96+ , MonadTrans
97+ , MFunctor
98+ , MonadIO
99+ , MonadFix
100+ , MonadAsyncException
101+ , MonadException
102+ )
103+
104+deriving instance MonadHold t m => MonadHold t (DynamicWriterT t w m)
105+deriving instance MonadSample t m => MonadSample t (DynamicWriterT t w m)
106+
107+
108+instance MonadRef m => MonadRef (DynamicWriterT t w m) where
109+ type Ref (DynamicWriterT t w m) = Ref m
110+ newRef = lift . newRef
111+ readRef = lift . readRef
112+ writeRef r = lift . writeRef r
113+
114+instance MonadAtomicRef m => MonadAtomicRef (DynamicWriterT t w m) where
115+ atomicModifyRef r = lift . atomicModifyRef r
116+
117+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DynamicWriterT t w m) where
118+ newEventWithTrigger = lift . newEventWithTrigger
119+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
120+
121+-- | Run a 'DynamicWriterT' action. The dynamic writer output will be provided
122+-- along with the result of the action.
123+runDynamicWriterT :: (MonadFix m, Reflex t, Monoid w) => DynamicWriterT t w m a -> m (a, Dynamic t w)
124+runDynamicWriterT (DynamicWriterT a) = do
125+ (result, ws) <- runStateT a []
126+ return (result, mconcat $ reverse ws)
127+
128+instance (Monad m, Monoid w, Reflex t) => DynamicWriter t w (DynamicWriterT t w m) where
129+ tellDyn w = DynamicWriterT $ modify (w :)
130+
131+instance MonadReader r m => MonadReader r (DynamicWriterT t w m) where
132+ ask = lift ask
133+ local f (DynamicWriterT a) = DynamicWriterT $ mapStateT (local f) a
134+ reader = lift . reader
135+
136+instance PerformEvent t m => PerformEvent t (DynamicWriterT t w m) where
137+ type Performable (DynamicWriterT t w m) = Performable m
138+ performEvent_ = lift . performEvent_
139+ performEvent = lift . performEvent
140+
141+instance TriggerEvent t m => TriggerEvent t (DynamicWriterT t w m) where
142+ newTriggerEvent = lift newTriggerEvent
143+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
144+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
145+
146+instance PostBuild t m => PostBuild t (DynamicWriterT t w m) where
147+ getPostBuild = lift getPostBuild
148+
149+instance MonadState s m => MonadState s (DynamicWriterT t w m) where
150+ get = lift get
151+ put = lift . put
152+
153+instance PrimMonad m => PrimMonad (DynamicWriterT t w m) where
154+ type PrimState (DynamicWriterT t w m) = PrimState m
155+ primitive = lift . primitive
156+
157+newtype DynamicWriterTLoweredResult t w v a = DynamicWriterTLoweredResult (v a, Dynamic t w)
158+
159+-- | When the execution of a 'DynamicWriterT' action is adjusted using
160+-- 'Adjustable', the 'Dynamic' output of that action will also be updated to
161+-- match.
162+instance (Adjustable t m, MonadFix m, Monoid w, MonadHold t m, Reflex t) => Adjustable t (DynamicWriterT t w m) where
163+ runWithReplace a0 a' = do
164+ (result0, result') <- lift $ runWithReplace (runDynamicWriterT a0) $ runDynamicWriterT <$> a'
165+ tellDyn . join =<< holdDyn (snd result0) (snd <$> result')
166+ return (fst result0, fst <$> result')
167+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust mergeIntMapDynIncremental
168+ traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap weakenPatchDMapWith mergeDynIncremental
169+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeDynIncrementalWithMove
170+
171+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)
172+ => ( (forall a. k a -> v a -> m (DynamicWriterTLoweredResult t w v' a))
173+ -> DMap k v
174+ -> Event t (p k v)
175+ -> m (DMap k (DynamicWriterTLoweredResult t w v'), Event t (p k (DynamicWriterTLoweredResult t w v')))
176+ )
177+ -> ((forall a. DynamicWriterTLoweredResult t w v' a -> v' a) -> p k (DynamicWriterTLoweredResult t w v') -> p k v')
178+ -> ((forall a. DynamicWriterTLoweredResult t w v' a -> Dynamic t w) -> p k (DynamicWriterTLoweredResult t w v') -> p' (Some k) (Dynamic t w))
179+ -> (Incremental t (p' (Some k) (Dynamic t w)) -> Incremental t (p' (Some k) w))
180+ -> (forall a. k a -> v a -> DynamicWriterT t w m (v' a))
181+ -> DMap k v
182+ -> Event t (p k v)
183+ -> DynamicWriterT t w m (DMap k v', Event t (p k v'))
184+traverseDMapWithKeyWithAdjustImpl base mapPatch weakenPatchWith mergeMyDynIncremental f (dm0 :: DMap k v) dm' = do
185+ (result0, result') <- lift $ base (\k v -> fmap DynamicWriterTLoweredResult $ runDynamicWriterT $ f k v) dm0 dm'
186+ let getValue (DynamicWriterTLoweredResult (v, _)) = v
187+ getWritten (DynamicWriterTLoweredResult (_, w)) = w
188+ liftedResult0 = DMap.map getValue result0
189+ liftedResult' = ffor result' $ mapPatch getValue
190+ liftedWritten0 :: Map (Some k) (Dynamic t w)
191+ liftedWritten0 = weakenDMapWith getWritten result0
192+ liftedWritten' = ffor result' $ weakenPatchWith getWritten
193+ --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
194+ i <- holdIncremental liftedWritten0 liftedWritten'
195+ tellDyn $ fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
196+ return (liftedResult0, liftedResult')
197+
198+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')
199+ => ( (IntMap.Key -> v -> m (v', Dynamic t w))
200+ -> IntMap v
201+ -> Event t (p v)
202+ -> m (IntMap (v', Dynamic t w), Event t (p (v', Dynamic t w)))
203+ )
204+ -> (Incremental t (p' (Dynamic t w)) -> Incremental t (p' w))
205+ -> (IntMap.Key -> v -> DynamicWriterT t w m v')
206+ -> IntMap v
207+ -> Event t (p v)
208+ -> DynamicWriterT t w m (IntMap v', Event t (p v'))
209+traverseIntMapWithKeyWithAdjustImpl base mergeMyDynIncremental f (dm0 :: IntMap v) dm' = do
210+ (result0, result') <- lift $ base (\k v -> runDynamicWriterT $ f k v) dm0 dm'
211+ let liftedResult0 = fmap fst result0
212+ liftedResult' = fmap (fmap fst) result'
213+ liftedWritten0 :: IntMap (Dynamic t w)
214+ liftedWritten0 = fmap snd result0
215+ liftedWritten' = fmap (fmap snd) result'
216+ --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics
217+ i <- holdIncremental liftedWritten0 liftedWritten'
218+ tellDyn $ fmap (mconcat . IntMap.elems) $ incrementalToDynamic $ mergeMyDynIncremental i
219+ return (liftedResult0, liftedResult')
220+
221+-- | Map a function over the output of a 'DynamicWriterT'.
222+withDynamicWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m, MonadFix m)
223+ => (w -> w')
224+ -> DynamicWriterT t w m a
225+ -> DynamicWriterT t w' m a
226+withDynamicWriterT f dw = do
227+ (r, d) <- lift $ do
228+ (r, d) <- runDynamicWriterT dw
229+ let d' = fmap f d
230+ return (r, d')
231+ tellDyn d
232+ return r
233+
234+instance Requester t m => Requester t (DynamicWriterT t w m) where
235+ type Request (DynamicWriterT t w m) = Request m
236+ type Response (DynamicWriterT t w m) = Response m
237+ requesting = lift . requesting
238+ requesting_ = lift . requesting_
239+
240+instance (MonadQuery t q m, Monad m) => MonadQuery t q (DynamicWriterT t w m) where
241+ tellQueryIncremental = lift . tellQueryIncremental
242+ askQueryResult = lift askQueryResult
243+ queryIncremental = lift . queryIncremental
244+
245+instance EventWriter t w m => EventWriter t w (DynamicWriterT t v m) where
246+ tellEvent = lift . tellEvent
src/Reflex/DynamicWriter/Class.hsnew file+28
@@ -0,0 +1,28 @@
1+-- | This module defines the 'DynamicWriter' class.
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE FunctionalDependencies #-}
6+{-# LANGUAGE UndecidableInstances #-}
7+#ifdef USE_REFLEX_OPTIMIZER
8+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
9+#endif
10+module Reflex.DynamicWriter.Class
11+ ( MonadDynamicWriter
12+ , DynamicWriter(..)
13+ ) where
14+
15+import Control.Monad.Reader (ReaderT, lift)
16+import Reflex.Class (Dynamic)
17+
18+{-# DEPRECATED MonadDynamicWriter "Use 'DynamicWriter' instead" #-}
19+-- | Type synonym for 'DynamicWriter'
20+type MonadDynamicWriter = DynamicWriter
21+
22+-- | 'MonadDynamicWriter' efficiently collects 'Dynamic' values using 'tellDyn'
23+-- and combines them monoidally to provide a 'Dynamic' result.
24+class (Monad m, Monoid w) => DynamicWriter t w m | m -> t w where
25+ tellDyn :: Dynamic t w -> m ()
26+
27+instance DynamicWriter t w m => DynamicWriter t w (ReaderT r m) where
28+ tellDyn = lift . tellDyn
src/Reflex/EventWriter.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+317
@@ -0,0 +1,317 @@
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.Morph
39+import Control.Monad.Primitive
40+import Control.Monad.Reader
41+import Control.Monad.Ref
42+import Control.Monad.State.Strict
43+import Data.Dependent.Map (DMap)
44+import qualified Data.Dependent.Map as DMap
45+import Data.Dependent.Sum (DSum (..))
46+import Data.Functor.Compose
47+import Data.Functor.Misc
48+import Data.GADT.Compare (GCompare (..), GEq (..), GOrdering (..))
49+import Data.IntMap.Strict (IntMap)
50+import qualified Data.IntMap.Strict as IntMap
51+import Data.List.NonEmpty (NonEmpty (..))
52+import Data.Map (Map)
53+import qualified Data.Map as Map
54+import Data.Semigroup
55+import Data.Some (Some)
56+import Data.Tuple
57+import Data.Type.Equality
58+
59+import Unsafe.Coerce
60+
61+{-# DEPRECATED TellId "Do not construct this directly; use tellId instead" #-}
62+newtype TellId w x
63+ = TellId Int -- ^ WARNING: Do not construct this directly; use 'tellId' instead
64+ deriving (Show, Eq, Ord, Enum)
65+
66+tellId :: Int -> TellId w w
67+tellId = TellId
68+{-# INLINE tellId #-}
69+
70+tellIdRefl :: TellId w x -> w :~: x
71+tellIdRefl _ = unsafeCoerce Refl
72+
73+withTellIdRefl :: TellId w x -> (w ~ x => r) -> r
74+withTellIdRefl tid r = case tellIdRefl tid of
75+ Refl -> r
76+
77+instance GEq (TellId w) where
78+ a `geq` b =
79+ withTellIdRefl a $
80+ withTellIdRefl b $
81+ if a == b
82+ then Just Refl
83+ else Nothing
84+
85+instance GCompare (TellId w) where
86+ a `gcompare` b =
87+ withTellIdRefl a $
88+ withTellIdRefl b $
89+ case a `compare` b of
90+ LT -> GLT
91+ EQ -> GEQ
92+ GT -> GGT
93+
94+data EventWriterState t w = EventWriterState
95+ { _eventWriterState_nextId :: {-# UNPACK #-} !Int -- Always negative (and decreasing over time)
96+ , _eventWriterState_told :: ![DSum (TellId w) (Event t)] -- In increasing order
97+ }
98+
99+-- | A basic implementation of 'EventWriter'.
100+newtype EventWriterT t w m a = EventWriterT { unEventWriterT :: StateT (EventWriterState t w) m a }
101+ deriving
102+ ( Functor
103+ , Applicative
104+ , Monad
105+ , MonadTrans
106+ , MFunctor
107+ , MonadFix
108+ , MonadIO
109+ , MonadException
110+ , MonadAsyncException
111+ )
112+
113+-- | Run a 'EventWriterT' action.
114+runEventWriterT :: forall t m w a. (Reflex t, Monad m, Semigroup w) => EventWriterT t w m a -> m (a, Event t w)
115+runEventWriterT (EventWriterT a) = do
116+ (result, requests) <- runStateT a $ EventWriterState (-1) []
117+ let combineResults :: DMap (TellId w) Identity -> w
118+ combineResults = sconcat
119+ . (\(h : t) -> h :| t) -- Unconditional; 'merge' guarantees that it will only fire with non-empty DMaps
120+ . 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
121+ 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
122+
123+instance (Reflex t, Monad m, Semigroup w) => EventWriter t w (EventWriterT t w m) where
124+ tellEvent w = EventWriterT $ modify $ \old ->
125+ let myId = _eventWriterState_nextId old
126+ in EventWriterState
127+ { _eventWriterState_nextId = pred myId
128+ , _eventWriterState_told = (tellId myId :=> w) : _eventWriterState_told old
129+ }
130+
131+instance MonadSample t m => MonadSample t (EventWriterT t w m) where
132+ sample = lift . sample
133+
134+instance MonadHold t m => MonadHold t (EventWriterT t w m) where
135+ {-# INLINABLE hold #-}
136+ hold v0 = lift . hold v0
137+ {-# INLINABLE holdDyn #-}
138+ holdDyn v0 = lift . holdDyn v0
139+ {-# INLINABLE holdIncremental #-}
140+ holdIncremental v0 = lift . holdIncremental v0
141+ {-# INLINABLE buildDynamic #-}
142+ buildDynamic a0 = lift . buildDynamic a0
143+ {-# INLINABLE headE #-}
144+ headE = lift . headE
145+ {-# INLINABLE now #-}
146+ now = lift now
147+
148+instance (Reflex t, Adjustable t m, MonadHold t m, Semigroup w) => Adjustable t (EventWriterT t w m) where
149+ runWithReplace = runWithReplaceEventWriterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
150+ traverseIntMapWithKeyWithAdjust = sequenceIntMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') mergeIntIncremental coincidencePatchIntMap
151+ traverseDMapWithKeyWithAdjust = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith mergeMapIncremental coincidencePatchMap
152+ traverseDMapWithKeyWithAdjustWithMove = sequenceDMapWithAdjustEventWriterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeMapIncrementalWithMove coincidencePatchMapWithMove
153+
154+instance Requester t m => Requester t (EventWriterT t w m) where
155+ type Request (EventWriterT t w m) = Request m
156+ type Response (EventWriterT t w m) = Response m
157+ requesting = lift . requesting
158+ requesting_ = lift . requesting_
159+
160+-- | Given a function like 'runWithReplace' for the underlying monad, implement
161+-- 'runWithReplace' for 'EventWriterT'. This is necessary when the underlying
162+-- monad doesn't have a 'Adjustable' instance or to override the default
163+-- 'Adjustable' behavior.
164+runWithReplaceEventWriterTWith :: forall m t w a b. (Reflex t, MonadHold t m, Semigroup w)
165+ => (forall a' b'. m a' -> Event t (m b') -> EventWriterT t w m (a', Event t b'))
166+ -> EventWriterT t w m a
167+ -> Event t (EventWriterT t w m b)
168+ -> EventWriterT t w m (a, Event t b)
169+runWithReplaceEventWriterTWith f a0 a' = do
170+ (result0, result') <- f (runEventWriterT a0) $ fmapCheap runEventWriterT a'
171+ tellEvent =<< switchHoldPromptOnly (snd result0) (fmapCheap snd result')
172+ return (fst result0, fmapCheap fst result')
173+
174+-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceIntMapWithAdjust'.
175+sequenceIntMapWithAdjustEventWriterTWith
176+ :: forall t m p w v v'
177+ . ( Reflex t
178+ , MonadHold t m
179+ , Semigroup w
180+ , Functor p
181+ , Patch (p (Event t w))
182+ , PatchTarget (p (Event t w)) ~ IntMap (Event t w)
183+ , Patch (p w)
184+ , PatchTarget (p w) ~ IntMap w
185+ )
186+ => ( (IntMap.Key -> v -> m (Event t w, v'))
187+ -> IntMap v
188+ -> Event t (p v)
189+ -> EventWriterT t w m (IntMap (Event t w, v'), Event t (p (Event t w, v')))
190+ )
191+ -> (Incremental t (p (Event t w)) -> Event t (PatchTarget (p w)))
192+ -> (Event t (p (Event t w)) -> Event t (p w))
193+ -> (IntMap.Key -> v -> EventWriterT t w m v')
194+ -> IntMap v
195+ -> Event t (p v)
196+ -> EventWriterT t w m (IntMap v', Event t (p v'))
197+sequenceIntMapWithAdjustEventWriterTWith base mergePatchIncremental coincidencePatch f dm0 dm' = do
198+ let f' :: IntMap.Key -> v -> m (Event t w, v')
199+ f' k v = swap <$> runEventWriterT (f k v)
200+ (children0, children') <- base f' dm0 dm'
201+ let result0 = fmap snd children0
202+ result' = fmapCheap (fmap snd) children'
203+ requests0 :: IntMap (Event t w)
204+ requests0 = fmap fst children0
205+ requests' :: Event t (p (Event t w))
206+ requests' = fmapCheap (fmap fst) children'
207+ e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
208+ tellEvent $ fforMaybeCheap e $ \m ->
209+ case IntMap.elems m of
210+ [] -> Nothing
211+ h : t -> Just $ sconcat $ h :| t
212+ return (result0, result')
213+
214+-- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceDMapWithAdjust'.
215+sequenceDMapWithAdjustEventWriterTWith
216+ :: forall t m p p' w k v v'
217+ . ( Reflex t
218+ , MonadHold t m
219+ , Semigroup w
220+ , Patch (p' (Some k) (Event t w))
221+ , PatchTarget (p' (Some k) (Event t w)) ~ Map (Some k) (Event t w)
222+ , GCompare k
223+ , Patch (p' (Some k) w)
224+ , PatchTarget (p' (Some k) w) ~ Map (Some k) w
225+ )
226+ => ( (forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a))
227+ -> DMap k v
228+ -> Event t (p k v)
229+ -> EventWriterT t w m (DMap k (Compose ((,) (Event t w)) v'), Event t (p k (Compose ((,) (Event t w)) v')))
230+ )
231+ -> ((forall a. Compose ((,) (Event t w)) v' a -> v' a) -> p k (Compose ((,) (Event t w)) v') -> p k v')
232+ -> ((forall a. Compose ((,) (Event t w)) v' a -> Event t w) -> p k (Compose ((,) (Event t w)) v') -> p' (Some k) (Event t w))
233+ -> (Incremental t (p' (Some k) (Event t w)) -> Event t (PatchTarget (p' (Some k) w)))
234+ -> (Event t (p' (Some k) (Event t w)) -> Event t (p' (Some k) w))
235+ -> (forall a. k a -> v a -> EventWriterT t w m (v' a))
236+ -> DMap k v
237+ -> Event t (p k v)
238+ -> EventWriterT t w m (DMap k v', Event t (p k v'))
239+sequenceDMapWithAdjustEventWriterTWith base mapPatch weakenPatchWith mergePatchIncremental coincidencePatch f dm0 dm' = do
240+ let f' :: forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a)
241+ f' k v = Compose . swap <$> runEventWriterT (f k v)
242+ (children0, children') <- base f' dm0 dm'
243+ let result0 = DMap.map (snd . getCompose) children0
244+ result' = fforCheap children' $ mapPatch $ snd . getCompose
245+ requests0 :: Map (Some k) (Event t w)
246+ requests0 = weakenDMapWith (fst . getCompose) children0
247+ requests' :: Event t (p' (Some k) (Event t w))
248+ requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
249+ e <- switchHoldPromptOnlyIncremental mergePatchIncremental coincidencePatch requests0 requests'
250+ tellEvent $ fforMaybeCheap e $ \m ->
251+ case Map.elems m of
252+ [] -> Nothing
253+ h : t -> Just $ sconcat $ h :| t
254+ return (result0, result')
255+
256+instance PerformEvent t m => PerformEvent t (EventWriterT t w m) where
257+ type Performable (EventWriterT t w m) = Performable m
258+ performEvent_ = lift . performEvent_
259+ performEvent = lift . performEvent
260+
261+instance PostBuild t m => PostBuild t (EventWriterT t w m) where
262+ getPostBuild = lift getPostBuild
263+
264+instance TriggerEvent t m => TriggerEvent t (EventWriterT t w m) where
265+ newTriggerEvent = lift newTriggerEvent
266+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
267+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
268+
269+instance MonadReader r m => MonadReader r (EventWriterT t w m) where
270+ ask = lift ask
271+ local f (EventWriterT a) = EventWriterT $ mapStateT (local f) a
272+ reader = lift . reader
273+
274+instance MonadRef m => MonadRef (EventWriterT t w m) where
275+ type Ref (EventWriterT t w m) = Ref m
276+ newRef = lift . newRef
277+ readRef = lift . readRef
278+ writeRef r = lift . writeRef r
279+
280+instance MonadAtomicRef m => MonadAtomicRef (EventWriterT t w m) where
281+ atomicModifyRef r = lift . atomicModifyRef r
282+
283+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (EventWriterT t w m) where
284+ newEventWithTrigger = lift . newEventWithTrigger
285+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
286+
287+instance (MonadQuery t q m, Monad m) => MonadQuery t q (EventWriterT t w m) where
288+ tellQueryIncremental = lift . tellQueryIncremental
289+ askQueryResult = lift askQueryResult
290+ queryIncremental = lift . queryIncremental
291+
292+instance DynamicWriter t w m => DynamicWriter t w (EventWriterT t v m) where
293+ tellDyn = lift . tellDyn
294+
295+instance PrimMonad m => PrimMonad (EventWriterT t w m) where
296+ type PrimState (EventWriterT t w m) = PrimState m
297+ primitive = lift . primitive
298+
299+-- | Map a function over the output of a 'EventWriterT'.
300+withEventWriterT :: (Semigroup w, Semigroup w', Reflex t, MonadHold t m)
301+ => (w -> w')
302+ -> EventWriterT t w m a
303+ -> EventWriterT t w' m a
304+withEventWriterT f ew = do
305+ (r, e) <- lift $ do
306+ (r, e) <- runEventWriterT ew
307+ let e' = fmap f e
308+ return (r, e')
309+ tellEvent e
310+ return r
311+
312+-- | Change the monad underlying an EventWriterT
313+mapEventWriterT
314+ :: (forall x. m x -> n x)
315+ -> EventWriterT t w m a
316+ -> EventWriterT t w n a
317+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+210
@@ -0,0 +1,210 @@
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+--
155+-- This function is marked NOINLINE so it is opaque to GHC.
156+-- If we do not do this, then GHC will sometimes fuse the constructor away
157+-- so any weak references that are attached to the ticket will have their
158+-- finalizer run. Using the opaque constructor, GHC does not see the
159+-- constructor application, so it behaves like an IORef and cannot be fused away.
160+--
161+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
162+-- the weak pointer to it in some cases.
163+{-# NOINLINE mkFastWeakTicket #-}
164+mkFastWeakTicket :: a -> IO (FastWeakTicket a)
165+-- 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
166+-- associated FastWeak to actually be weak
167+#ifdef GHCJS_FAST_WEAK
168+mkFastWeakTicket v = js_fastWeakTicket (unsafeToRawJSVal v)
169+
170+foreign import javascript unsafe "$r = new h$FastWeakTicket($1);" js_fastWeakTicket :: JSVal -> IO (FastWeakTicket a)
171+#else
172+mkFastWeakTicket v = do
173+ v' <- evaluate v
174+ w <- mkWeakPtr v' Nothing
175+ return $ FastWeakTicket
176+ { _fastWeakTicket_val = v'
177+ , _fastWeakTicket_weak = w
178+ }
179+#endif
180+
181+-- | Demote a 'FastWeakTicket'; which ensures the value is alive, to a 'FastWeak' which doesn't.
182+-- Note that unless the ticket for the same 'FastWeak' is held in some other way
183+-- the value might be collected immediately.
184+getFastWeakTicketWeak :: FastWeakTicket a -> IO (FastWeak a)
185+-- Needs IO so that it can force the value - otherwise, could end up with a reference to the Ticket, which would retain the value
186+#ifdef GHCJS_FAST_WEAK
187+foreign import javascript unsafe "$r = $1.weak;" getFastWeakTicketWeak' :: FastWeakTicket a -> IO (FastWeak a)
188+{-# INLINE getFastWeakTicketWeak #-}
189+getFastWeakTicketWeak = getFastWeakTicketWeak'
190+#else
191+getFastWeakTicketWeak = return . _fastWeakTicket_weak
192+#endif
193+
194+-- | A weak reference that is always empty
195+emptyFastWeak :: FastWeak a
196+emptyFastWeak = unsafeCoerce w
197+ where w :: FastWeak Any
198+#ifdef GHCJS_FAST_WEAK
199+ w = js_emptyWeak
200+#else
201+ w = unsafePerformIO $ do
202+ w' <- mkWeakPtr undefined Nothing
203+ finalize w'
204+ return w'
205+#endif
206+{-# NOINLINE emptyFastWeak #-}
207+
208+#ifdef GHCJS_FAST_WEAK
209+foreign import javascript unsafe "$r = new h$FastWeak(null);" js_emptyWeak :: FastWeak Any
210+#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.hs+247−24
@@ -1,38 +1,161 @@
1−{-# LANGUAGE ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, FunctionalDependencies #-}
2−module Reflex.Host.Class where
3−
4−import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl)
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
529
630import Reflex.Class
731
8−import Control.Monad.Identity hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
9−import Control.Monad.State.Strict hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
10−import Control.Monad.Reader hiding (mapM, mapM_, forM, forM_, sequence, sequence_)
11−import Data.Dependent.Sum (DSum)
32+import Control.Monad.Fix
33+import Control.Monad.Identity
1234import 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
1345
14−class Reflex t => ReflexHost t where
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
1555 type EventTrigger t :: * -> *
1656 type EventHandle t :: * -> *
1757 type HostFrame t :: * -> *
1858
19−class (ReflexHost t, Monad m) => MonadReadEvent t m | m -> t where
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'.
2089 readEvent :: EventHandle t a -> m (Maybe (m a))
2190
22−class (Monad m, ReflexHost t) => MonadReflexCreateTrigger t m | m -> t where
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.
23106 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
24133
25−class (Monad m, ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexHost t m | m -> t where
26− fireEventsAndRead :: [DSum (EventTrigger t)] -> (forall m'. (MonadReadEvent t m') => m' a) -> m a
27− subscribeEvent :: Event t a -> m (EventHandle t a) --TODO: Return a handle, and use them in fireEventsAnRead
28− runFrame :: PushM t a -> m a
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.
29143 runHostFrame :: HostFrame t a -> m a
30144
31−fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t)] -> m ()
32−{-# INLINE fireEvents #-}
145+-- | Like 'fireEventsAndRead', but without reading any events.
146+fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t) Identity] -> m ()
33147fireEvents dm = fireEventsAndRead dm $ return ()
148+{-# INLINE fireEvents #-}
34149
35−{-# INLINE newEventWithTriggerRef #-}
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.
36159newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
37160newEventWithTriggerRef = do
38161 rt <- newRef Nothing
@@ -40,17 +163,117 @@ newEventWithTriggerRef = do
40163 writeRef rt $ Just t
41164 return $ writeRef rt Nothing
42165 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+
43189
44190--------------------------------------------------------------------------------
45191-- Instances
46192--------------------------------------------------------------------------------
47193
48−instance (Reflex t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (ReaderT r m) where
49− newEventWithTrigger initializer = do
50− r <- ask
51− lift $ newEventWithTrigger initializer
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
52248
53−instance (Reflex t, MonadReflexHost t m) => MonadReflexHost t (ReaderT r m) where
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
54254 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
55262 subscribeEvent = lift . subscribeEvent
56− runFrame = lift . runFrame
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/Host/Headless.hsnew file+128
@@ -0,0 +1,128 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE RankNTypes #-}
4+{-# LANGUAGE TypeFamilies #-}
5+{-# LANGUAGE ConstraintKinds #-}
6+
7+module Reflex.Host.Headless where
8+
9+import Control.Concurrent.Chan (newChan, readChan)
10+import Control.Monad (unless)
11+import Control.Monad.Fix (MonadFix, fix)
12+import Control.Monad.IO.Class (MonadIO, liftIO)
13+import Control.Monad.Primitive (PrimMonad)
14+import Control.Monad.Ref (MonadRef, Ref, readRef)
15+import Data.Dependent.Sum (DSum (..), (==>))
16+import Data.Foldable (for_)
17+import Data.Functor.Identity (Identity(..))
18+import Data.IORef (IORef, readIORef)
19+import Data.Maybe (catMaybes, fromMaybe)
20+import Data.Traversable (for)
21+
22+import Reflex
23+import Reflex.Host.Class
24+
25+type MonadHeadlessApp t m =
26+ ( Adjustable t m
27+ , MonadFix m
28+ , MonadHold t m
29+ , MonadIO (HostFrame t)
30+ , MonadIO (Performable m)
31+ , MonadIO m
32+ , MonadRef (HostFrame t)
33+ , NotReady t m
34+ , PerformEvent t m
35+ , PostBuild t m
36+ , PrimMonad (HostFrame t)
37+ , Ref (HostFrame t) ~ IORef
38+ , Ref m ~ IORef
39+ , Reflex t
40+ , ReflexHost t
41+ , TriggerEvent t m
42+ )
43+
44+-- | Run a headless FRP network. Inside the action, you will most probably use
45+-- the capabilities provided by the 'TriggerEvent' and 'PerformEvent' type
46+-- classes to interface the FRP network with the outside world. Useful for
47+-- testing. Each headless network runs on its own spider timeline.
48+runHeadlessApp
49+ :: (forall t m. MonadHeadlessApp t m => m (Event t ()))
50+ -- ^ The action to be run in the headless FRP network. The FRP network is
51+ -- closed at the first occurrence of the resulting 'Event'.
52+ -> IO ()
53+runHeadlessApp guest =
54+ -- We are using the 'Spider' implementation of reflex. Running the host
55+ -- allows us to take actions on the FRP timeline.
56+ withSpiderTimeline $ runSpiderHostForTimeline $ do
57+ -- Create the "post-build" event and associated trigger. This event fires
58+ -- once, when the application starts.
59+ (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
60+ -- Create a queue to which we will write 'Event's that need to be
61+ -- processed.
62+ events <- liftIO newChan
63+ -- Run the "guest" application, providing the appropriate context. We'll
64+ -- pure the result of the action, and a 'FireCommand' that will be used to
65+ -- trigger events.
66+ (result, fc@(FireCommand fire)) <- do
67+ hostPerformEventT $ -- Allows the guest app to run
68+ -- 'performEvent', so that actions
69+ -- (e.g., IO actions) can be run when
70+ -- 'Event's fire.
71+
72+ flip runPostBuildT postBuild $ -- Allows the guest app to access to
73+ -- a "post-build" 'Event'
74+
75+ flip runTriggerEventT events $ -- Allows the guest app to create new
76+ -- events and triggers and write
77+ -- those triggers to a channel from
78+ -- which they will be read and
79+ -- processed.
80+ guest
81+
82+ -- Read the trigger reference for the post-build event. This will be
83+ -- 'Nothing' if the guest application hasn't subscribed to this event.
84+ mPostBuildTrigger <- readRef postBuildTriggerRef
85+
86+ -- Subscribe to an 'Event' of that the guest application can use to
87+ -- request application shutdown. We'll check whether this 'Event' is firing
88+ -- to determine whether to terminate.
89+ shutdown <- subscribeEvent result
90+
91+ -- When there is a subscriber to the post-build event, fire the event.
92+ soa <- for mPostBuildTrigger $ \postBuildTrigger ->
93+ fire [postBuildTrigger :=> Identity ()] $ isFiring shutdown
94+
95+ -- The main application loop. We wait for new events and fire those that
96+ -- have subscribers. If we detect a shutdown request, the application
97+ -- terminates.
98+ unless (or (fromMaybe [] soa)) $ fix $ \loop -> do
99+ -- Read the next event (blocking).
100+ ers <- liftIO $ readChan events
101+ stop <- do
102+ -- Fire events that have subscribers.
103+ fireEventTriggerRefs fc ers $
104+ -- Check if the shutdown 'Event' is firing.
105+ isFiring shutdown
106+ if or stop
107+ then pure ()
108+ else loop
109+ where
110+ isFiring ev = readEvent ev >>= \case
111+ Nothing -> pure False
112+ Just _ -> pure True
113+ -- Use the given 'FireCommand' to fire events that have subscribers
114+ -- and call the callback for the 'TriggerInvocation' of each.
115+ fireEventTriggerRefs
116+ :: MonadIO m
117+ => FireCommand t m
118+ -> [DSum (EventTriggerRef t) TriggerInvocation]
119+ -> ReadPhase m a
120+ -> m [a]
121+ fireEventTriggerRefs (FireCommand fire) ers rcb = do
122+ mes <- liftIO $
123+ for ers $ \(EventTriggerRef er :=> TriggerInvocation a _) -> do
124+ me <- readIORef er
125+ pure $ fmap (==> a) me
126+ a <- fire (catMaybes mes) rcb
127+ liftIO $ for_ ers $ \(_ :=> TriggerInvocation _ cb) -> cb
128+ pure a
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 at post-build time and when the 'Dynamic' updates.
24+-- Note: Often, the type 'a' is an Event, in which case the return value is an Event-of-Events, where the outer 'Event' fires
25+-- when switching networks. Such an 'Event' would typically be flattened (via 'switchPromptly').
26+networkView :: (NotReady t m, Adjustable t m, PostBuild t m) => Dynamic t (m a) -> m (Event t a)
27+networkView child = do
28+ postBuild <- getPostBuild
29+ let newChild = leftmost [updated child, tagCheap (current child) postBuild]
30+ snd <$> runWithReplace notReady newChild
31+
32+-- | Given an initial "network" and an 'Event' of network-creating actions, create a network that is recreated whenever the Event fires.
33+-- The returned Dynamic of network results occurs when the Event does.
34+-- Note: Often, the type 'a' is an Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
35+networkHold :: (Adjustable t m, MonadHold t m) => m a -> Event t (m a) -> m (Dynamic t a)
36+networkHold child0 newChild = do
37+ (result0, newResult) <- runWithReplace child0 newChild
38+ holdDyn result0 newResult
39+
40+-- | Render a placeholder network to be shown while another network is not yet
41+-- done building
42+untilReady :: (Adjustable t m, PostBuild t m) => m a -> m b -> m (a, Event t b)
43+untilReady a b = do
44+ postBuild <- getPostBuild
45+ runWithReplace a $ b <$ postBuild
src/Reflex/NotReady/Class.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/PerformEvent/Base.hsnew file+181
@@ -0,0 +1,181 @@
1+-- | This module provides 'PerformEventT', the standard implementation of
2+-- 'PerformEvent'.
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE ExistentialQuantification #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GADTs #-}
8+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE PartialTypeSignatures #-}
11+{-# LANGUAGE PolyKinds #-}
12+{-# LANGUAGE RankNTypes #-}
13+{-# LANGUAGE ScopedTypeVariables #-}
14+{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE TypeFamilies #-}
16+{-# LANGUAGE TypeOperators #-}
17+{-# LANGUAGE UndecidableInstances #-}
18+#ifdef USE_REFLEX_OPTIMIZER
19+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
20+#endif
21+module Reflex.PerformEvent.Base
22+ ( PerformEventT (..)
23+ , FireCommand (..)
24+ , hostPerformEventT
25+ ) where
26+
27+import Reflex.Class
28+import Reflex.Adjustable.Class
29+import Reflex.Host.Class
30+import Reflex.PerformEvent.Class
31+import Reflex.Requester.Base
32+import Reflex.Requester.Class
33+
34+import Control.Lens
35+import Control.Monad.Exception
36+import Control.Monad.Identity
37+import Control.Monad.Primitive
38+import Control.Monad.Reader
39+import Control.Monad.Ref
40+import Data.Coerce
41+import Data.Dependent.Map (DMap)
42+import qualified Data.Dependent.Map as DMap
43+import Data.Dependent.Sum
44+import Data.IntMap.Strict (IntMap)
45+import qualified Data.IntMap.Strict as IntMap
46+import qualified Data.Semigroup as S
47+
48+-- | A function that fires events for the given 'EventTrigger's and then runs
49+-- any followup actions provided via 'PerformEvent'. The given 'ReadPhase'
50+-- action will be run once for the initial trigger execution as well as once for
51+-- each followup.
52+newtype FireCommand t m = FireCommand { runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a] } --TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?
53+
54+-- | Provides a basic implementation of 'PerformEvent'. Note that, despite the
55+-- name, 'PerformEventT' is not an instance of 'MonadTrans'.
56+newtype PerformEventT t m a = PerformEventT { unPerformEventT :: RequesterT t (HostFrame t) Identity (HostFrame t) a }
57+
58+deriving instance ReflexHost t => Functor (PerformEventT t m)
59+deriving instance ReflexHost t => Applicative (PerformEventT t m)
60+deriving instance ReflexHost t => Monad (PerformEventT t m)
61+deriving instance ReflexHost t => MonadFix (PerformEventT t m)
62+deriving instance (ReflexHost t, MonadIO (HostFrame t)) => MonadIO (PerformEventT t m)
63+deriving instance (ReflexHost t, MonadException (HostFrame t)) => MonadException (PerformEventT t m)
64+deriving instance (ReflexHost t, Monoid a) => Monoid (PerformEventT t m a)
65+deriving instance (ReflexHost t, S.Semigroup a) => S.Semigroup (PerformEventT t m a)
66+
67+instance (PrimMonad (HostFrame t), ReflexHost t) => PrimMonad (PerformEventT t m) where
68+ type PrimState (PerformEventT t m) = PrimState (HostFrame t)
69+ primitive = PerformEventT . lift . primitive
70+
71+instance (ReflexHost t, Ref m ~ Ref IO) => PerformEvent t (PerformEventT t m) where
72+ type Performable (PerformEventT t m) = HostFrame t
73+ {-# INLINABLE performEvent_ #-}
74+ performEvent_ = PerformEventT . requesting_
75+ {-# INLINABLE performEvent #-}
76+ performEvent = PerformEventT . requestingIdentity
77+
78+instance (ReflexHost t, PrimMonad (HostFrame t)) => Adjustable t (PerformEventT t m) where
79+ runWithReplace outerA0 outerA' = PerformEventT $ runWithReplaceRequesterTWith f (coerce outerA0) (coerceEvent outerA')
80+ where f :: HostFrame t a -> Event t (HostFrame t b) -> RequesterT t (HostFrame t) Identity (HostFrame t) (a, Event t b)
81+ f a0 a' = do
82+ result0 <- lift a0
83+ result' <- requestingIdentity a'
84+ return (result0, result')
85+ traverseIntMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseIntMapWithKeyWithAdjustRequesterTWith (defaultAdjustIntBase traverseIntMapPatchWithKey) patchIntMapNewElementsMap mergeIntIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
86+ traverseDMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithKey) mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
87+ traverseDMapWithKeyWithAdjustWithMove f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithMoveWithKey) mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')
88+
89+defaultAdjustBase :: forall t v v2 k' p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
90+ => ((forall a. k' a -> v a -> HostFrame t (v2 a)) -> p k' v -> HostFrame t (p k' v2))
91+ -> (forall a. k' a -> v a -> HostFrame t (v2 a))
92+ -> DMap k' v
93+ -> Event t (p k' v)
94+ -> RequesterT t (HostFrame t) Identity (HostFrame t) (DMap k' v2, Event t (p k' v2))
95+defaultAdjustBase traversePatchWithKey f' dm0 dm' = do
96+ result0 <- lift $ DMap.traverseWithKey f' dm0
97+ result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
98+ return (result0, result')
99+
100+defaultAdjustIntBase :: forall t v v2 p. (Monad (HostFrame t), PrimMonad (HostFrame t), Reflex t)
101+ => ((IntMap.Key -> v -> HostFrame t v2) -> p v -> HostFrame t (p v2))
102+ -> (IntMap.Key -> v -> HostFrame t v2)
103+ -> IntMap v
104+ -> Event t (p v)
105+ -> RequesterT t (HostFrame t) Identity (HostFrame t) (IntMap v2, Event t (p v2))
106+defaultAdjustIntBase traversePatchWithKey f' dm0 dm' = do
107+ result0 <- lift $ IntMap.traverseWithKey f' dm0
108+ result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'
109+ return (result0, result')
110+
111+instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where
112+ {-# INLINABLE newEventWithTrigger #-}
113+ newEventWithTrigger = PerformEventT . lift . newEventWithTrigger
114+ {-# INLINABLE newFanEventWithTrigger #-}
115+ newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f
116+
117+-- | Run a 'PerformEventT' action, returning a 'FireCommand' that allows the
118+-- caller to trigger 'Event's while ensuring that 'performEvent' actions are run
119+-- at the appropriate time.
120+{-# INLINABLE hostPerformEventT #-}
121+hostPerformEventT :: forall t m a.
122+ ( Monad m
123+ , MonadSubscribeEvent t m
124+ , MonadReflexHost t m
125+ , MonadRef m
126+ , Ref m ~ Ref IO
127+ )
128+ => PerformEventT t m a
129+ -> m (a, FireCommand t m)
130+hostPerformEventT a = do
131+ (response, responseTrigger) <- newEventWithTriggerRef
132+ (result, eventToPerform) <- runHostFrame $ runRequesterT (unPerformEventT a) response
133+ eventToPerformHandle <- subscribeEvent eventToPerform
134+ return $ (,) result $ FireCommand $ \triggers (readPhase :: ReadPhase m a') -> do
135+ let go :: [DSum (EventTrigger t) Identity] -> m [a']
136+ go ts = do
137+ (result', mToPerform) <- fireEventsAndRead ts $ do
138+ mToPerform <- sequence =<< readEvent eventToPerformHandle
139+ result' <- readPhase
140+ return (result', mToPerform)
141+ case mToPerform of
142+ Nothing -> return [result']
143+ Just toPerform -> do
144+ responses <- runHostFrame $ traverseRequesterData (fmap Identity) toPerform
145+ mrt <- readRef responseTrigger
146+ let followupEventTriggers = case mrt of
147+ Just rt -> [rt :=> Identity responses]
148+ Nothing -> []
149+ (result':) <$> go followupEventTriggers
150+ go triggers
151+
152+instance ReflexHost t => MonadSample t (PerformEventT t m) where
153+ {-# INLINABLE sample #-}
154+ sample = PerformEventT . lift . sample
155+
156+instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where
157+ {-# INLINABLE hold #-}
158+ hold v0 v' = PerformEventT $ lift $ hold v0 v'
159+ {-# INLINABLE holdDyn #-}
160+ holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'
161+ {-# INLINABLE holdIncremental #-}
162+ holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'
163+ {-# INLINABLE buildDynamic #-}
164+ buildDynamic getV0 v' = PerformEventT $ lift $ buildDynamic getV0 v'
165+ {-# INLINABLE headE #-}
166+ headE = PerformEventT . lift . headE
167+ {-# INLINABLE now #-}
168+ now = PerformEventT . lift $ now
169+
170+instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where
171+ type Ref (PerformEventT t m) = Ref (HostFrame t)
172+ {-# INLINABLE newRef #-}
173+ newRef = PerformEventT . lift . newRef
174+ {-# INLINABLE readRef #-}
175+ readRef = PerformEventT . lift . readRef
176+ {-# INLINABLE writeRef #-}
177+ writeRef r = PerformEventT . lift . writeRef r
178+
179+instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where
180+ {-# INLINABLE atomicModifyRef #-}
181+ atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
src/Reflex/PerformEvent/Class.hsnew file+68
@@ -0,0 +1,68 @@
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 UndecidableInstances #-}
12+#ifdef USE_REFLEX_OPTIMIZER
13+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
14+#endif
15+module Reflex.PerformEvent.Class
16+ ( PerformEvent (..)
17+ , performEventAsync
18+ ) where
19+
20+import Reflex.Class
21+import Reflex.TriggerEvent.Class
22+
23+import Control.Monad.Reader
24+import Control.Monad.Trans.Maybe (MaybeT (..))
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
64+
65+instance PerformEvent t m => PerformEvent t (MaybeT m) where
66+ type Performable (MaybeT m) = MaybeT (Performable m)
67+ performEvent_ = lift . performEvent_ . fmapCheap (void . runMaybeT)
68+ performEvent = lift . fmap (fmapMaybe id) . performEvent . fmapCheap runMaybeT
src/Reflex/PostBuild/Base.hsnew file+198
@@ -0,0 +1,198 @@
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 UndecidableInstances #-}
13+#ifdef USE_REFLEX_OPTIMIZER
14+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
15+#endif
16+module Reflex.PostBuild.Base
17+ ( PostBuildT (..)
18+ , runPostBuildT
19+ -- * Internal
20+ , mapIntMapWithAdjustImpl
21+ , mapDMapWithAdjustImpl
22+ ) where
23+
24+import Reflex.Class
25+import Reflex.Adjustable.Class
26+import Reflex.Host.Class
27+import Reflex.PerformEvent.Class
28+import Reflex.PostBuild.Class
29+import Reflex.TriggerEvent.Class
30+
31+import Control.Applicative (liftA2)
32+import Control.Monad.Exception
33+import Control.Monad.Identity
34+import Control.Monad.Primitive
35+import Control.Monad.Reader
36+import Control.Monad.Ref
37+import qualified Control.Monad.Trans.Control as TransControl
38+import Data.Dependent.Map (DMap)
39+import qualified Data.Dependent.Map as DMap
40+import Data.Functor.Compose
41+import Data.IntMap.Strict (IntMap)
42+import qualified Data.IntMap.Strict as IntMap
43+import qualified Data.Semigroup as S
44+
45+-- | Provides a basic implementation of 'PostBuild'.
46+newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException)
47+
48+-- | Run a 'PostBuildT' action. An 'Event' should be provided that fires
49+-- immediately after the action is finished running; no other 'Event's should
50+-- fire first.
51+{-# INLINABLE runPostBuildT #-}
52+runPostBuildT :: PostBuildT t m a -> Event t () -> m a
53+runPostBuildT (PostBuildT a) = runReaderT a
54+
55+-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
56+instance (Monoid a, Applicative m) => Monoid (PostBuildT t m a) where
57+ mempty = pure mempty
58+ mappend = liftA2 mappend
59+
60+instance (S.Semigroup a, Applicative m) => S.Semigroup (PostBuildT t m a) where
61+ (<>) = liftA2 (S.<>)
62+
63+instance PrimMonad m => PrimMonad (PostBuildT x m) where
64+ type PrimState (PostBuildT x m) = PrimState m
65+ primitive = lift . primitive
66+
67+instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where
68+ {-# INLINABLE getPostBuild #-}
69+ getPostBuild = PostBuildT ask
70+
71+instance MonadSample t m => MonadSample t (PostBuildT t m) where
72+ {-# INLINABLE sample #-}
73+ sample = lift . sample
74+
75+instance MonadHold t m => MonadHold t (PostBuildT t m) where
76+ {-# INLINABLE hold #-}
77+ hold v0 = lift . hold v0
78+ {-# INLINABLE holdDyn #-}
79+ holdDyn v0 = lift . holdDyn v0
80+ {-# INLINABLE holdIncremental #-}
81+ holdIncremental v0 = lift . holdIncremental v0
82+ {-# INLINABLE buildDynamic #-}
83+ buildDynamic a0 = lift . buildDynamic a0
84+ {-# INLINABLE headE #-}
85+ headE = lift . headE
86+ {-# INLINABLE now #-}
87+ now = lift now
88+
89+instance PerformEvent t m => PerformEvent t (PostBuildT t m) where
90+ type Performable (PostBuildT t m) = Performable m
91+ {-# INLINABLE performEvent_ #-}
92+ performEvent_ = lift . performEvent_
93+ {-# INLINABLE performEvent #-}
94+ performEvent = lift . performEvent
95+
96+instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where
97+ {-# INLINABLE newEventWithTrigger #-}
98+ newEventWithTrigger = PostBuildT . lift . newEventWithTrigger
99+ {-# INLINABLE newFanEventWithTrigger #-}
100+ newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f
101+
102+instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where
103+ {-# INLINABLE newTriggerEvent #-}
104+ newTriggerEvent = lift newTriggerEvent
105+ {-# INLINABLE newTriggerEventWithOnComplete #-}
106+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
107+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
108+
109+instance MonadRef m => MonadRef (PostBuildT t m) where
110+ type Ref (PostBuildT t m) = Ref m
111+ {-# INLINABLE newRef #-}
112+ newRef = lift . newRef
113+ {-# INLINABLE readRef #-}
114+ readRef = lift . readRef
115+ {-# INLINABLE writeRef #-}
116+ writeRef r = lift . writeRef r
117+
118+instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where
119+ {-# INLINABLE atomicModifyRef #-}
120+ atomicModifyRef r = lift . atomicModifyRef r
121+
122+instance (Reflex t, MonadHold t m, MonadFix m, Adjustable t m, PerformEvent t m) => Adjustable t (PostBuildT t m) where
123+ runWithReplace a0 a' = do
124+ postBuild <- getPostBuild
125+ lift $ do
126+ rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a'
127+ let voidResult' = fmapCheap (\_ -> ()) result'
128+ return result
129+ {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
130+ traverseIntMapWithKeyWithAdjust = mapIntMapWithAdjustImpl traverseIntMapWithKeyWithAdjust
131+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
132+ traverseDMapWithKeyWithAdjust = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap
133+ traverseDMapWithKeyWithAdjustWithMove = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove
134+
135+{-# INLINABLE mapIntMapWithAdjustImpl #-}
136+mapIntMapWithAdjustImpl :: forall t m v v' p. (Reflex t, MonadFix m, MonadHold t m, Functor p)
137+ => ( (IntMap.Key -> (Event t (), v) -> m v')
138+ -> IntMap (Event t (), v)
139+ -> Event t (p (Event t (), v))
140+ -> m (IntMap v', Event t (p v'))
141+ )
142+ -> (IntMap.Key -> v -> PostBuildT t m v')
143+ -> IntMap v
144+ -> Event t (p v)
145+ -> PostBuildT t m (IntMap v', Event t (p v'))
146+mapIntMapWithAdjustImpl base f dm0 dm' = do
147+ postBuild <- getPostBuild
148+ let loweredDm0 = fmap ((,) postBuild) dm0
149+ f' :: IntMap.Key -> (Event t (), v) -> m v'
150+ f' k (e, v) = do
151+ runPostBuildT (f k v) e
152+ lift $ do
153+ rec (result0, result') <- base f' loweredDm0 loweredDm'
154+ cohortDone <- numberOccurrencesFrom_ 1 result'
155+ numberedDm' <- numberOccurrencesFrom 1 dm'
156+ let postBuild' = fanInt $ fmapCheap (`IntMap.singleton` ()) cohortDone
157+ loweredDm' = flip pushAlways numberedDm' $ \(n, p) -> do
158+ return $ fmap ((,) (selectInt postBuild' n)) p
159+ return (result0, result')
160+
161+{-# INLINABLE mapDMapWithAdjustImpl #-}
162+mapDMapWithAdjustImpl :: forall t m k v v' p. (Reflex t, MonadFix m, MonadHold t m)
163+ => ( (forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a))
164+ -> DMap k (Compose ((,) (Bool, Event t ())) v)
165+ -> Event t (p k (Compose ((,) (Bool, Event t ())) v))
166+ -> m (DMap k v', Event t (p k v'))
167+ )
168+ -> ((forall a. v a -> Compose ((,) (Bool, Event t ())) v a) -> p k v -> p k (Compose ((,) (Bool, Event t ())) v))
169+ -> (forall a. k a -> v a -> PostBuildT t m (v' a))
170+ -> DMap k v
171+ -> Event t (p k v)
172+ -> PostBuildT t m (DMap k v', Event t (p k v'))
173+mapDMapWithAdjustImpl base mapPatch f dm0 dm' = do
174+ postBuild <- getPostBuild
175+ let loweredDm0 = DMap.map (Compose . (,) (False, postBuild)) dm0
176+ f' :: forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a)
177+ f' k (Compose ((shouldHeadE, e), v)) = do
178+ eOnce <- if shouldHeadE
179+ 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
180+ else return e
181+ runPostBuildT (f k v) eOnce
182+ lift $ do
183+ rec (result0, result') <- base f' loweredDm0 loweredDm'
184+ let voidResult' = fmapCheap (\_ -> ()) result'
185+ let loweredDm' = ffor dm' $ mapPatch (Compose . (,) (True, voidResult'))
186+ return (result0, result')
187+
188+--------------------------------------------------------------------------------
189+-- Deprecated functionality
190+--------------------------------------------------------------------------------
191+
192+-- | Deprecated
193+instance TransControl.MonadTransControl (PostBuildT t) where
194+ type StT (PostBuildT t) a = TransControl.StT (ReaderT (Event t ())) a
195+ {-# INLINABLE liftWith #-}
196+ liftWith = TransControl.defaultLiftWith PostBuildT unPostBuildT
197+ {-# INLINABLE restoreT #-}
198+ restoreT = TransControl.defaultRestoreT PostBuildT
src/Reflex/PostBuild/Class.hsnew file+40
@@ -0,0 +1,40 @@
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 UndecidableInstances #-}
10+#ifdef USE_REFLEX_OPTIMIZER
11+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
12+#endif
13+module Reflex.PostBuild.Class
14+ ( PostBuild (..)
15+ ) where
16+
17+import Reflex.Class
18+
19+import Control.Monad.Reader
20+import Control.Monad.State
21+import qualified Control.Monad.State.Strict as Strict
22+
23+-- | 'PostBuild' represents an action that is notified via an 'Event' when it
24+-- has finished executing. Note that the specific definition of "finished" is
25+-- determined by the instance of 'PostBuild', but the intent is to allow
26+-- 'Behavior's and 'Dynamic's to be safely sampled, regardless of where they
27+-- were created, when the post-build 'Event' fires. The post-build 'Event' will
28+-- fire exactly once for an given action.
29+class (Reflex t, Monad m) => PostBuild t m | m -> t where
30+ -- | Retrieve the post-build 'Event' for this action.
31+ getPostBuild :: m (Event t ())
32+
33+instance PostBuild t m => PostBuild t (ReaderT r m) where
34+ getPostBuild = lift getPostBuild
35+
36+instance PostBuild t m => PostBuild t (StateT s m) where
37+ getPostBuild = lift getPostBuild
38+
39+instance PostBuild t m => PostBuild t (Strict.StateT s m) where
40+ getPostBuild = lift getPostBuild
src/Reflex/Profiled.hsnew file+281
@@ -0,0 +1,281 @@
1+{-# LANGUAGE EmptyDataDecls #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE InstanceSigs #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE StandaloneDeriving #-}
9+{-# LANGUAGE TypeFamilies #-}
10+{-# LANGUAGE UndecidableInstances #-}
11+{-# LANGUAGE PolyKinds #-}
12+{-# LANGUAGE TypeApplications #-}
13+{-# LANGUAGE RankNTypes #-}
14+-- |
15+-- Module:
16+-- Reflex.Profiled
17+-- Description:
18+-- This module contains an instance of the 'Reflex' class that provides
19+-- profiling/cost-center information.
20+module Reflex.Profiled where
21+
22+import Control.Monad
23+import Control.Monad.Exception
24+import Control.Monad.Fix
25+import Control.Monad.Primitive
26+import Control.Monad.Reader
27+import Control.Monad.Ref
28+import Control.Monad.State.Strict (StateT, execStateT, modify)
29+import Data.Bifunctor
30+import Data.Coerce
31+import Data.Dependent.Map (DMap)
32+import Data.GADT.Compare (GCompare)
33+import Data.FastMutableIntMap
34+import Data.IORef
35+import Data.List
36+import Data.Map (Map)
37+import qualified Data.Map.Strict as Map
38+import Data.Monoid ((<>))
39+import Data.Ord
40+import Data.Profunctor.Unsafe ((#.))
41+import qualified Data.Semigroup as S
42+import Data.Type.Coercion
43+import Foreign.Ptr
44+import GHC.Foreign
45+import GHC.IO.Encoding
46+import GHC.Stack
47+import Reflex.Adjustable.Class
48+import Reflex.BehaviorWriter.Class
49+import Reflex.Class
50+import Reflex.DynamicWriter.Class
51+import Reflex.EventWriter.Class
52+import Reflex.Host.Class
53+import Reflex.NotReady.Class
54+import Reflex.PerformEvent.Class
55+import Reflex.PostBuild.Class
56+import Reflex.Query.Class
57+import Reflex.Requester.Class
58+import Reflex.TriggerEvent.Class
59+
60+import System.IO.Unsafe
61+
62+data ProfiledTimeline t
63+
64+{-# NOINLINE profilingData #-}
65+profilingData :: IORef (Map (Ptr CostCentreStack) Int)
66+profilingData = unsafePerformIO $ newIORef Map.empty
67+
68+data CostCentreTree = CostCentreTree
69+ { _costCentreTree_ownEntries :: !Int
70+ , _costCentreTree_cumulativeEntries :: !Int
71+ , _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
72+ }
73+ deriving (Show, Eq, Ord)
74+
75+instance S.Semigroup CostCentreTree where
76+ (CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
77+ CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
78+
79+instance Monoid CostCentreTree where
80+ mempty = CostCentreTree 0 0 mempty
81+ mappend = (S.<>)
82+
83+getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
84+getCostCentreStack = go []
85+ where go l ccs = if ccs == nullPtr
86+ then return l
87+ else do
88+ cc <- ccsCC ccs
89+ parent <- ccsParent ccs
90+ go (cc : l) parent
91+
92+toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
93+toCostCentreTree ccs n =
94+ foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty)
95+ <$> getCostCentreStack ccs
96+
97+getCostCentreTree :: IO CostCentreTree
98+getCostCentreTree = do
99+ vals <- readIORef profilingData
100+ mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
101+
102+formatCostCentreTree :: CostCentreTree -> IO String
103+formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
104+ where go :: Int -> CostCentreTree -> StateT [String] IO ()
105+ go depth cct = do
106+ let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
107+ indent = mconcat $ replicate depth " "
108+ forM_ children $ \(cc, childCct) -> do
109+ lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
110+ mdl <- liftIO $ peekCString utf8 =<< ccModule cc
111+ loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
112+ let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
113+ modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
114+ go (succ depth) childCct
115+
116+showProfilingData :: IO ()
117+showProfilingData = do
118+ putStr =<< formatCostCentreTree =<< getCostCentreTree
119+
120+writeProfilingData :: FilePath -> IO ()
121+writeProfilingData p = do
122+ writeFile p =<< formatCostCentreTree =<< getCostCentreTree
123+
124+newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
125+ deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
126+
127+profileEvent :: Reflex t => Event t a -> Event t a
128+profileEvent e = unsafePerformIO $ do
129+ stack <- getCurrentCCS e
130+ let f x = unsafePerformIO $ do
131+ modifyIORef' profilingData $ Map.insertWith (+) stack 1
132+ return $ return $ Just x
133+ return $ pushCheap f e
134+
135+--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
136+
137+instance Reflex t => Reflex (ProfiledTimeline t) where
138+ newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
139+ newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
140+ newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
141+ newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
142+ type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
143+ type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
144+ never = Event_Profiled never
145+ constant = Behavior_Profiled . constant
146+ push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
147+ pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
148+ pull = Behavior_Profiled . pull . coerce
149+ fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)
150+ mergeG :: forall z (k :: z -> *) q v. GCompare k
151+ => (forall a. q a -> Event (ProfiledTimeline t) (v a))
152+ -> DMap k q -> Event (ProfiledTimeline t) (DMap k v)
153+ mergeG nt = Event_Profiled #. mergeG (coerce nt)
154+ switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
155+ coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
156+ current (Dynamic_Profiled d) = coerce $ current d
157+ updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
158+ unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
159+ unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
160+ mergeIncrementalG nt res = Event_Profiled $ mergeIncrementalG (coerce nt) (coerce res)
161+ mergeIncrementalWithMoveG nt res = Event_Profiled $ mergeIncrementalWithMoveG (coerce nt) (coerce res)
162+ currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
163+ updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
164+ incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
165+ behaviorCoercion c =
166+ Coercion `trans` behaviorCoercion @t c `trans` Coercion
167+ eventCoercion c =
168+ Coercion `trans` eventCoercion @t c `trans` Coercion
169+ dynamicCoercion c =
170+ Coercion `trans` dynamicCoercion @t c `trans` Coercion
171+ incrementalCoercion c d =
172+ Coercion `trans` incrementalCoercion @t c d `trans` Coercion
173+ mergeIntIncremental = Event_Profiled . mergeIntIncremental .
174+ coerceWith (Coercion `trans` incrementalCoercion Coercion Coercion `trans` Coercion)
175+ fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
176+
177+deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
178+deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
179+deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
180+
181+instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
182+ hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
183+ holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
184+ holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
185+ buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
186+ headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
187+ now = ProfiledM $ Event_Profiled <$> now
188+
189+instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
190+ sample (Behavior_Profiled b) = ProfiledM $ sample b
191+
192+instance Adjustable t m => Adjustable (ProfiledTimeline t) (ProfiledM m) where
193+ runWithReplace a0 a' = (fmap . fmap) coerce . lift $
194+ runWithReplace (coerce a0) (coerce $ coerce <$> a')
195+ traverseIntMapWithKeyWithAdjust f dm0 dm' = (fmap . fmap) coerce . lift $
196+ traverseIntMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')
197+ traverseDMapWithKeyWithAdjust f dm0 dm' = (fmap . fmap) coerce . lift $
198+ traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')
199+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = (fmap . fmap) coerce . lift $
200+ traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) dm0 (coerce dm')
201+
202+instance MonadTrans ProfiledM where
203+ lift = ProfiledM
204+
205+instance MonadIO m => MonadIO (ProfiledM m) where
206+ liftIO = lift . liftIO
207+
208+instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
209+ type Performable (ProfiledM m) = Performable m
210+ performEvent_ = lift . performEvent_ . coerce
211+ performEvent = lift . fmap coerce . performEvent . coerce
212+
213+instance TriggerEvent t m => TriggerEvent (ProfiledTimeline t) (ProfiledM m) where
214+ newTriggerEvent = first coerce <$> lift newTriggerEvent
215+ newTriggerEventWithOnComplete = first coerce <$> lift newTriggerEventWithOnComplete
216+ newEventWithLazyTriggerWithOnComplete f = coerce <$> lift (newEventWithLazyTriggerWithOnComplete f)
217+
218+instance PostBuild t m => PostBuild (ProfiledTimeline t) (ProfiledM m) where
219+ getPostBuild = coerce <$> lift getPostBuild
220+
221+instance NotReady t m => NotReady (ProfiledTimeline t) (ProfiledM m) where
222+ notReady = lift notReady
223+ notReadyUntil = lift . notReadyUntil . coerce
224+
225+instance BehaviorWriter t w m => BehaviorWriter (ProfiledTimeline t) w (ProfiledM m) where
226+ tellBehavior = lift . tellBehavior . coerce
227+
228+instance DynamicWriter t w m => DynamicWriter (ProfiledTimeline t) w (ProfiledM m) where
229+ tellDyn = lift . tellDyn . coerce
230+
231+instance EventWriter t w m => EventWriter (ProfiledTimeline t) w (ProfiledM m) where
232+ tellEvent = lift . tellEvent . coerce
233+
234+instance MonadQuery t q m => MonadQuery (ProfiledTimeline t) q (ProfiledM m) where
235+ tellQueryIncremental = lift . tellQueryIncremental . coerce
236+ askQueryResult = coerce <$> lift askQueryResult
237+ queryIncremental = fmap coerce . lift . queryIncremental . coerce
238+
239+instance Requester t m => Requester (ProfiledTimeline t) (ProfiledM m) where
240+ type Request (ProfiledM m) = Request m
241+ type Response (ProfiledM m) = Response m
242+
243+ requesting = fmap coerce . lift . requesting . coerce
244+ requesting_ = lift . requesting_ . coerce
245+
246+instance MonadRef m => MonadRef (ProfiledM m) where
247+ type Ref (ProfiledM m) = Ref m
248+ newRef = lift . newRef
249+ readRef = lift . readRef
250+ writeRef r = lift . writeRef r
251+
252+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
253+ newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
254+ newFanEventWithTrigger f = do
255+ es <- lift $ newFanEventWithTrigger f
256+ return $ EventSelector $ \k -> coerce $ select es k
257+
258+instance MonadReader r m => MonadReader r (ProfiledM m) where
259+ ask = lift ask
260+ local f (ProfiledM a) = ProfiledM $ local f a
261+ reader = lift . reader
262+
263+instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
264+ type EventTrigger (ProfiledTimeline t) = EventTrigger t
265+ type EventHandle (ProfiledTimeline t) = EventHandle t
266+ type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
267+
268+instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
269+ subscribeEvent = lift . subscribeEvent . coerce
270+
271+instance PrimMonad m => PrimMonad (ProfiledM m) where
272+ type PrimState (ProfiledM m) = PrimState m
273+ primitive = lift . primitive
274+
275+instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
276+ type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
277+ fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
278+ runHostFrame = lift . runHostFrame . coerce
279+
280+instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
281+ readEvent = lift . fmap coerce . readEvent
src/Reflex/Pure.hsnew file+217
@@ -0,0 +1,217 @@
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)
36+import Data.GADT.Compare (GCompare)
37+import qualified Data.Dependent.Map as DMap
38+import Data.IntMap (IntMap)
39+import qualified Data.IntMap as IntMap
40+import Data.Maybe
41+import Data.MemoTrie
42+import Data.Monoid
43+import Data.Type.Coercion
44+import Reflex.Class
45+import Data.Kind (Type)
46+
47+-- | A completely pure-functional 'Reflex' timeline, identifying moments in time
48+-- with the type @/t/@.
49+data Pure (t :: Type)
50+
51+-- | The 'Enum' instance of @/t/@ must be dense: for all @/x :: t/@, there must not exist
52+-- any @/y :: t/@ such that @/'pred' x < y < x/@. The 'HasTrie' instance will be used
53+-- exclusively to memoize functions of @/t/@, not for any of its other capabilities.
54+instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where
55+
56+ newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }
57+ newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }
58+ newtype Dynamic (Pure t) a = Dynamic { unDynamic :: t -> (a, Maybe a) }
59+ newtype Incremental (Pure t) p = Incremental { unIncremental :: t -> (PatchTarget p, Maybe p) }
60+
61+ type PushM (Pure t) = (->) t
62+ type PullM (Pure t) = (->) t
63+
64+ never :: Event (Pure t) a
65+ never = Event $ \_ -> Nothing
66+
67+ constant :: a -> Behavior (Pure t) a
68+ constant x = Behavior $ \_ -> x
69+
70+ push :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
71+ push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t
72+
73+ pushCheap :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b
74+ pushCheap = push
75+
76+ pull :: PullM (Pure t) a -> Behavior (Pure t) a
77+ pull = Behavior . memo
78+
79+ -- [UNUSED_CONSTRAINT]: The following type signature for merge will produce a
80+ -- warning because the GCompare instance is not used; however, removing the
81+ -- GCompare instance produces a different warning, due to that constraint
82+ -- being present in the original class definition.
83+
84+ --mergeG :: GCompare k => (forall a. q a -> Event (Pure t) (v a))
85+ -- -> DMap k q -> Event (Pure t) (DMap k v)
86+ mergeG nt events = Event $ memo $ \t ->
87+ let currentOccurrences = DMap.mapMaybeWithKey (\_ q -> case nt q of Event a -> a t) events
88+ in if DMap.null currentOccurrences
89+ then Nothing
90+ else Just currentOccurrences
91+
92+-- The instance signature doeesn't compile, leave commented for documentation
93+-- fanG :: GCompare k => Event (Pure t) (DMap k v) -> EventSelectorG (Pure t) k v
94+ fanG e = EventSelectorG $ \k -> Event $ \t -> unEvent e t >>= DMap.lookup k
95+
96+ switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a
97+ switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
98+
99+ coincidence :: Event (Pure t) (Event (Pure t) a) -> Event (Pure t) a
100+ coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
101+
102+ current :: Dynamic (Pure t) a -> Behavior (Pure t) a
103+ current d = Behavior $ \t -> fst $ unDynamic d t
104+
105+ updated :: Dynamic (Pure t) a -> Event (Pure t) a
106+ updated d = Event $ \t -> snd $ unDynamic d t
107+
108+ unsafeBuildDynamic :: PullM (Pure t) a -> Event (Pure t) a -> Dynamic (Pure t) a
109+ unsafeBuildDynamic readV0 v' = Dynamic $ \t -> (readV0 t, unEvent v' t)
110+
111+ -- See UNUSED_CONSTRAINT, above.
112+
113+ --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p
114+ --a) -> Incremental (Pure t) p a
115+ unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)
116+
117+ mergeIncrementalG = mergeIncrementalImpl
118+ mergeIncrementalWithMoveG = mergeIncrementalImpl
119+
120+ currentIncremental i = Behavior $ \t -> fst $ unIncremental i t
121+
122+ updatedIncremental i = Event $ \t -> snd $ unIncremental i t
123+
124+ incrementalToDynamic i = Dynamic $ \t ->
125+ let (old, mPatch) = unIncremental i t
126+ e = case mPatch of
127+ Nothing -> Nothing
128+ Just patch -> apply patch old
129+ in (old, e)
130+ behaviorCoercion Coercion = Coercion
131+ eventCoercion Coercion = Coercion
132+ dynamicCoercion Coercion = Coercion
133+ incrementalCoercion Coercion Coercion = Coercion
134+
135+ fanInt e = EventSelectorInt $ \k -> Event $ \t -> unEvent e t >>= IntMap.lookup k
136+
137+ mergeIntIncremental = mergeIntIncrementalImpl
138+
139+mergeIncrementalImpl :: (PatchTarget p ~ DMap k q, GCompare k)
140+ => (forall a. q a -> Event (Pure t) (v a))
141+ -> Incremental (Pure t) p -> Event (Pure t) (DMap k v)
142+mergeIncrementalImpl nt i = Event $ \t ->
143+ let results = DMap.mapMaybeWithKey (\_ q -> case nt q of Event e -> e t) $ fst $ unIncremental i t
144+ in if DMap.null results
145+ then Nothing
146+ else Just results
147+
148+mergeIntIncrementalImpl :: (PatchTarget p ~ IntMap (Event (Pure t) a)) => Incremental (Pure t) p -> Event (Pure t) (IntMap a)
149+mergeIntIncrementalImpl i = Event $ \t ->
150+ let results = IntMap.mapMaybeWithKey (\_ (Event e) -> e t) $ fst $ unIncremental i t
151+ in if IntMap.null results
152+ then Nothing
153+ else Just results
154+
155+instance Functor (Dynamic (Pure t)) where
156+ fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t
157+ in (f cur, fmap f upd)
158+
159+instance Applicative (Dynamic (Pure t)) where
160+ pure a = Dynamic $ \_ -> (a, Nothing)
161+ (<*>) = ap
162+
163+instance Monad (Dynamic (Pure t)) where
164+ return = pure
165+ (x :: Dynamic (Pure t) a) >>= (f :: a -> Dynamic (Pure t) b) = Dynamic $ \t ->
166+ let (curX :: a, updX :: Maybe a) = unDynamic x t
167+ (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t
168+ (updInner :: Maybe b, updBoth :: Maybe b) = case updX of
169+ Nothing -> (Nothing, Nothing)
170+ Just nextX -> let (c, u) = unDynamic (f nextX) t
171+ in (Just c, u)
172+ in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])
173+
174+instance MonadSample (Pure t) ((->) t) where
175+
176+ sample :: Behavior (Pure t) a -> (t -> a)
177+ sample = unBehavior
178+
179+instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
180+
181+ hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a
182+ hold initialValue e initialTime = Behavior f
183+ where f = memo $ \sampleTime ->
184+ -- Really, the sampleTime should never be prior to the initialTime,
185+ -- because that would mean the Behavior is being sampled before
186+ -- being created.
187+ if sampleTime <= initialTime
188+ then initialValue
189+ else let lastTime = pred sampleTime
190+ in fromMaybe (f lastTime) $ unEvent e lastTime
191+
192+ holdDyn v0 = buildDynamic (return v0)
193+
194+ buildDynamic :: (t -> a) -> Event (Pure t) a -> t -> Dynamic (Pure t) a
195+ buildDynamic initialValue e initialTime =
196+ let Behavior f = hold (initialValue initialTime) e initialTime
197+ in Dynamic $ \t -> (f t, unEvent e t)
198+
199+ holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p
200+ holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)
201+ where f = memo $ \sampleTime ->
202+ -- Really, the sampleTime should never be prior to the initialTime,
203+ -- because that would mean the Behavior is being sampled before
204+ -- being created.
205+ if sampleTime <= initialTime
206+ then initialValue
207+ else let lastTime = pred sampleTime
208+ lastValue = f lastTime
209+ in case unEvent e lastTime of
210+ Nothing -> lastValue
211+ Just x -> fromMaybe lastValue $ apply x lastValue
212+
213+ headE = slowHeadE
214+ now t = Event $ guard . (t ==)
215+
216+
217+
src/Reflex/Query/Base.hsnew file+346
@@ -0,0 +1,346 @@
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+ , mapQueryT
20+ ) where
21+
22+import Control.Applicative (liftA2)
23+import Control.Monad.Exception
24+import Control.Monad.Fix
25+import Control.Monad.Morph
26+import Control.Monad.Primitive
27+import Control.Monad.Reader
28+import Control.Monad.Ref
29+import Control.Monad.State.Strict
30+import Data.Align
31+import Data.Dependent.Map (DMap)
32+import qualified Data.Dependent.Map as DMap
33+import Data.Dependent.Sum (DSum(..))
34+import Data.Foldable
35+import Data.Functor.Compose
36+import Data.Functor.Misc
37+import Data.GADT.Compare (GCompare)
38+import Data.IntMap (IntMap)
39+import qualified Data.IntMap as IntMap
40+import Data.Map (Map)
41+import qualified Data.Map as Map
42+import Data.Monoid ((<>))
43+import qualified Data.Semigroup as S
44+import Data.Some (Some(Some))
45+import Data.These
46+
47+import Reflex.Class
48+import Reflex.Adjustable.Class
49+import Reflex.DynamicWriter.Class
50+import Reflex.EventWriter.Base
51+import Reflex.EventWriter.Class
52+import Reflex.Host.Class
53+import qualified Data.Patch.MapWithMove as MapWithMove
54+import Reflex.PerformEvent.Class
55+import Reflex.PostBuild.Class
56+import Reflex.Query.Class
57+import Reflex.Requester.Class
58+import Reflex.TriggerEvent.Class
59+
60+newtype QueryT t q m a = QueryT { unQueryT :: StateT [Behavior t q] (EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m)) a }
61+ deriving (Functor, Applicative, Monad, MonadException, MonadFix, MonadIO, MonadAtomicRef)
62+
63+deriving instance MonadHold t m => MonadHold t (QueryT t q m)
64+deriving instance MonadSample t m => MonadSample t (QueryT t q m)
65+
66+runQueryT :: (MonadFix m, Additive q, Group q, Reflex t) => QueryT t q m a -> Dynamic t (QueryResult q) -> m (a, Incremental t (AdditivePatch q))
67+runQueryT (QueryT a) qr = do
68+ ((r, bs), es) <- runReaderT (runEventWriterT (runStateT a mempty)) qr
69+ return (r, unsafeBuildIncremental (foldlM (\b c -> (b <>) <$> sample c) mempty bs) (fmapCheap AdditivePatch es))
70+
71+newtype QueryTLoweredResult t q v = QueryTLoweredResult (v, [Behavior t q])
72+
73+getQueryTLoweredResultValue :: QueryTLoweredResult t q v -> v
74+getQueryTLoweredResultValue (QueryTLoweredResult (v, _)) = v
75+
76+getQueryTLoweredResultWritten :: QueryTLoweredResult t q v -> [Behavior t q]
77+getQueryTLoweredResultWritten (QueryTLoweredResult (_, w)) = w
78+
79+maskMempty :: (Eq a, Monoid a) => a -> Maybe a
80+maskMempty x = if x == mempty then Nothing else Just x
81+
82+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
83+ runWithReplace (QueryT a0) a' = do
84+ ((r0, bs0), r') <- QueryT $ lift $ runWithReplace (runStateT a0 []) $ fmapCheap (flip runStateT [] . unQueryT) a'
85+ let sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
86+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
87+ bs' = fmapCheap snd $ r'
88+ bbs <- hold bs0 bs'
89+ let patches = flip pushCheap bs' $ \newBs -> do
90+ oldBs <- sample bbs
91+ maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
92+ QueryT $ modify $ (:) $ pull $ sampleBs =<< sample bbs
93+ QueryT $ lift $ tellEvent patches
94+ return (r0, fmapCheap fst r')
95+
96+ 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'))
97+ traverseIntMapWithKeyWithAdjust f im0 im' = do
98+ let f' :: IntMap.Key -> v -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (QueryTLoweredResult t q v')
99+ f' k v = fmap QueryTLoweredResult $ flip runStateT [] $ unQueryT $ f k v
100+ (result0, result') <- QueryT $ lift $ traverseIntMapWithKeyWithAdjust f' im0 im'
101+ let liftedResult0 = IntMap.map getQueryTLoweredResultValue result0
102+ liftedResult' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
103+ IntMap.map (fmap getQueryTLoweredResultValue) p
104+ liftedBs0 :: IntMap [Behavior t q]
105+ liftedBs0 = IntMap.map getQueryTLoweredResultWritten result0
106+ liftedBs' :: Event t (PatchIntMap [Behavior t q])
107+ liftedBs' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $
108+ IntMap.map (fmap getQueryTLoweredResultWritten) p
109+ sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
110+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
111+ accumBehaviors :: forall m'. MonadHold t m'
112+ => IntMap [Behavior t q]
113+ -> PatchIntMap [Behavior t q]
114+ -> m' ( Maybe (IntMap [Behavior t q])
115+ , Maybe (AdditivePatch q))
116+ -- f accumulates the child behavior state we receive from running traverseIntMapWithKeyWithAdjust for the underlying monad.
117+ -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
118+ -- bs0 is a Map denoting the behaviors of the current children.
119+ -- pbs is a PatchMap denoting an update to the behaviors of the current children
120+ accumBehaviors bs0 pbs@(PatchIntMap bs') = do
121+ let p k bs = case IntMap.lookup k bs0 of
122+ Nothing -> case bs of
123+ -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
124+ Nothing -> return mempty
125+ -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
126+ Just newBs -> sampleBs newBs
127+ Just oldBs -> case bs of
128+ -- 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
129+ Nothing -> negateG <$> sampleBs oldBs
130+ -- 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
131+ -- composed with the sampling the child's new state.
132+ Just newBs -> (~~) <$> sampleBs newBs <*> sampleBs oldBs
133+ -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
134+ -- child patches and wrap them in AdditivePatch.
135+ patch <- AdditivePatch . fold <$> IntMap.traverseWithKey p bs'
136+ return (apply pbs bs0, Just patch)
137+ (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
138+ tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
139+ return (liftedResult0, liftedResult')
140+
141+ traverseDMapWithKeyWithAdjust :: forall (k :: * -> *) v v'. (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'))
142+ traverseDMapWithKeyWithAdjust f dm0 dm' = do
143+ let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
144+ f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
145+ (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjust f' dm0 dm'
146+ let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
147+ liftedResult' = fforCheap result' $ \(PatchDMap p) -> PatchDMap $
148+ mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (getQueryTLoweredResultValue . getCompose) mr)) p
149+ liftedBs0 :: Map (Some k) [Behavior t q]
150+ liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
151+ liftedBs' :: Event t (PatchMap (Some k) [Behavior t q])
152+ liftedBs' = fforCheap result' $ \(PatchDMap p) -> PatchMap $
153+ Map.fromDistinctAscList $ (\(k :=> ComposeMaybe mr) -> (Some k, fmap (getQueryTLoweredResultWritten . getCompose) mr)) <$> DMap.toList p
154+ sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
155+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
156+ accumBehaviors :: forall m'. MonadHold t m'
157+ => Map (Some k) [Behavior t q]
158+ -> PatchMap (Some k) [Behavior t q]
159+ -> m' ( Maybe (Map (Some k) [Behavior t q])
160+ , Maybe (AdditivePatch q))
161+ -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjust for the underlying monad.
162+ -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
163+ -- bs0 is a Map denoting the behaviors of the current children.
164+ -- pbs is a PatchMap denoting an update to the behaviors of the current children
165+ accumBehaviors bs0 pbs@(PatchMap bs') = do
166+ let p k bs = case Map.lookup k bs0 of
167+ Nothing -> case bs of
168+ -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
169+ Nothing -> return Nothing
170+ -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
171+ Just newBs -> maskMempty <$> sampleBs newBs
172+ Just oldBs -> case bs of
173+ -- 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
174+ Nothing -> maskMempty . negateG <$> sampleBs oldBs
175+ -- 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
176+ -- composed with the sampling the child's new state.
177+ Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
178+ -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
179+ -- child patches and wrap them in AdditivePatch.
180+ patch <- fold <$> Map.traverseWithKey p bs'
181+ return (apply pbs bs0, AdditivePatch <$> patch)
182+ (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors liftedBs0 liftedBs'
183+ tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
184+ return (liftedResult0, liftedResult')
185+
186+ traverseDMapWithKeyWithAdjustWithMove :: forall (k :: * -> *) v v'. (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'))
187+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do
188+ let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)
189+ f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v
190+ (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjustWithMove f' dm0 dm'
191+ let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0
192+ liftedResult' = fforCheap result' $ mapPatchDMapWithMove (getQueryTLoweredResultValue . getCompose)
193+ liftedBs0 :: Map (Some k) [Behavior t q]
194+ liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0
195+ liftedBs' :: Event t (PatchMapWithMove (Some k) [Behavior t q])
196+ liftedBs' = fforCheap result' $ weakenPatchDMapWithMoveWith (getQueryTLoweredResultWritten . getCompose) {- \(PatchDMap p) -> PatchMapWithMove $
197+ Map.fromDistinctAscList $ (\(k :=> mr) -> (Some k, fmap (fmap (getQueryTLoweredResultWritten . getCompose)) mr)) <$> DMap.toList p -}
198+ sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q
199+ sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty
200+ accumBehaviors' :: forall m'. MonadHold t m'
201+ => Map (Some k) [Behavior t q]
202+ -> PatchMapWithMove (Some k) [Behavior t q]
203+ -> m' ( Maybe (Map (Some k) [Behavior t q])
204+ , Maybe (AdditivePatch q))
205+ -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjustWithMove for the underlying monad.
206+ -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.
207+ -- bs0 is a Map denoting the behaviors of the current children.
208+ -- pbs is a PatchMapWithMove denoting an update to the behaviors of the current children
209+ accumBehaviors' bs0 pbs = do
210+ let bs' = unPatchMapWithMove pbs
211+ p k bs = case Map.lookup k bs0 of
212+ Nothing -> case MapWithMove._nodeInfo_from bs of
213+ -- If the update is to delete the state for a child that doesn't exist, the patch is mempty.
214+ MapWithMove.From_Delete -> return Nothing
215+ -- If the update is to update the state for a child that doesn't exist, the patch is the sample of the new state.
216+ MapWithMove.From_Insert newBs -> maskMempty <$> sampleBs newBs
217+ MapWithMove.From_Move k' -> case Map.lookup k' bs0 of
218+ Nothing -> return Nothing
219+ Just newBs -> maskMempty <$> sampleBs newBs
220+ Just oldBs -> case MapWithMove._nodeInfo_from bs of
221+ -- 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
222+ MapWithMove.From_Delete -> maskMempty . negateG <$> sampleBs oldBs
223+ -- 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
224+ -- composed with the sampling the child's new state.
225+ MapWithMove.From_Insert newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
226+ MapWithMove.From_Move k'
227+ | k' == k -> return Nothing
228+ | otherwise -> case Map.lookup k' bs0 of
229+ -- If we are moving from a non-existent key, that is a delete
230+ Nothing -> maskMempty . negateG <$> sampleBs oldBs
231+ Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)
232+ -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the
233+ -- child patches and wrap them in AdditivePatch.
234+ patch <- fold <$> Map.traverseWithKey p bs'
235+ return (apply pbs bs0, AdditivePatch <$> patch)
236+ (qpatch :: Event t (AdditivePatch q)) <- mapAccumMaybeM_ accumBehaviors' liftedBs0 liftedBs'
237+ tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch
238+ return (liftedResult0, liftedResult')
239+
240+instance MonadTrans (QueryT t q) where
241+ lift = QueryT . lift . lift . lift
242+
243+instance MFunctor (QueryT t q) where
244+ hoist = mapQueryT
245+
246+instance PrimMonad m => PrimMonad (QueryT t q m) where
247+ type PrimState (QueryT t q m) = PrimState m
248+ primitive = lift . primitive
249+
250+instance PostBuild t m => PostBuild t (QueryT t q m) where
251+ getPostBuild = lift getPostBuild
252+
253+instance (MonadAsyncException m) => MonadAsyncException (QueryT t q m) where
254+ mask f = QueryT $ mask $ \unMask -> unQueryT $ f $ QueryT . unMask . unQueryT
255+
256+instance TriggerEvent t m => TriggerEvent t (QueryT t q m) where
257+ newTriggerEvent = lift newTriggerEvent
258+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
259+ newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
260+
261+instance PerformEvent t m => PerformEvent t (QueryT t q m) where
262+ type Performable (QueryT t q m) = Performable m
263+ performEvent_ = lift . performEvent_
264+ performEvent = lift . performEvent
265+
266+instance MonadRef m => MonadRef (QueryT t q m) where
267+ type Ref (QueryT t q m) = Ref m
268+ newRef = QueryT . newRef
269+ readRef = QueryT . readRef
270+ writeRef r = QueryT . writeRef r
271+
272+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (QueryT t q m) where
273+ newEventWithTrigger = QueryT . newEventWithTrigger
274+ newFanEventWithTrigger a = QueryT . lift $ newFanEventWithTrigger a
275+
276+-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
277+instance (Monoid a, Monad m) => Monoid (QueryT t q m a) where
278+ mempty = pure mempty
279+ mappend = (<>)
280+
281+instance (S.Semigroup a, Monad m) => S.Semigroup (QueryT t q m a) where
282+ (<>) = liftA2 (S.<>)
283+
284+-- | withQueryT's QueryMorphism argument needs to be a group homomorphism in order to behave correctly
285+withQueryT :: (MonadFix m, PostBuild t m, Group q, Group q', Additive q, Additive q', Query q')
286+ => QueryMorphism q q'
287+ -> QueryT t q m a
288+ -> QueryT t q' m a
289+withQueryT f a = do
290+ r' <- askQueryResult
291+ (result, q) <- lift $ runQueryT a $ mapQueryResult f <$> r'
292+ tellQueryIncremental $ unsafeBuildIncremental
293+ (fmap (mapQuery f) (sample (currentIncremental q)))
294+ (fmapCheap (AdditivePatch . mapQuery f . unAdditivePatch) $ updatedIncremental q)
295+ return result
296+
297+-- | Maps a function over a 'QueryT' that can change the underlying monad
298+mapQueryT :: (forall b. m b -> n b) -> QueryT t q m a -> QueryT t q n a
299+mapQueryT f (QueryT a) = QueryT $ mapStateT (mapEventWriterT (mapReaderT f)) a
300+
301+-- | dynWithQueryT's (Dynamic t QueryMorphism) argument needs to be a group homomorphism at all times in order to behave correctly
302+dynWithQueryT :: (MonadFix m, PostBuild t m, Group q, Additive q, Group q', Additive q', Query q')
303+ => Dynamic t (QueryMorphism q q')
304+ -> QueryT t q m a
305+ -> QueryT t q' m a
306+dynWithQueryT f q = do
307+ r' <- askQueryResult
308+ (result, q') <- lift $ runQueryT q $ zipDynWith mapQueryResult f r'
309+ tellQueryIncremental $ zipDynIncrementalWith mapQuery f q'
310+ return result
311+ where zipDynIncrementalWith g da ib =
312+ let eab = align (updated da) (updatedIncremental ib)
313+ ec = flip push eab $ \case
314+ This a -> do
315+ aOld <- sample $ current da
316+ b <- sample $ currentIncremental ib
317+ return $ Just $ AdditivePatch (g a b ~~ g aOld b)
318+ That (AdditivePatch b) -> do
319+ a <- sample $ current da
320+ return $ Just $ AdditivePatch $ g a b
321+ These a (AdditivePatch b) -> do
322+ aOld <- sample $ current da
323+ bOld <- sample $ currentIncremental ib
324+ return $ Just $ AdditivePatch $ mconcat [ g a bOld, negateG (g aOld bOld), g a b]
325+ in unsafeBuildIncremental (g <$> sample (current da) <*> sample (currentIncremental ib)) ec
326+
327+instance (Monad m, Group q, Additive q, Query q, Reflex t) => MonadQuery t q (QueryT t q m) where
328+ tellQueryIncremental q = do
329+ QueryT (modify (currentIncremental q:))
330+ QueryT (lift (tellEvent (fmapCheap unAdditivePatch (updatedIncremental q))))
331+ askQueryResult = QueryT ask
332+ queryIncremental q = do
333+ tellQueryIncremental q
334+ zipDynWith crop (incrementalToDynamic q) <$> askQueryResult
335+
336+instance Requester t m => Requester t (QueryT t q m) where
337+ type Request (QueryT t q m) = Request m
338+ type Response (QueryT t q m) = Response m
339+ requesting = lift . requesting
340+ requesting_ = lift . requesting_
341+
342+instance EventWriter t w m => EventWriter t w (QueryT t q m) where
343+ tellEvent = lift . tellEvent
344+
345+instance DynamicWriter t w m => DynamicWriter t w (QueryT t q m) where
346+ tellDyn = lift . tellDyn
src/Reflex/Query/Class.hsnew file+158
@@ -0,0 +1,158 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE FunctionalDependencies #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE TypeFamilies #-}
8+{-# LANGUAGE UndecidableInstances #-}
9+-- |
10+-- Module:
11+-- Reflex.Query.Class
12+-- Description:
13+-- A class that ties together queries to some data source and their results,
14+-- providing methods for requesting data from the source and accumulating
15+-- streamed results.
16+module Reflex.Query.Class
17+ ( Query (..)
18+ , QueryMorphism (..)
19+ , SelectedCount (..)
20+ , combineSelectedCounts
21+
22+ , MonadQuery (..)
23+ , tellQueryDyn
24+ , queryDyn
25+ , subQuery
26+ , mapQuery
27+ , mapQueryResult
28+ ) where
29+
30+import Control.Category (Category)
31+import qualified Control.Category as Cat
32+import Control.Monad.Reader
33+import Data.Bits
34+import Data.Data
35+import Data.Ix
36+import Data.Map.Monoidal (MonoidalMap)
37+import qualified Data.Map.Monoidal as MonoidalMap
38+import Data.Semigroup (Semigroup(..))
39+import Foreign.Storable
40+import Data.Void
41+import Data.Monoid hiding ((<>))
42+import Control.Applicative
43+
44+import Reflex.Class
45+
46+-- | A 'Query' can be thought of as a declaration of interest in some set of data.
47+-- A 'QueryResult' is the set of data associated with that interest set.
48+-- The @crop@ function provides a way to determine what part of a given 'QueryResult'
49+-- is relevant to a given 'Query'.
50+class (Monoid (QueryResult a), Semigroup (QueryResult a)) => Query a where
51+ type QueryResult a :: *
52+ crop :: a -> QueryResult a -> QueryResult a
53+
54+instance (Ord k, Query v) => Query (MonoidalMap k v) where
55+ type QueryResult (MonoidalMap k v) = MonoidalMap k (QueryResult v)
56+ crop q r = MonoidalMap.intersectionWith (flip crop) r q
57+
58+-- | the result of two queries is both results.
59+instance (Query a, Query b) => Query (a, b) where
60+ type QueryResult (a, b) = (QueryResult a, QueryResult b)
61+ crop (x, x') (y, y') = (crop x y, crop x' y')
62+
63+-- | Trivial queries have trivial results.
64+instance Query () where
65+ type QueryResult () = ()
66+ crop _ _ = ()
67+
68+-- | The result of an absurd query is trivial; If you can ask the question, the
69+-- answer cannot tell you anything you didn't already know.
70+--
71+-- 'QueryResult Void = @Void@' seems like it would also work, but that has
72+-- problems of robustness. In some applications, an unasked question can still
73+-- be answered, so it is important that the result is inhabited even when the
74+-- question isn't. Applications that wish to prevent this can mandate that the
75+-- query result be paired with the query: then the whole response will be
76+-- uninhabited as desired.
77+instance Query Void where
78+ type QueryResult Void = ()
79+ crop = absurd
80+
81+#if MIN_VERSION_base(4,12,0)
82+-- | We can lift queries into monoidal containers.
83+-- But beware of Applicatives whose monoid is different from (pure mempty, liftA2 mappend)
84+instance (Query q, Applicative f) => Query (Ap f q) where
85+ type QueryResult (Ap f q) = Ap f (QueryResult q)
86+ crop = liftA2 crop
87+#endif
88+
89+-- | QueryMorphism's must be group homomorphisms when acting on the query type
90+-- and compatible with the query relationship when acting on the query result.
91+data QueryMorphism q q' = QueryMorphism
92+ { _queryMorphism_mapQuery :: q -> q'
93+ , _queryMorphism_mapQueryResult :: QueryResult q' -> QueryResult q
94+ }
95+
96+instance Category QueryMorphism where
97+ id = QueryMorphism id id
98+ qm . qm' = QueryMorphism
99+ { _queryMorphism_mapQuery = mapQuery qm . mapQuery qm'
100+ , _queryMorphism_mapQueryResult = mapQueryResult qm' . mapQueryResult qm
101+ }
102+
103+-- | Apply a 'QueryMorphism' to a 'Query'
104+mapQuery :: QueryMorphism q q' -> q -> q'
105+mapQuery = _queryMorphism_mapQuery
106+
107+-- | Map a 'QueryMorphism' to a 'QueryResult'
108+mapQueryResult :: QueryMorphism q q' -> QueryResult q' -> QueryResult q
109+mapQueryResult = _queryMorphism_mapQueryResult
110+
111+-- | This type can be used to track of the frequency of interest in a given 'Query'. See note on
112+-- 'combineSelectedCounts'
113+newtype SelectedCount = SelectedCount { unSelectedCount :: Int }
114+ deriving (Eq, Ord, Show, Read, Integral, Num, Bounded, Enum, Real, Ix, Bits, FiniteBits, Storable, Data)
115+
116+instance Semigroup SelectedCount where
117+ SelectedCount a <> SelectedCount b = SelectedCount (a + b)
118+
119+instance Monoid SelectedCount where
120+ mempty = SelectedCount 0
121+ mappend = (<>)
122+
123+instance Group SelectedCount where
124+ negateG (SelectedCount a) = SelectedCount (negate a)
125+
126+instance Additive SelectedCount
127+
128+-- | The Semigroup\/Monoid\/Group instances for a Query containing 'SelectedCount's should use
129+-- this function which returns Nothing if the result is 0. This allows the pruning of leaves
130+-- of the 'Query' that are no longer wanted.
131+combineSelectedCounts :: SelectedCount -> SelectedCount -> Maybe SelectedCount
132+combineSelectedCounts (SelectedCount i) (SelectedCount j) = if i == negate j then Nothing else Just $ SelectedCount (i + j)
133+
134+-- | A class that allows sending of 'Query's and retrieval of 'QueryResult's. See 'queryDyn' for a commonly
135+-- used interface.
136+class (Group q, Additive q, Query q, Monad m) => MonadQuery t q m | m -> q t where
137+ tellQueryIncremental :: Incremental t (AdditivePatch q) -> m ()
138+ askQueryResult :: m (Dynamic t (QueryResult q))
139+ queryIncremental :: Incremental t (AdditivePatch q) -> m (Dynamic t (QueryResult q))
140+
141+instance MonadQuery t q m => MonadQuery t q (ReaderT r m) where
142+ tellQueryIncremental = lift . tellQueryIncremental
143+ askQueryResult = lift askQueryResult
144+ queryIncremental = lift . queryIncremental
145+
146+-- | Produce and send an 'Incremental' 'Query' from a 'Dynamic' 'Query'.
147+tellQueryDyn :: (Reflex t, MonadQuery t q m) => Dynamic t q -> m ()
148+tellQueryDyn d = tellQueryIncremental $ unsafeBuildIncremental (sample (current d)) $ attachWith (\old new -> AdditivePatch $ new ~~ old) (current d) (updated d)
149+
150+-- | Retrieve 'Dynamic'ally updating 'QueryResult's for a 'Dynamic'ally updating 'Query'.
151+queryDyn :: (Reflex t, MonadQuery t q m) => Dynamic t q -> m (Dynamic t (QueryResult q))
152+queryDyn q = do
153+ tellQueryDyn q
154+ zipDynWith crop q <$> askQueryResult
155+
156+-- | Use a query morphism to operate on a smaller version of a query.
157+subQuery :: (Reflex t, MonadQuery t q2 m) => QueryMorphism q1 q2 -> Dynamic t q1 -> m (Dynamic t (QueryResult q1))
158+subQuery (QueryMorphism f g) x = fmap g <$> queryDyn (fmap f x)
src/Reflex/Requester/Base.hsnew file+607
@@ -0,0 +1,607 @@
1+-- | This module provides 'RequesterT', the standard implementation of
2+-- 'Requester'.
3+{-# LANGUAGE AllowAmbiguousTypes #-}
4+{-# LANGUAGE ApplicativeDo #-}
5+{-# LANGUAGE CPP #-}
6+{-# LANGUAGE EmptyDataDecls #-}
7+{-# LANGUAGE ExistentialQuantification #-}
8+{-# LANGUAGE FlexibleInstances #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE MultiParamTypeClasses #-}
12+{-# LANGUAGE Rank2Types #-}
13+{-# LANGUAGE RecursiveDo #-}
14+{-# LANGUAGE ScopedTypeVariables #-}
15+{-# LANGUAGE StandaloneDeriving #-}
16+{-# LANGUAGE TypeFamilies #-}
17+{-# LANGUAGE TypeOperators #-}
18+{-# LANGUAGE UndecidableInstances #-}
19+#ifdef USE_REFLEX_OPTIMIZER
20+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
21+#endif
22+module Reflex.Requester.Base
23+ ( RequesterT (..)
24+ , runRequesterT
25+ , withRequesterT
26+ , runWithReplaceRequesterTWith
27+ , traverseIntMapWithKeyWithAdjustRequesterTWith
28+ , traverseDMapWithKeyWithAdjustRequesterTWith
29+ , RequesterData
30+ , RequesterDataKey
31+ , traverseRequesterData
32+ , forRequesterData
33+ , requesterDataToList
34+ , singletonRequesterData
35+ , matchResponsesWithRequests
36+ , matchResponseMapWithRequests
37+ , multiEntry
38+ , unMultiEntry
39+ , requesting'
40+ ) where
41+
42+import Reflex.Class
43+import Reflex.Adjustable.Class
44+import Reflex.Dynamic
45+import Reflex.Host.Class
46+import Reflex.PerformEvent.Class
47+import Reflex.PostBuild.Class
48+import Reflex.Requester.Class
49+import Reflex.TriggerEvent.Class
50+
51+import Control.Applicative (liftA2)
52+import Control.Monad.Exception
53+import Control.Monad.Identity
54+import Control.Monad.Morph
55+import Control.Monad.Primitive
56+import Control.Monad.Reader
57+import Control.Monad.Ref
58+import Control.Monad.State.Strict
59+import Data.Bits
60+import Data.Coerce
61+import Data.Constraint
62+import Data.Dependent.Map (DMap)
63+import qualified Data.Dependent.Map as DMap
64+import Data.Dependent.Sum (DSum (..))
65+import Data.Functor.Compose
66+import Data.Functor.Misc
67+import Data.IntMap.Strict (IntMap)
68+import qualified Data.IntMap.Strict as IntMap
69+import Data.Map (Map)
70+import qualified Data.Map as Map
71+import Data.Monoid ((<>))
72+import Data.Proxy
73+import qualified Data.Semigroup as S
74+import Data.Some (Some(Some))
75+import Data.Type.Equality
76+import Data.Unique.Tag
77+
78+import GHC.Exts (Any)
79+import Unsafe.Coerce
80+
81+--TODO: Make this module type-safe
82+
83+newtype TagMap (f :: * -> *) = TagMap (IntMap Any)
84+
85+newtype RequesterData f = RequesterData (TagMap (Entry f))
86+
87+emptyRequesterData :: RequesterData f
88+emptyRequesterData = RequesterData $ TagMap IntMap.empty
89+
90+data RequesterDataKey a where
91+ RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a
92+ 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
93+ RequesterDataKey_Multi2 :: GCompare k => {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
94+ RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a
95+
96+singletonRequesterData :: RequesterDataKey a -> f a -> RequesterData f
97+singletonRequesterData rdk v = case rdk of
98+ RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v
99+ RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v
100+ RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Multi2Contents
101+ { _multi2Contents_values = Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
102+ , _multi2Contents_dict = Dict
103+ }
104+ RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v
105+
106+mergeRequesterData :: RequesterData f -> RequesterData f -> RequesterData f
107+mergeRequesterData (RequesterData a) (RequesterData b) = RequesterData $ mergeTagMap a b
108+
109+mergeTagMap :: forall f. TagMap (Entry f) -> TagMap (Entry f) -> TagMap (Entry f)
110+mergeTagMap (TagMap m) (TagMap n) =
111+ TagMap $ IntMap.unionWithKey (g' combiner) m n
112+ where
113+ combiner :: forall a. MyTag a -> Entry f a -> Entry f a -> Entry f a
114+ combiner k (Entry a) (Entry b) = Entry $ case myKeyType k of
115+ MyTagType_Single -> a
116+ MyTagType_Multi -> IntMap.unionWith mergeRequesterData a b
117+ MyTagType_Multi2 -> case _multi2Contents_dict a of
118+ Dict -> Multi2Contents
119+ { _multi2Contents_values = Map.unionWith (IntMap.unionWith mergeRequesterData) (_multi2Contents_values a) (_multi2Contents_values b)
120+ , _multi2Contents_dict = Dict
121+ }
122+ MyTagType_Multi3 -> IntMap.unionWith (IntMap.unionWith mergeRequesterData) a b
123+ g' :: (forall a. MyTag a -> Entry f a -> Entry f a -> Entry f a) -> Int -> Any -> Any -> Any
124+ g' f rawKey a b =
125+ let k = MyTag rawKey :: MyTag a
126+ fromAny :: Any -> Entry f a
127+ fromAny = unsafeCoerce
128+ toAny :: Entry f a -> Any
129+ toAny = unsafeCoerce
130+ in toAny $ f k (fromAny a) (fromAny b)
131+
132+requesterDataToList :: RequesterData f -> [DSum RequesterDataKey f]
133+requesterDataToList (RequesterData m) = do
134+ k :=> Entry e <- tagMapToList m
135+ case myKeyType k of
136+ MyTagType_Single -> return $ RequesterDataKey_Single k :=> e
137+ MyTagType_Multi -> do
138+ (k', e') <- IntMap.toList e
139+ k'' :=> e'' <- requesterDataToList e'
140+ return $ RequesterDataKey_Multi k k' k'' :=> e''
141+ MyTagType_Multi2 -> case _multi2Contents_dict e of
142+ Dict -> do
143+ (k', e') <- Map.toList $ _multi2Contents_values e
144+ (k'', e'') <- IntMap.toList e'
145+ k''' :=> e''' <- requesterDataToList e''
146+ return $ RequesterDataKey_Multi2 k k' k'' k''' :=> e'''
147+ MyTagType_Multi3 -> do
148+ (k', e') <- IntMap.toList e
149+ (k'', e'') <- IntMap.toList e'
150+ k''' :=> e''' <- requesterDataToList e''
151+ return $ RequesterDataKey_Multi3 k k' k'' k''' :=> e'''
152+
153+singletonTagMap :: forall f a. MyTag a -> f a -> TagMap f
154+singletonTagMap (MyTag k) v = TagMap $ IntMap.singleton k $ (unsafeCoerce :: f a -> Any) v
155+
156+tagMapToList :: forall f. TagMap f -> [DSum MyTag f]
157+tagMapToList (TagMap m) = f <$> IntMap.toList m
158+ where f :: (Int, Any) -> DSum MyTag f
159+ f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v
160+
161+traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g)
162+traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m
163+ where
164+ g :: Int -> Any -> t Any
165+ g k v = (unsafeCoerce :: g a -> Any) <$> f (MyTag k) ((unsafeCoerce :: Any -> f a) v)
166+
167+-- | Runs in reverse to accommodate for the fact that we accumulate it in reverse
168+traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response)
169+traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order
170+ where go :: forall x. MyTag x -> Entry request x -> m (Entry response x)
171+ go k (Entry request) = Entry <$> case myKeyType k of
172+ MyTagType_Single -> f request
173+ MyTagType_Multi -> traverse (traverseRequesterData f) request
174+ MyTagType_Multi2 -> case request of
175+ Multi2Contents { _multi2Contents_values = request', _multi2Contents_dict = Dict } -> do
176+ v <- traverse (traverse (traverseRequesterData f)) request'
177+ pure $ Multi2Contents
178+ { _multi2Contents_values = v
179+ , _multi2Contents_dict = Dict
180+ }
181+ MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request
182+
183+-- | 'traverseRequesterData' with its arguments flipped
184+forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response)
185+forRequesterData r f = traverseRequesterData f r
186+
187+data MyTagType :: * -> * where
188+ MyTagType_Single :: MyTagType (Single a)
189+ MyTagType_Multi :: MyTagType Multi
190+ MyTagType_Multi2 :: MyTagType (Multi2 k)
191+ MyTagType_Multi3 :: MyTagType Multi3
192+
193+myKeyType :: MyTag x -> MyTagType x
194+myKeyType (MyTag k) = case k .&. 0x3 of
195+ 0x0 -> unsafeCoerce MyTagType_Single
196+ 0x1 -> unsafeCoerce MyTagType_Multi
197+ 0x2 -> unsafeCoerce MyTagType_Multi2
198+ 0x3 -> unsafeCoerce MyTagType_Multi3
199+ t -> error $ "Reflex.Requester.Base.myKeyType: no such key type" <> show t
200+
201+data Single a
202+data Multi
203+data Multi2 (k :: * -> *)
204+data Multi3
205+
206+class MyTagTypeOffset x where
207+ myTagTypeOffset :: proxy x -> Int
208+
209+instance MyTagTypeOffset (Single a) where
210+ myTagTypeOffset _ = 0x0
211+
212+instance MyTagTypeOffset Multi where
213+ myTagTypeOffset _ = 0x1
214+
215+instance MyTagTypeOffset (Multi2 k) where
216+ myTagTypeOffset _ = 0x2
217+
218+instance MyTagTypeOffset Multi3 where
219+ myTagTypeOffset _ = 0x3
220+
221+type family EntryContents request a where
222+ EntryContents request (Single a) = request a
223+ EntryContents request Multi = IntMap (RequesterData request)
224+ EntryContents request (Multi2 k) = Multi2Contents k request
225+ EntryContents request Multi3 = IntMap (IntMap (RequesterData request))
226+
227+data Multi2Contents k request = Multi2Contents
228+ { _multi2Contents_dict :: {-# UNPACK #-} !(Dict (GCompare k)) -- This is a Dict instead of an existential context because we only want to use it in certain circumstances
229+ , _multi2Contents_values :: {-# UNPACK #-} !(Map (Some k) (IntMap (RequesterData request)))
230+ }
231+
232+newtype Entry request x = Entry { unEntry :: EntryContents request x }
233+
234+{-# INLINE singleEntry #-}
235+singleEntry :: f a -> Entry f (Single a)
236+singleEntry = Entry
237+
238+{-# INLINE multiEntry #-}
239+multiEntry :: IntMap (RequesterData f) -> Entry f Multi
240+multiEntry = Entry
241+
242+{-# INLINE unMultiEntry #-}
243+unMultiEntry :: Entry f Multi -> IntMap (RequesterData f)
244+unMultiEntry = unEntry
245+
246+-- | 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
247+-- 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
248+newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum)
249+
250+newtype MyTagWrap (f :: * -> *) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum)
251+
252+{-# INLINE castMyTagWrap #-}
253+castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x)
254+castMyTagWrap = coerce
255+
256+instance GEq MyTag where
257+ (MyTag a) `geq` (MyTag b) =
258+ if a == b
259+ then Just $ unsafeCoerce Refl
260+ else Nothing
261+
262+instance GCompare MyTag where
263+ (MyTag a) `gcompare` (MyTag b) =
264+ case a `compare` b of
265+ LT -> GLT
266+ EQ -> unsafeCoerce GEQ
267+ GT -> GGT
268+
269+instance GEq (MyTagWrap f) where
270+ (MyTagWrap a) `geq` (MyTagWrap b) =
271+ if a == b
272+ then Just $ unsafeCoerce Refl
273+ else Nothing
274+
275+instance GCompare (MyTagWrap f) where
276+ (MyTagWrap a) `gcompare` (MyTagWrap b) =
277+ case a `compare` b of
278+ LT -> GLT
279+ EQ -> unsafeCoerce GEQ
280+ GT -> GGT
281+
282+data RequesterState t (request :: * -> *) = RequesterState
283+ { _requesterState_nextMyTag :: {-# UNPACK #-} !Int -- Starts at -4 and goes down by 4 each time, to accommodate two 'type' bits at the bottom
284+ , _requesterState_requests :: ![(Int, Event t Any)]
285+ }
286+
287+-- | A basic implementation of 'Requester'.
288+newtype RequesterT t request (response :: * -> *) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a }
289+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
290+-- MonadAsyncException can't be derived on ghc-8.0.1; we use base-4.9.1 as a proxy for ghc-8.0.2
291+#if MIN_VERSION_base(4,9,1)
292+ , MonadAsyncException
293+#endif
294+ )
295+
296+deriving instance MonadSample t m => MonadSample t (RequesterT t request response m)
297+deriving instance MonadHold t m => MonadHold t (RequesterT t request response m)
298+deriving instance PostBuild t m => PostBuild t (RequesterT t request response m)
299+deriving instance TriggerEvent t m => TriggerEvent t (RequesterT t request response m)
300+
301+instance PrimMonad m => PrimMonad (RequesterT t request response m) where
302+ type PrimState (RequesterT t request response m) = PrimState m
303+ primitive = lift . primitive
304+
305+-- TODO: Monoid and Semigroup can likely be derived once StateT has them.
306+instance (Monoid a, Monad m) => Monoid (RequesterT t request response m a) where
307+ mempty = pure mempty
308+ mappend = liftA2 mappend
309+
310+instance (S.Semigroup a, Monad m) => S.Semigroup (RequesterT t request response m a) where
311+ (<>) = liftA2 (S.<>)
312+
313+
314+-- | Run a 'RequesterT' action. The resulting 'Event' will fire whenever
315+-- requests are made, and responses should be provided in the input 'Event'.
316+-- The 'Tag' keys will be used to return the responses to the same place the
317+-- requests were issued.
318+runRequesterT :: (Reflex t, Monad m)
319+ => RequesterT t request response m a
320+ -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse
321+ -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild
322+runRequesterT (RequesterT a) responses = do
323+ (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $
324+ coerceEvent responses
325+ return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s)
326+
327+-- | Map a function over the request and response of a 'RequesterT'
328+withRequesterT
329+ :: (Reflex t, MonadFix m)
330+ => (forall x. req x -> req' x) -- ^ The function to map over the request
331+ -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response
332+ -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed
333+ -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT'
334+withRequesterT freq frsp child = do
335+ rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp'
336+ (a, req) <- lift $ runRequesterT child rsp
337+ rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $
338+ fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req
339+ return a
340+
341+instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where
342+ type Request (RequesterT t request response m) = request
343+ type Response (RequesterT t request response m) = response
344+ requesting = fmap coerceEvent . responseFromTag . castMyTagWrap <=< tagRequest . (coerceEvent :: Event t (request a) -> Event t (Entry request (Single a)))
345+ requesting_ = void . tagRequest . fmapCheap singleEntry
346+
347+{-# INLINE tagRequest #-}
348+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))
349+tagRequest req = do
350+ old <- RequesterT get
351+ let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x)
352+ t = MyTagWrap n
353+ RequesterT $ put $ RequesterState
354+ { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4
355+ , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old
356+ }
357+ return t
358+
359+{-# INLINE responseFromTag #-}
360+responseFromTag :: forall m t request response x. Monad m => MyTagWrap response (Entry response x) -> RequesterT t request response m (Event t (Entry response x))
361+responseFromTag (MyTagWrap t) = do
362+ responses :: EventSelectorInt t Any <- RequesterT ask
363+ return $ (unsafeCoerce :: Event t Any -> Event t (Entry response x)) $ selectInt responses t
364+
365+instance MonadTrans (RequesterT t request response) where
366+ lift = RequesterT . lift . lift
367+
368+instance MFunctor (RequesterT t request response) where
369+ hoist f = RequesterT . hoist (hoist f) . unRequesterT
370+
371+instance PerformEvent t m => PerformEvent t (RequesterT t request response m) where
372+ type Performable (RequesterT t request response m) = Performable m
373+ performEvent_ = lift . performEvent_
374+ performEvent = lift . performEvent
375+
376+instance MonadRef m => MonadRef (RequesterT t request response m) where
377+ type Ref (RequesterT t request response m) = Ref m
378+ newRef = lift . newRef
379+ readRef = lift . readRef
380+ writeRef r = lift . writeRef r
381+
382+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequesterT t request response m) where
383+ newEventWithTrigger = lift . newEventWithTrigger
384+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
385+
386+instance MonadReader r m => MonadReader r (RequesterT t request response m) where
387+ ask = lift ask
388+ local f (RequesterT a) = RequesterT $ mapStateT (mapReaderT $ local f) a
389+ reader = lift . reader
390+
391+instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where
392+ runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'
393+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental
394+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
395+ traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental
396+ traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove
397+
398+requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x))
399+requesting' = responseFromTag . castMyTagWrap <=< tagRequest
400+
401+{-# INLINABLE runWithReplaceRequesterTWith #-}
402+runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m
403+ , MonadFix m
404+ )
405+ => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))
406+ -> RequesterT t request response m a
407+ -> Event t (RequesterT t request response m b)
408+ -> RequesterT t request response m (a, Event t b)
409+runWithReplaceRequesterTWith f a0 a' = do
410+ rec na' <- numberOccurrencesFrom 1 a'
411+ responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here
412+ let responses' = fanInt responses
413+ ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na'
414+ requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v'
415+ return (result0, fmapCheap (fst . snd) v')
416+
417+{-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-}
418+traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p.
419+ ( Reflex t
420+ , MonadHold t m
421+ , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))
422+ , Patch (p (Event t (IntMap (RequesterData request))))
423+ , Functor p
424+ , MonadFix m
425+ )
426+ => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))
427+ -> IntMap (IntMap.Key, v)
428+ -> Event t (p (IntMap.Key, v))
429+ -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))
430+ )
431+ -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))
432+ -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))
433+ -> (IntMap.Key -> v -> RequesterT t request response m v')
434+ -> IntMap v
435+ -> Event t (p v)
436+ -> RequesterT t request response m (IntMap v', Event t (p v'))
437+traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do
438+ rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
439+ let responses :: EventSelectorInt t (IntMap (RequesterData response))
440+ responses = fanInt $ fmapCheap unpack response
441+ unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response))
442+ unpack = unEntry
443+ pack :: IntMap (IntMap (RequesterData request)) -> Entry request Multi3
444+ pack = Entry
445+ f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v')
446+ f' k (n, v) = do
447+ (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?
448+ return (fmapCheap (IntMap.singleton n) myRequests, result)
449+ ndm' <- numberOccurrencesFrom 1 dm'
450+ (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
451+ let result0 = fmap snd children0
452+ result' = fforCheap children' $ fmap snd
453+ requests0 :: IntMap (Event t (IntMap (RequesterData request)))
454+ requests0 = fmap fst children0
455+ requests' :: Event t (p (Event t (IntMap (RequesterData request))))
456+ requests' = fforCheap children' $ fmap fst
457+ promptRequests :: Event t (IntMap (IntMap (RequesterData request)))
458+ promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
459+ requests <- holdIncremental requests0 requests'
460+ return (result0, result')
461+
462+{-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-}
463+traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'.
464+ ( GCompare k
465+ , Reflex t
466+ , MonadHold t m
467+ , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))
468+ , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))
469+ , MonadFix m
470+ )
471+ => (forall k' v1 v2. GCompare k'
472+ => (forall a. k' a -> v1 a -> m (v2 a))
473+ -> DMap k' v1
474+ -> Event t (p k' v1)
475+ -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))
476+ )
477+ -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)
478+ -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)
479+ -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)
480+ -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))
481+ -> (forall a. k a -> v a -> RequesterT t request response m (v' a))
482+ -> DMap k v
483+ -> Event t (p k v)
484+ -> RequesterT t request response m (DMap k v', Event t (p k v'))
485+traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do
486+ rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here
487+ let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response)))
488+ responses = fanMap $ fmapCheap unpack response
489+ unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response))
490+ unpack = _multi2Contents_values . unEntry
491+ pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k)
492+ pack m = Entry $ Multi2Contents { _multi2Contents_values = m, _multi2Contents_dict = Dict }
493+ f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a)
494+ f' k (Compose (n, v)) = do
495+ (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some k))
496+ return $ Compose (fmapCheap (IntMap.singleton n) myRequests, result)
497+ ndm' <- numberOccurrencesFrom 1 dm'
498+ (children0, children') <- base f' (DMap.map (\v -> Compose (0, v)) dm0) $ fmap (\(n, dm) -> mapPatch (\v -> Compose (n, v)) dm) ndm'
499+ let result0 = DMap.map (snd . getCompose) children0
500+ result' = fforCheap children' $ mapPatch $ snd . getCompose
501+ requests0 :: Map (Some k) (Event t (IntMap (RequesterData request)))
502+ requests0 = weakenDMapWith (fst . getCompose) children0
503+ requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request))))
504+ requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose
505+ promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request)))
506+ promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'
507+ requests <- holdIncremental requests0 requests'
508+ return (result0, result')
509+
510+data Decoder rawResponse response =
511+ forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)
512+
513+matchResponsesWithRequests
514+ :: forall t rawRequest rawResponse request response m.
515+ ( MonadFix m
516+ , MonadHold t m
517+ , Reflex t
518+ )
519+ => (forall a. request a -> (rawRequest, rawResponse -> response a))
520+ -- ^ Given a request (from 'Requester'), produces the wire format of the
521+ -- request and a function used to process the associated response
522+ -> Event t (RequesterData request)
523+ -- ^ The outgoing requests
524+ -> Event t (Int, rawResponse)
525+ -- ^ The incoming responses, tagged by an identifying key
526+ -> m ( Event t (Map Int rawRequest)
527+ , Event t (RequesterData response)
528+ )
529+ -- ^ A map of outgoing wire-format requests and an event of responses keyed
530+ -- by the 'RequesterData' key of the associated outgoing request
531+matchResponsesWithRequests f send recv = matchResponseMapWithRequests f send $ uncurry Map.singleton <$> recv
532+
533+-- | Matches incoming responses with previously-sent requests
534+-- and uses the provided request "decoder" function to process
535+-- incoming responses.
536+matchResponseMapWithRequests
537+ :: forall t rawRequest rawResponse request response m.
538+ ( MonadFix m
539+ , MonadHold t m
540+ , Reflex t
541+ )
542+ => (forall a. request a -> (rawRequest, rawResponse -> response a))
543+ -- ^ Given a request (from 'Requester'), produces the wire format of the
544+ -- request and a function used to process the associated response
545+ -> Event t (RequesterData request)
546+ -- ^ The outgoing requests
547+ -> Event t (Map Int rawResponse)
548+ -- ^ A map of incoming responses, tagged by an identifying key
549+ -> m ( Event t (Map Int rawRequest)
550+ , Event t (RequesterData response)
551+ )
552+ -- ^ A map of outgoing wire-format requests and an event of responses keyed
553+ -- by the 'RequesterData' key of the associated outgoing request
554+matchResponseMapWithRequests f send recv = do
555+ rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing
556+ waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <-
557+ holdIncremental mempty $ leftmost
558+ [ fmap (\(_, outstanding, _) -> outstanding) outgoing
559+ , snd <$> incoming
560+ ]
561+ let outgoing = processOutgoing nextId send
562+ incoming = processIncoming waitingFor recv
563+ return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming)
564+ where
565+ -- Tags each outgoing request with an identifying integer key
566+ -- and returns the next available key, a map of response decoders
567+ -- for requests for which there are outstanding responses, and the
568+ -- raw requests to be sent out.
569+ processOutgoing
570+ :: Behavior t Int
571+ -- The next available key
572+ -> Event t (RequesterData request)
573+ -- The outgoing request
574+ -> Event t ( Int
575+ , PatchMap Int (Decoder rawResponse response)
576+ , Map Int rawRequest )
577+ -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests
578+ processOutgoing nextId out = flip pushAlways out $ \dm -> do
579+ oldNextId <- sample nextId
580+ let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do
581+ n <- get
582+ put $ succ n
583+ let (rawReq, rspF) = f v
584+ return (n, rawReq, Decoder k rspF)
585+ patchWaitingFor = PatchMap $ Map.fromList $
586+ (\(n, _, dec) -> (n, Just dec)) <$> result
587+ toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result
588+ return (newNextId, patchWaitingFor, toSend)
589+ -- Looks up the each incoming raw response in a map of response
590+ -- decoders and returns the decoded response and a patch that can
591+ -- be used to clear the ID of the consumed response out of the queue
592+ -- of expected responses.
593+ processIncoming
594+ :: Incremental t (PatchMap Int (Decoder rawResponse response))
595+ -- A map of outstanding expected responses
596+ -> Event t (Map Int rawResponse)
597+ -- A incoming response paired with its identifying key
598+ -> Event t (RequesterData response, PatchMap Int v)
599+ -- The decoded response and a patch that clears the outstanding responses queue
600+ processIncoming waitingFor inc = flip push inc $ \rspMap -> do
601+ wf <- sample $ currentIncremental waitingFor
602+ let match rawRsp (Decoder k rspF) =
603+ let rsp = rspF rawRsp
604+ in singletonRequesterData k rsp
605+ matches = Map.intersectionWith match rspMap wf
606+ pure $ if Map.null matches then Nothing else Just
607+ (Map.foldl' mergeRequesterData emptyRequesterData matches, PatchMap $ Nothing <$ matches)
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.hs+18−3
@@ -1,5 +1,20 @@
1−module Reflex.Spider ( Spider
2− , SpiderHost (..) --Temporary, until Widget no longer uses unsafePerformIO
3− ) where
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
419
520import Reflex.Spider.Internal
src/Reflex/Spider/Internal.hs+2632−1048
@@ -1,82 +1,210 @@
1−{-# LANGUAGE CPP, ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, LambdaCase #-}
2−module Reflex.Spider.Internal where
3−
4−import Prelude hiding (mapM, mapM_, any, sequence, concat)
5−
6−import qualified Reflex.Class as R
7−import qualified Reflex.Host.Class as R
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 RankNTypes #-}
13+{-# LANGUAGE RoleAnnotations #-}
14+{-# LANGUAGE ScopedTypeVariables #-}
15+{-# LANGUAGE TypeFamilies #-}
16+{-# LANGUAGE TypeOperators #-}
17+{-# LANGUAGE UndecidableInstances #-}
18+{-# LANGUAGE PolyKinds #-}
19+{-# LANGUAGE DeriveFunctor #-}
20+{-# LANGUAGE StandaloneDeriving #-}
21+{-# LANGUAGE InstanceSigs #-}
22+{-# LANGUAGE MultiWayIf #-}
23+
24+#ifdef USE_REFLEX_OPTIMIZER
25+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
26+#endif
27+{-# OPTIONS_GHC -Wunused-binds #-}
28+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
29+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
30+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
831
9−import Data.IORef
10−import System.Mem.Weak
11−import Data.Foldable
12−import Data.Traversable
13−import Control.Monad hiding (mapM, mapM_, forM_, forM, sequence)
14−import Control.Monad.Reader hiding (mapM, mapM_, forM_, forM, sequence)
15−import GHC.Exts
16−import Control.Applicative
17−import Data.Dependent.Map (DMap, DSum (..))
32+#if MIN_VERSION_base(4,10,0)
33+import Control.Applicative (liftA2)
34+#endif
35+import Control.Concurrent
36+import Control.Exception
37+import Control.Monad hiding (forM, forM_, mapM, mapM_)
38+import Control.Monad.Exception
39+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
40+import Control.Monad.Primitive
41+import Control.Monad.Reader.Class
42+import Control.Monad.IO.Class
43+import Control.Monad.ReaderIO
44+import Control.Monad.Ref
45+import Control.Monad.Fail (MonadFail)
46+import qualified Control.Monad.Fail as MonadFail
47+import Data.Align
48+import Data.Coerce
49+import Data.Dependent.Map (DMap)
1850import qualified Data.Dependent.Map as DMap
19−import Data.GADT.Compare
51+import Data.Dependent.Sum (DSum (..))
52+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
53+import qualified Data.FastMutableIntMap as FastMutableIntMap
54+import Data.Foldable hiding (concat, elem, sequence_)
55+import Data.Functor.Constant
2056import Data.Functor.Misc
21−import Data.Maybe
22−import Data.IntMap (IntMap)
23−import qualified Data.IntMap as IntMap
24−import Control.Lens hiding (coerce)
25−import Control.Monad.TypedId
26−import Control.Monad.Ref
27−import Data.Monoid ((<>))
28−
57+import Data.Functor.Product
58+import Data.GADT.Compare
59+import Data.IntMap.Strict (IntMap)
60+import qualified Data.IntMap.Strict as IntMap
61+import Data.IORef
62+import Data.Kind (Type)
63+import Data.Maybe hiding (mapMaybe)
64+import Data.Monoid (mempty, (<>))
65+import Data.Proxy
66+import Data.These
67+import Data.Traversable
68+import Data.Type.Equality ((:~:)(Refl))
69+import Data.Witherable (Filterable, mapMaybe)
70+import GHC.Exts hiding (toList)
71+import GHC.IORef (IORef (..))
72+import GHC.Stack
73+import Reflex.FastWeak
2974import System.IO.Unsafe
75+import System.Mem.Weak
3076import Unsafe.Coerce
31−import Control.Monad.Primitive
77+
78+#ifdef MIN_VERSION_semialign
79+#if MIN_VERSION_these(0,8,0)
80+import Data.These.Combinators (justThese)
81+#endif
82+#if MIN_VERSION_semialign(1,1,0)
83+import Data.Zip (Zip (..))
84+#endif
85+#endif
86+
87+#ifdef DEBUG_CYCLES
88+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
89+#endif
90+
91+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
92+import qualified Data.List.NonEmpty as NonEmpty
93+import Data.Tree (Forest, Tree (..), drawForest)
94+import Data.List (isPrefixOf)
95+
96+import Data.FastWeakBag (FastWeakBag, FastWeakBagTicket)
97+import qualified Data.FastWeakBag as FastWeakBag
98+
99+import Data.Reflection
100+import Data.Some (Some(Some))
101+import Data.Type.Coercion
102+import Data.Profunctor.Unsafe ((#.), (.#))
103+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
104+import qualified Data.WeakBag as WeakBag
105+import qualified Reflex.Class
106+import qualified Reflex.Class as R
107+import qualified Reflex.Host.Class
108+import Reflex.NotReady.Class
109+import Data.Patch
110+import qualified Data.Patch.DMapWithMove as PatchDMapWithMove
111+import Reflex.PerformEvent.Base (PerformEventT)
112+
113+#ifdef DEBUG_TRACE_EVENTS
114+import qualified Data.ByteString.Char8 as BS8
115+import System.IO (stderr)
116+import Data.List (isPrefixOf)
117+#endif
118+
119+-- TODO stdout might not be the best channel for debug output
120+debugStrLn :: String -> IO ()
121+debugStrLn = putStrLn
122+
123+#ifdef DEBUG_TRACE_EVENTS
124+withStackOneLine :: (BS8.ByteString -> a) -> a
125+withStackOneLine expr = unsafePerformIO $ do
126+ stack <- currentCallStack
127+ return (expr . BS8.pack . unwords . dropInternal . reverse $ stack)
128+ where dropInternal = filterStack "Reflex.Spider.Internal"
129+
130+#endif
32131
33132debugPropagate :: Bool
34133
35134debugInvalidateHeight :: Bool
36135
37−#ifdef DEBUG
136+debugInvalidate :: Bool
38137
138+#ifdef DEBUG
39139#define DEBUG_NODEIDS
40140
141+#ifdef DEBUG_TRACE_PROPAGATION
41142debugPropagate = True
143+#else
144+debugPropagate = False
145+#endif
42146
147+#ifdef DEBUG_TRACE_HEIGHT
43148debugInvalidateHeight = True
149+#else
150+debugInvalidateHeight = False
151+#endif
152+
153+#ifdef DEBUG_TRACE_INVALIDATION
154+debugInvalidate = True
155+#else
156+debugInvalidate = False
157+#endif
44158
45159class HasNodeId a where
46160 getNodeId :: a -> Int
47161
48−instance HasNodeId (Hold a) where
49− getNodeId = holdNodeId
162+instance HasNodeId (CacheSubscribed x a) where
163+ getNodeId = _cacheSubscribed_nodeId
50164
51−instance HasNodeId (PushSubscribed a b) where
52− getNodeId = pushSubscribedNodeId
165+instance HasNodeId (FanInt x a) where
166+ getNodeId = _fanInt_nodeId
53167
54−instance HasNodeId (SwitchSubscribed a) where
55− getNodeId = switchSubscribedNodeId
168+instance HasNodeId (Hold x p) where
169+ getNodeId = holdNodeId
56170
57−instance HasNodeId (MergeSubscribed a) where
58− getNodeId = mergeSubscribedNodeId
171+instance HasNodeId (SwitchSubscribed x a) where
172+ getNodeId = switchSubscribedNodeId
59173
60−instance HasNodeId (FanSubscribed a) where
174+instance HasNodeId (FanSubscribed x v a) where
61175 getNodeId = fanSubscribedNodeId
62176
63−instance HasNodeId (CoincidenceSubscribed a) where
177+instance HasNodeId (CoincidenceSubscribed x a) where
64178 getNodeId = coincidenceSubscribedNodeId
65179
66−instance HasNodeId (RootSubscribed a) where
180+instance HasNodeId (RootSubscribed x a) where
67181 getNodeId = rootSubscribedNodeId
68182
183+instance HasNodeId (Pull x a) where
184+ getNodeId = pullNodeId
185+
186+{-# INLINE showNodeId #-}
69187showNodeId :: HasNodeId a => a -> String
70−showNodeId = ("#"<>) . show . getNodeId
188+showNodeId = showNodeId' . getNodeId
189+
190+showNodeId' :: Int -> String
191+showNodeId' = ("#"<>) . show
192+
71193
72194#else
73195
74196debugPropagate = False
75−
76197debugInvalidateHeight = False
198+debugInvalidate = False
77199
200+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
201+{-# INLINE showNodeId #-}
78202showNodeId :: a -> String
79−showNodeId = const ""
203+showNodeId _ = ""
204+
205+{-# INLINE showNodeId' #-}
206+showNodeId' :: Int -> String
207+showNodeId' _ = ""
80208
81209#endif
82210
@@ -85,873 +213,1632 @@ showNodeId = const ""
85213nextNodeIdRef :: IORef Int
86214nextNodeIdRef = unsafePerformIO $ newIORef 1
87215
88−{-# NOINLINE unsafeNodeId #-}
89−unsafeNodeId :: a -> Int
90−unsafeNodeId a = unsafePerformIO $ do
91− touch a
92− atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
216+newNodeId :: IO Int
217+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
218+#endif
219+
220+--------------------------------------------------------------------------------
221+-- EventSubscription
222+--------------------------------------------------------------------------------
223+
224+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
225+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
226+data EventSubscription x = EventSubscription
227+ { _eventSubscription_unsubscribe :: !(IO ())
228+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
229+ }
230+
231+unsubscribe :: EventSubscription x -> IO ()
232+unsubscribe (EventSubscription u _) = u
233+
234+--------------------------------------------------------------------------------
235+-- Event
236+--------------------------------------------------------------------------------
237+
238+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
239+
240+{-# INLINE subscribeAndRead #-}
241+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
242+subscribeAndRead = unEvent
243+
244+{-# RULES
245+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
246+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
247+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
248+ #-}
249+
250+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
251+-- caching; if the computation function is very cheap, this is (much) more
252+-- efficient than 'push'
253+{-# INLINE [1] pushCheap #-}
254+pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
255+pushCheap !f e = Event $ \sub -> do
256+ (subscription, occ) <- subscribeAndRead e $ debugSubscriber' "push" $ sub
257+ { subscriberPropagate = \a -> do
258+ mb <- f a
259+ mapM_ (subscriberPropagate sub) mb
260+ }
261+ occ' <- join <$> mapM f occ
262+ return (subscription, occ')
263+
264+-- | A subscriber that never triggers other 'Event's
265+{-# INLINE terminalSubscriber #-}
266+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
267+terminalSubscriber p = Subscriber
268+ { subscriberPropagate = p
269+ , subscriberInvalidateHeight = \_ -> return ()
270+ , subscriberRecalculateHeight = \_ -> return ()
271+ }
272+
273+-- | Subscribe to an Event only for the duration of one occurrence
274+{-# INLINE subscribeAndReadHead #-}
275+subscribeAndReadHead :: HasSpiderTimeline x => Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
276+subscribeAndReadHead e sub = do
277+ subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
278+ (subscription, occ) <- subscribeAndRead e $ debugSubscriber' "head" $ sub
279+ { subscriberPropagate = \a -> do
280+ liftIO $ unsubscribe =<< readIORef subscriptionRef
281+ subscriberPropagate sub a
282+ }
283+ liftIO $ case occ of
284+ Nothing -> writeIORef subscriptionRef $! subscription
285+ Just _ -> unsubscribe subscription
286+ return (subscription, occ)
287+
288+--TODO: Make this lazy in its input event
289+headE :: (MonadIO m, Defer (SomeMergeInit x) m, HasSpiderTimeline x) => Event x a -> m (Event x a)
290+headE originalE = do
291+ parent <- liftIO $ newIORef $ Just originalE
292+ defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
293+ let clearParent = liftIO $ writeIORef parent Nothing
294+ (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ const clearParent
295+ when (isJust occ) clearParent
296+ return $ Event $ \sub ->
297+ liftIO (readIORef parent) >>= \case
298+ Nothing -> subscribeAndReadNever
299+ Just e -> subscribeAndReadHead e sub
300+
301+data CacheSubscribed x a
302+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
303+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
304+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
305+#ifdef DEBUG_NODEIDS
306+ , _cacheSubscribed_nodeId :: {-# UNPACK #-} !Int
307+#endif
308+ }
309+
310+nowSpiderEventM :: (HasSpiderTimeline x) => EventM x (R.Event (SpiderTimeline x) ())
311+nowSpiderEventM =
312+ SpiderEvent <$> now
313+
314+now :: (MonadIO m, Defer (Some Clear) m, HasSpiderTimeline x
315+ ) => m (Event x ())
316+now = do
317+ nowOrNot <- liftIO $ newIORef $ Just ()
318+ scheduleClear nowOrNot
319+ return . Event $ \_ -> do
320+ occ <- liftIO . readIORef $ nowOrNot
321+ return ( EventSubscription (return ()) eventSubscribedNow
322+ , occ
323+ )
324+
325+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
326+-- repeatedly
327+--
328+--TODO: Try a caching strategy where we subscribe directly to the parent when
329+--there's only one subscriber, and then build our own FastWeakBag only when a second
330+--subscriber joins
331+{-# NOINLINE [0] cacheEvent #-}
332+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
333+cacheEvent e =
334+#ifdef DEBUG_TRACE_EVENTS
335+ withStackOneLine $ \callSite -> Event $
336+#else
337+ Event $
338+#endif
339+ unsafePerformIO $ do
340+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
341+ <- newIORef emptyFastWeak
342+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
343+#ifdef DEBUG_TRACE_EVENTS
344+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
345+#endif
346+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
347+ Just subscribedTicket -> return subscribedTicket
348+ Nothing -> do
349+#ifdef DEBUG_NODEIDS
350+ nodeId <- liftIO newNodeId
351+#endif
352+ subscribers <- liftIO FastWeakBag.empty
353+ occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
354+#ifdef DEBUG_NODEIDS
355+ (parentSub, occ) <- subscribeAndRead e $ debugSubscriber' ("cacheEvent" <> showNodeId' nodeId) $ Subscriber
356+#else
357+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
358+#endif
359+ { subscriberPropagate = \a -> do
360+ liftIO $ writeIORef occRef (Just a)
361+ scheduleClear occRef
362+ propagateFast a subscribers
363+ , subscriberInvalidateHeight = FastWeakBag.traverse_ subscribers . invalidateSubscriberHeight
364+ , subscriberRecalculateHeight = FastWeakBag.traverse_ subscribers . recalculateSubscriberHeight
365+ }
366+ when (isJust occ) $ do
367+ liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
368+ scheduleClear occRef
369+ let !subscribed = CacheSubscribed
370+ { _cacheSubscribed_subscribers = subscribers
371+ , _cacheSubscribed_parent = parentSub
372+ , _cacheSubscribed_occurrence = occRef
373+#ifdef DEBUG_NODEIDS
374+ , _cacheSubscribed_nodeId = nodeId
375+#endif
376+ }
377+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
378+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
379+ return subscribedTicket
380+ liftIO $ cacheSubscription sub mSubscribedRef subscribedTicket
381+
382+cacheSubscription :: Subscriber x a -> IORef (FastWeak (CacheSubscribed x a))
383+ -> FastWeakTicket (CacheSubscribed x a) -> IO (EventSubscription x, Maybe a)
384+cacheSubscription sub mSubscribedRef subscribedTicket = do
385+ subscribed <- getFastWeakTicketValue subscribedTicket
386+ ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
387+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
388+
389+ let parentSub = _cacheSubscribed_parent subscribed
390+ es = EventSubscription
391+ { _eventSubscription_unsubscribe = do
392+ FastWeakBag.remove ticket
393+
394+ isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
395+ when isEmpty $ do
396+ writeIORef mSubscribedRef emptyFastWeak
397+ unsubscribe parentSub
398+ touch ticket
399+ touch subscribedTicket
400+ , _eventSubscription_subscribed = EventSubscribed
401+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub
402+ , eventSubscribedRetained = toAny subscribedTicket
403+#ifdef DEBUG_CYCLES
404+ , eventSubscribedGetParents = return [_eventSubscription_subscribed parentSub]
405+ , eventSubscribedHasOwnHeightRef = False
406+ , eventSubscribedWhoCreated = whoCreatedIORef mSubscribedRef
407+#endif
408+ }
409+ }
410+ return (es, occ)
411+
412+
413+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
414+subscribe e s = fst <$> subscribeAndRead e s
415+
416+{-# INLINE wrap #-}
417+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
418+wrap tag getSpecificSubscribed sub = do
419+ (sln, subd, occ) <- getSpecificSubscribed sub
420+ let es = tag subd
421+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
422+
423+eventRoot :: (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Event x a
424+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
425+
426+subscribeAndReadNever :: EventM x (EventSubscription x, Maybe a)
427+subscribeAndReadNever = return (EventSubscription (return ()) eventSubscribedNever, Nothing)
428+
429+eventNever :: Event x a
430+eventNever = Event $ const subscribeAndReadNever
431+
432+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
433+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
434+
435+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
436+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
437+
438+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
439+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
440+
441+eventHold :: Hold x p -> Event x p
442+eventHold !h = Event $ subscribeHoldEvent h
443+
444+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
445+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
446+
447+{-# INLINE subscribeCoincidenceInner #-}
448+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
449+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
450+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
451+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
452+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
453+ let height = max innerHeight outerHeight
454+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
455+ return (innerOcc, height, innerSubd)
456+
457+--------------------------------------------------------------------------------
458+-- Subscriber
459+--------------------------------------------------------------------------------
460+
461+data Subscriber x a = Subscriber
462+ { subscriberPropagate :: !(a -> EventM x ())
463+ , subscriberInvalidateHeight :: !(Height -> IO ())
464+ , subscriberRecalculateHeight :: !(Height -> IO ())
465+ }
466+
467+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
468+newSubscriberHold h = return $ Subscriber
469+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
470+ , subscriberInvalidateHeight = \_ -> return ()
471+ , subscriberRecalculateHeight = \_ -> return ()
472+ }
473+
474+newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
475+newSubscriberFan subscribed = debugSubscriber ("SubscriberFan " <> showNodeId subscribed) $ Subscriber
476+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
477+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
478+ tracePropagate (Proxy :: Proxy x) $ show (DMap.size subs) <> " keys subscribed, " <> show (DMap.size a) <> " keys firing"
479+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
480+ scheduleClear $ fanSubscribedOccurrence subscribed
481+ let f _ (Pair v subsubs) = do
482+ propagate v $ _fanSubscribedChildren_list subsubs
483+ return $ Constant ()
484+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
485+ return ()
486+ , subscriberInvalidateHeight = \old -> do
487+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
488+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
489+ , subscriberRecalculateHeight = \new -> do
490+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
491+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
492+ }
493+
494+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
495+newSubscriberSwitch subscribed = debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $ Subscriber
496+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
497+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
498+ scheduleClear $ switchSubscribedOccurrence subscribed
499+ propagate a $ switchSubscribedSubscribers subscribed
500+ , subscriberInvalidateHeight = \_ -> do
501+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
502+ when (oldHeight /= invalidHeight) $ do
503+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
504+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
505+ , subscriberRecalculateHeight = (`updateSwitchHeight` subscribed)
506+ }
507+
508+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
509+newSubscriberCoincidenceOuter subscribed = debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $ Subscriber
510+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
511+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
512+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
513+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
514+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
515+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
516+
517+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
518+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
519+ case occ of
520+ Nothing ->
521+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
522+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
523+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
524+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
525+ Just o -> do -- Since it's already firing, no need to adjust height
526+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
527+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
528+ propagate o $ coincidenceSubscribedSubscribers subscribed
529+ , subscriberInvalidateHeight = \_ -> invalidateCoincidenceHeight subscribed
530+ , subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed
531+ }
532+
533+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
534+newSubscriberCoincidenceInner subscribed = debugSubscriber ("SubscriberCoincidenceInner" <> showNodeId subscribed) $ Subscriber
535+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
536+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
537+ case occ of
538+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
539+ Nothing -> do
540+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
541+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
542+ propagate a $ coincidenceSubscribedSubscribers subscribed
543+ , subscriberInvalidateHeight = \_ -> invalidateCoincidenceHeight subscribed
544+ , subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed
545+ }
546+
547+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
548+invalidateSubscriberHeight = flip subscriberInvalidateHeight
549+
550+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
551+recalculateSubscriberHeight = flip subscriberRecalculateHeight
552+
553+-- | Propagate everything at the current height
554+propagate :: forall x a. HasSpiderTimeline x => a -> WeakBag (Subscriber x a) -> EventM x ()
555+propagate a subscribers = withIncreasedDepth (Proxy::Proxy x) $
556+ -- 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
557+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
558+ WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
559+
560+-- | Propagate everything at the current height
561+propagateFast :: forall x a. HasSpiderTimeline x => a -> FastWeakBag (Subscriber x a) -> EventM x ()
562+propagateFast a subscribers = withIncreasedDepth (Proxy::Proxy x) $
563+ -- 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
564+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
565+ FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
566+
567+--------------------------------------------------------------------------------
568+-- EventSubscribed
569+--------------------------------------------------------------------------------
570+
571+toAny :: a -> Any
572+toAny = unsafeCoerce
573+
574+-- Why do we use Any here, instead of just giving eventSubscribedRetained an
575+-- existential type? Sadly, GHC does not currently know how to unbox types
576+-- with existentially quantified fields. So instead we just coerce values
577+-- to type Any on the way in. Since we never coerce them back, this is
578+-- perfectly safe.
579+data EventSubscribed x = EventSubscribed
580+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
581+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
582+#ifdef DEBUG_CYCLES
583+ , eventSubscribedGetParents :: !(IO [EventSubscribed x]) -- For debugging loops
584+ , eventSubscribedHasOwnHeightRef :: !Bool
585+ , eventSubscribedWhoCreated :: !(IO [String])
93586#endif
587+ }
588+
589+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
590+eventSubscribedRoot !r = EventSubscribed
591+ { eventSubscribedHeightRef = zeroRef
592+ , eventSubscribedRetained = toAny r
593+#ifdef DEBUG_CYCLES
594+ , eventSubscribedGetParents = return []
595+ , eventSubscribedHasOwnHeightRef = False
596+ , eventSubscribedWhoCreated = return ["root"]
597+#endif
598+ }
599+
600+eventSubscribedNever :: EventSubscribed x
601+eventSubscribedNever = EventSubscribed
602+ { eventSubscribedHeightRef = zeroRef
603+ , eventSubscribedRetained = toAny ()
604+#ifdef DEBUG_CYCLES
605+ , eventSubscribedGetParents = return []
606+ , eventSubscribedHasOwnHeightRef = False
607+ , eventSubscribedWhoCreated = return ["never"]
608+#endif
609+ }
610+eventSubscribedNow :: EventSubscribed x
611+eventSubscribedNow = EventSubscribed
612+ { eventSubscribedHeightRef = zeroRef
613+ , eventSubscribedRetained = toAny ()
614+#ifdef DEBUG_CYCLES
615+ , eventSubscribedGetParents = return []
616+ , eventSubscribedHasOwnHeightRef = False
617+ , eventSubscribedWhoCreated = return ["now"]
618+#endif
619+ }
620+
621+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
622+eventSubscribedFan !subscribed = EventSubscribed
623+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
624+ , eventSubscribedRetained = toAny subscribed
625+#ifdef DEBUG_CYCLES
626+ , eventSubscribedGetParents = return [_eventSubscription_subscribed $ fanSubscribedParent subscribed]
627+ , eventSubscribedHasOwnHeightRef = False
628+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
629+#endif
630+ }
631+
632+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
633+eventSubscribedSwitch !subscribed = EventSubscribed
634+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
635+ , eventSubscribedRetained = toAny subscribed
636+#ifdef DEBUG_CYCLES
637+ , eventSubscribedGetParents = do
638+ s <- readIORef $ switchSubscribedCurrentParent subscribed
639+ return [_eventSubscription_subscribed s]
640+ , eventSubscribedHasOwnHeightRef = True
641+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
642+#endif
643+ }
644+
645+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
646+eventSubscribedCoincidence !subscribed = EventSubscribed
647+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
648+ , eventSubscribedRetained = toAny subscribed
649+#ifdef DEBUG_CYCLES
650+ , eventSubscribedGetParents = do
651+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
652+ let outerParent = _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
653+ innerParents = maybeToList $ innerSubscription
654+ return $ outerParent : innerParents
655+ , eventSubscribedHasOwnHeightRef = True
656+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
657+#endif
658+ }
659+
660+getEventSubscribedHeight :: EventSubscribed x -> IO Height
661+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
662+
663+#ifdef DEBUG_CYCLES
664+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
665+whoCreatedEventSubscribed = eventSubscribedWhoCreated
666+
667+walkInvalidHeightParents :: EventSubscribed x -> IO [EventSubscribed x]
668+walkInvalidHeightParents s0 = do
669+ subscribers <- flip execStateT mempty $ ($ s0) $ fix $ \loop s -> do
670+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
671+ when (h == invalidHeight) $ do
672+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
673+ modify (s :)
674+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
675+ forM_ subscribers $ \s -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
676+ return subscribers
677+#endif
678+
679+{-# INLINE subscribeHoldEvent #-}
680+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
681+subscribeHoldEvent = subscribeAndRead . holdEvent
682+
683+--------------------------------------------------------------------------------
684+-- Behavior
685+--------------------------------------------------------------------------------
686+
687+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
688+
689+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
690+behaviorHold !h = Behavior $ readHoldTracked h
691+
692+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
693+behaviorHoldIdentity = behaviorHold
694+
695+behaviorConst :: a -> Behavior x a
696+behaviorConst !a = Behavior $ return a
697+
698+behaviorPull :: Pull x a -> Behavior x a
699+behaviorPull !p = Behavior $ do
700+ val <- liftIO $ readIORef $ pullValue p
701+ case val of
702+ Just subscribed -> do
703+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
704+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
705+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
706+ return $ pullSubscribedValue subscribed
707+ Nothing -> do
708+ i <- liftIO $ newInvalidatorPull p
709+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
710+ parentsRef <- liftIO $ newIORef []
711+ holdInits <- askBehaviorHoldInits
712+ a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
713+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
714+ parents <- liftIO $ readIORef parentsRef
715+ let subscribed = PullSubscribed
716+ { pullSubscribedValue = a
717+ , pullSubscribedInvalidators = invsRef
718+ , pullSubscribedOwnInvalidator = i
719+ , pullSubscribedParents = parents
720+ }
721+ liftIO $ writeIORef (pullValue p) $ Just subscribed
722+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
723+ return a
724+
725+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
726+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
727+
728+{-# INLINE readHoldTracked #-}
729+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
730+readHoldTracked h = do
731+ result <- liftIO $ readIORef $ holdValue h
732+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
733+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
734+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
735+ return result
736+
737+{-# INLINABLE readBehaviorUntracked #-}
738+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
739+readBehaviorUntracked b = do
740+ holdInits <- getDeferralQueue
741+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
742+
743+--------------------------------------------------------------------------------
744+-- Dynamic
745+--------------------------------------------------------------------------------
746+
747+type DynamicS x p = Dynamic x (PatchTarget p) p
748+
749+data Dynamic x target p = Dynamic
750+ { dynamicCurrent :: !(Behavior x target)
751+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
752+ }
753+
754+deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
755+
756+
757+
758+
759+dynamicHold :: Hold x p -> DynamicS x p
760+dynamicHold !h = Dynamic
761+ { dynamicCurrent = behaviorHold h
762+ , dynamicUpdated = eventHold h
763+ }
764+
765+dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
766+dynamicHoldIdentity = dynamicHold
767+
768+dynamicConst :: PatchTarget p -> DynamicS x p
769+dynamicConst !a = Dynamic
770+ { dynamicCurrent = behaviorConst a
771+ , dynamicUpdated = eventNever
772+ }
773+
774+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
775+dynamicDyn !d = Dynamic
776+ { dynamicCurrent = behaviorDyn d
777+ , dynamicUpdated = eventDyn d
778+ }
779+
780+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
781+dynamicDynIdentity = dynamicDyn
782+
783+--------------------------------------------------------------------------------
784+-- Combinators
785+--------------------------------------------------------------------------------
94786
95−--TODO: Figure out why certain things are not 'representational', then make them representational so we can use coerce
96787--type role Hold representational
97−data Hold a
98− = Hold { holdValue :: !(IORef a)
99− , holdInvalidators :: !(IORef [Weak Invalidator])
100− -- We need to use 'Any' for the next two things, because otherwise Hold inherits a nominal role for its 'a' parameter, and we want to be able to use 'coerce'
101− , holdSubscriber :: !(IORef Any) -- Keeps its subscription alive; for some reason, a regular (or strict) reference to the Subscriber itself wasn't working, so had to use an IORef
102− , holdParent :: !(IORef Any) -- Keeps its parent alive (will be undefined until the hold is initialized --TODO: Probably shouldn't be an IORef
788+data Hold x p
789+ = Hold { holdValue :: !(IORef (PatchTarget p))
790+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
791+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
792+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
103793#ifdef DEBUG_NODEIDS
104794 , holdNodeId :: Int
105795#endif
106796 }
107797
108−data EventEnv
109− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment])
110− , eventEnvHoldInits :: !(IORef [SomeHoldInit])
111− , eventEnvClears :: !(IORef [SomeMaybeIORef])
112− , eventEnvCurrentHeight :: !(IORef Int)
113− , eventEnvCoincidenceInfos :: !(IORef [SomeCoincidenceInfo])
114− , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge]))
798+-- | A statically allocated 'SpiderTimeline'
799+data Global
800+
801+{-# NOINLINE globalSpiderTimelineEnv #-}
802+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
803+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
804+
805+-- | Stores all global data relevant to a particular Spider timeline; only one
806+-- value should exist for each type @x@
807+newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
808+-- We implement SpiderTimelineEnv with a newtype wrapper so
809+-- we can get the coercions we want safely.
810+type role SpiderTimelineEnv nominal
811+
812+data SpiderTimelineEnv' x = SpiderTimelineEnv
813+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
814+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
815+#ifdef DEBUG
816+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
817+#endif
818+ }
819+type role SpiderTimelineEnv' phantom
820+
821+instance Eq (SpiderTimelineEnv x) where
822+ _ == _ = True -- Since only one exists of each type
823+
824+instance GEq SpiderTimelineEnv where
825+ a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
826+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
827+ else Nothing
828+
829+data EventEnv x
830+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
831+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
832+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
833+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
834+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
835+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
836+ , eventEnvIntClears :: !(IORef [Some IntClear])
837+ , eventEnvRootClears :: !(IORef [Some RootClear])
838+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
839+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
840+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
115841 }
116842
117−runEventM :: EventM a -> EventEnv -> IO a
118−runEventM = runReaderT . unEventM
843+{-# INLINE runEventM #-}
844+runEventM :: EventM x a -> IO a
845+runEventM = unEventM
119846
120−askToAssignRef :: EventM (IORef [SomeAssignment])
121−askToAssignRef = EventM $ asks eventEnvAssignments
847+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
848+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
122849
123−askHoldInitRef :: EventM (IORef [SomeHoldInit])
124−askHoldInitRef = EventM $ asks eventEnvHoldInits
850+class MonadIO m => Defer a m where
851+ getDeferralQueue :: m (IORef [a])
125852
126−getCurrentHeight :: EventM Int
127−getCurrentHeight = EventM $ do
128− heightRef <- asks eventEnvCurrentHeight
129− liftIO $ readIORef heightRef
853+{-# INLINE defer #-}
854+defer :: Defer a m => a -> m ()
855+defer a = do
856+ q <- getDeferralQueue
857+ liftIO $ modifyIORef' q (a:)
130858
131−putCurrentHeight :: Int -> EventM ()
132−putCurrentHeight h = EventM $ do
133− heightRef <- asks eventEnvCurrentHeight
134− liftIO $ writeIORef heightRef h
859+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
860+ {-# INLINE getDeferralQueue #-}
861+ getDeferralQueue = asksEventEnv eventEnvAssignments
135862
136−scheduleClear :: IORef (Maybe a) -> EventM ()
137−scheduleClear r = EventM $ do
138− clears <- asks eventEnvClears
139− liftIO $ modifyIORef' clears (SomeMaybeIORef r :)
863+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
864+ {-# INLINE getDeferralQueue #-}
865+ getDeferralQueue = asksEventEnv eventEnvHoldInits
140866
141−scheduleMerge :: Int -> MergeSubscribed a -> EventM ()
142−scheduleMerge height subscribed = EventM $ do
143− delayedRef <- asks eventEnvDelayedMerges
144− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) height [DelayedMerge subscribed]
867+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
868+ {-# INLINE getDeferralQueue #-}
869+ getDeferralQueue = asksEventEnv eventEnvDynInits
145870
146−emitCoincidenceInfo :: SomeCoincidenceInfo -> EventM ()
147−emitCoincidenceInfo sci = EventM $ do
148− ciRef <- asks eventEnvCoincidenceInfos
149− liftIO $ modifyIORef' ciRef (sci:)
871+instance Defer (SomeHoldInit x) (BehaviorM x) where
872+ {-# INLINE getDeferralQueue #-}
873+ getDeferralQueue = BehaviorM $ asks snd
874+
875+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
876+ {-# INLINE getDeferralQueue #-}
877+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
878+
879+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
880+ {-# INLINE getDeferralQueue #-}
881+ getDeferralQueue = asksEventEnv eventEnvMergeInits
882+
883+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
884+ getCurrentHeight :: m Height
885+ scheduleMerge :: Height -> EventM x () -> m ()
886+
887+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
888+ {-# INLINE getCurrentHeight #-}
889+ getCurrentHeight = do
890+ heightRef <- asksEventEnv eventEnvCurrentHeight
891+ liftIO $ readIORef heightRef
892+ {-# INLINE scheduleMerge #-}
893+ scheduleMerge height subscribed = do
894+ delayedRef <- asksEventEnv eventEnvDelayedMerges
895+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
896+
897+class HasSpiderTimeline x where
898+ -- | Retrieve the current SpiderTimelineEnv
899+ spiderTimeline :: SpiderTimelineEnv x
900+
901+instance HasSpiderTimeline Global where
902+ spiderTimeline = globalSpiderTimelineEnv
903+
904+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
905+putCurrentHeight h = do
906+ heightRef <- asksEventEnv eventEnvCurrentHeight
907+ liftIO $ writeIORef heightRef $! h
908+
909+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
910+ {-# INLINE getDeferralQueue #-}
911+ getDeferralQueue = asksEventEnv eventEnvClears
912+
913+{-# INLINE scheduleClear #-}
914+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
915+scheduleClear r = defer $ Some $ Clear r
916+
917+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
918+ {-# INLINE getDeferralQueue #-}
919+ getDeferralQueue = asksEventEnv eventEnvIntClears
920+
921+{-# INLINE scheduleIntClear #-}
922+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
923+scheduleIntClear r = defer $ Some $ IntClear r
924+
925+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
926+ {-# INLINE getDeferralQueue #-}
927+ getDeferralQueue = asksEventEnv eventEnvRootClears
928+
929+{-# INLINE scheduleRootClear #-}
930+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
931+scheduleRootClear r = defer $ Some $ RootClear r
932+
933+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
934+ {-# INLINE getDeferralQueue #-}
935+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
150936
151937-- Note: hold cannot examine its event until after the phase is over
152−hold :: a -> Event a -> EventM (Behavior a)
938+{-# INLINE [1] hold #-}
939+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
153940hold v0 e = do
154− holdInitRef <- askHoldInitRef
155− liftIO $ do
156− valRef <- newIORef v0
157− invsRef <- newIORef []
158− parentRef <- newIORef $ error "hold not yet initialized (parent)"
159− subscriberRef <- newIORef $ error "hold not yet initialized (subscriber)"
160− let h = Hold
161− { holdValue = valRef
162− , holdInvalidators = invsRef
163− , holdSubscriber = subscriberRef
164− , holdParent = parentRef
941+ valRef <- liftIO $ newIORef v0
942+ invsRef <- liftIO $ newIORef []
943+ parentRef <- liftIO $ newIORef Nothing
165944#ifdef DEBUG_NODEIDS
166− , holdNodeId = unsafeNodeId (v0, e)
945+ nodeId <- liftIO newNodeId
167946#endif
168− }
169− !s = SubscriberHold h
170− writeIORef subscriberRef $ unsafeCoerce s
171− modifyIORef' holdInitRef (SomeHoldInit e h :)
172− return $ BehaviorHold h
173−
174−subscribeHold :: Event a -> Hold a -> EventM ()
175−subscribeHold e h = do
176− toAssignRef <- askToAssignRef
177− !s <- liftIO $ liftM unsafeCoerce $ readIORef $ holdSubscriber h -- This must be performed strictly so that the weak pointer points at the actual item
178− ws <- liftIO $ mkWeakPtrWithDebug s "holdSubscriber"
179− subd <- subscribe e $ WeakSubscriberSimple ws
180− liftIO $ writeIORef (holdParent h) $ unsafeCoerce subd
181− occ <- liftIO $ getEventSubscribedOcc subd
182− case occ of
183− Nothing -> return ()
184− Just o -> liftIO $ modifyIORef' toAssignRef (SomeAssignment h o :)
947+ let h = Hold
948+ { holdValue = valRef
949+ , holdInvalidators = invsRef
950+ , holdEvent = e
951+ , holdParent = parentRef
952+#ifdef DEBUG_NODEIDS
953+ , holdNodeId = nodeId
954+#endif
955+ }
956+ defer $ SomeHoldInit h
957+ return h
958+
959+{-# INLINE getHoldEventSubscription #-}
960+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
961+getHoldEventSubscription h = do
962+ ep <- liftIO $ readIORef $ holdParent h
963+ case ep of
964+ Just subd -> return subd
965+ Nothing -> do
966+ let e = holdEvent h
967+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
968+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
969+ liftIO $ writeIORef subscriptionRef $! subscription
970+ case occ of
971+ Nothing -> return ()
972+ Just o -> do
973+ old <- liftIO $ readIORef $ holdValue h
974+ case apply o old of
975+ Nothing -> return ()
976+ Just new -> do
977+ -- Need to evaluate these so that we don't retain the Hold itself
978+ v <- liftIO $ evaluate $ holdValue h
979+ i <- liftIO $ evaluate $ holdInvalidators h
980+ defer $ SomeAssignment v i new
981+ liftIO $ writeIORef (holdParent h) $ Just subscription
982+ return subscription
983+
984+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
185985
186−--type role BehaviorM representational
187986-- BehaviorM can sample behaviors
188−newtype BehaviorM a = BehaviorM { unBehaviorM :: ReaderT (Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed])) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
987+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
988+ deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
989+
990+instance Monad (BehaviorM x) where
991+ {-# INLINE (>>=) #-}
992+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
993+ {-# INLINE (>>) #-}
994+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
995+ {-# INLINE return #-}
996+ return x = BehaviorM $ return x
997+#if !MIN_VERSION_base(4,13,0)
998+ {-# INLINE fail #-}
999+ fail s = BehaviorM $ fail s
1000+#endif
1891001
190−data BehaviorSubscribed a
191− = BehaviorSubscribedHold (Hold a)
192− | BehaviorSubscribedPull (PullSubscribed a)
1002+data BehaviorSubscribed x a
1003+ = forall p. BehaviorSubscribedHold (Hold x p)
1004+ | BehaviorSubscribedPull (PullSubscribed x a)
1931005
194−data SomeBehaviorSubscribed = forall a. SomeBehaviorSubscribed (BehaviorSubscribed a)
1006+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
1951007
1961008--type role PullSubscribed representational
197−data PullSubscribed a
1009+data PullSubscribed x a
1981010 = PullSubscribed { pullSubscribedValue :: !a
199− , pullSubscribedInvalidators :: !(IORef [Weak Invalidator])
200− , pullSubscribedOwnInvalidator :: !Invalidator
201− , pullSubscribedParents :: ![SomeBehaviorSubscribed] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
1011+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
1012+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
1013+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
2021014 }
2031015
2041016--type role Pull representational
205−data Pull a
206− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed a)))
207− , pullCompute :: !(BehaviorM a)
1017+data Pull x a
1018+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
1019+ , pullCompute :: !(BehaviorM x a)
1020+#ifdef DEBUG_NODEIDS
1021+ , pullNodeId :: Int
1022+#endif
2081023 }
2091024
210−data Invalidator
211− = forall a. InvalidatorPull (Pull a)
212− | forall a. InvalidatorSwitch (SwitchSubscribed a)
213−
214−data RootSubscribed a
215− = RootSubscribed { rootSubscribedSubscribers :: !(IORef [WeakSubscriber a])
216− , rootSubscribedOccurrence :: !(IORef (Maybe a)) -- Alias to rootOccurrence
217− }
1025+data Invalidator x
1026+ = forall a. InvalidatorPull (Pull x a)
1027+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
1028+
1029+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1030+ { rootSubscribedKey :: !(k a)
1031+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1032+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1033+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1034+ , rootSubscribedUninit :: IO ()
1035+ , 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?
1036+#ifdef DEBUG_NODEIDS
1037+ , rootSubscribedNodeId :: Int
1038+#endif
1039+ }
2181040
219−data Root a
220− = Root { rootOccurrence :: !(IORef (Maybe a)) -- The currently-firing occurrence of this event
221− , rootSubscribed :: !(IORef (Maybe (RootSubscribed a)))
222− , rootInit :: !(RootTrigger a -> IO (IO ()))
1041+data Root x k
1042+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1043+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1044+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
2231045 }
2241046
225−data SomeHoldInit = forall a. SomeHoldInit (Event a) (Hold a)
1047+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1048+
1049+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1050+
1051+data SomeMergeUpdate x = SomeMergeUpdate
1052+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1053+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1054+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1055+ }
1056+
1057+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
2261058
2271059-- EventM can do everything BehaviorM can, plus create holds
228−newtype EventM a = EventM { unEventM :: ReaderT EventEnv IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over
229−
230−data PushSubscribed a b
231− = PushSubscribed { pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are)
232− , pushSubscribedHeight :: !(IORef Int)
233− , pushSubscribedSubscribers :: !(IORef [WeakSubscriber b])
234− , pushSubscribedSelf :: !(Subscriber a) -- Hold this in memory to ensure our WeakReferences don't die
235− , pushSubscribedParent :: !(EventSubscribed a)
236−#ifdef DEBUG_NODEIDS
237− , pushSubscribedNodeId :: Int
238−#endif
239− }
1060+newtype EventM x a = EventM { unEventM :: IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException)
2401061
241−data Push a b
242− = Push { pushCompute :: !(a -> EventM (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed
243− , pushParent :: !(Event a)
244− , pushSubscribed :: !(IORef (Maybe (PushSubscribed a b))) --TODO: Can we replace this with an unsafePerformIO thunk?
245− }
1062+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
2461063
247−data MergeSubscribed k
248− = MergeSubscribed { mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k)))
249− , mergeSubscribedAccum :: !(IORef (DMap k)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
250− , mergeSubscribedHeight :: !(IORef Int)
251− , mergeSubscribedSubscribers :: !(IORef [WeakSubscriber (DMap k)])
252− , mergeSubscribedSelf :: !Any -- Hold all our Subscribers in memory
253− , mergeSubscribedParents :: !(DMap (WrapArg EventSubscribed k))
254−#ifdef DEBUG_NODEIDS
255− , mergeSubscribedNodeId :: Int
1064+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1065+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1066+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1067+ }
1068+
1069+data HeightBag = HeightBag
1070+ { _heightBag_size :: {-# UNPACK #-} !Int
1071+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1072+ }
1073+ deriving (Show, Read, Eq, Ord)
1074+
1075+heightBagEmpty :: HeightBag
1076+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1077+
1078+heightBagSize :: HeightBag -> Int
1079+heightBagSize = _heightBag_size
1080+
1081+heightBagFromList :: [Height] -> HeightBag
1082+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1083+
1084+heightBagAdd :: Height -> HeightBag -> HeightBag
1085+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $
1086+ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1087+
1088+heightBagRemove :: Height -> HeightBag -> HeightBag
1089+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1090+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1091+ Just old -> HeightBag (pred s) $ case old of
1092+ 0 -> IntMap.delete h c
1093+ _ -> IntMap.insert h (pred old) c
1094+
1095+heightBagRemoveMaybe :: Height -> HeightBag -> Maybe HeightBag
1096+heightBagRemoveMaybe (Height h) b@(HeightBag s c) = heightBagVerify . removed <$> IntMap.lookup h c where
1097+ removed old = HeightBag (pred s) $ case old of
1098+ 0 -> IntMap.delete h c
1099+ _ -> IntMap.insert h (pred old) c
1100+
1101+
1102+heightBagMax :: HeightBag -> Height
1103+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1104+ Just ((h, _), _) -> Height h
1105+ Nothing -> zeroHeight
1106+
1107+heightBagVerify :: HeightBag -> HeightBag
1108+#ifdef DEBUG
1109+heightBagVerify b@(HeightBag s c) = if
1110+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1111+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1112+ | unHeight invalidHeight `IntMap.member` c
1113+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1114+ | otherwise -> b
1115+#else
1116+heightBagVerify = id
2561117#endif
257− }
2581118
259−--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
260−data Merge k
261− = Merge { mergeParents :: !(DMap (WrapArg Event k))
262− , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed k))) --TODO: Can we replace this with an unsafePerformIO thunk?
263− }
264−
265−data FanSubscriberKey k a where
266− FanSubscriberKey :: k a -> FanSubscriberKey k [WeakSubscriber a]
267−
268−instance GEq k => GEq (FanSubscriberKey k) where
269− geq (FanSubscriberKey a) (FanSubscriberKey b) = case geq a b of
270− Nothing -> Nothing
271− Just Refl -> Just Refl
272−
273−instance GCompare k => GCompare (FanSubscriberKey k) where
274− gcompare (FanSubscriberKey a) (FanSubscriberKey b) = case gcompare a b of
275− GLT -> GLT
276− GEQ -> GEQ
277− GGT -> GGT
278−
279−data FanSubscribed k
280− = FanSubscribed { fanSubscribedSubscribers :: !(IORef (DMap (FanSubscriberKey k)))
281− , fanSubscribedParent :: !(EventSubscribed (DMap k))
282− , fanSubscribedSelf :: !(Subscriber (DMap k))
1119+data FanSubscribedChildren x k v a = FanSubscribedChildren
1120+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1121+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1122+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
1123+ }
1124+
1125+data FanSubscribed x k v
1126+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1127+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1128+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
1129+ , fanSubscribedParent :: !(EventSubscription x)
2831130#ifdef DEBUG_NODEIDS
2841131 , fanSubscribedNodeId :: Int
2851132#endif
2861133 }
2871134
288−data Fan k
289− = Fan { fanParent :: !(Event (DMap k))
290− , fanSubscribed :: !(IORef (Maybe (FanSubscribed k)))
1135+data Fan x k v
1136+ = Fan { fanParent :: !(Event x (DMap k v))
1137+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
2911138 }
2921139
293−data SwitchSubscribed a
294− = SwitchSubscribed { switchSubscribedOccurrence :: !(IORef (Maybe a))
295− , switchSubscribedHeight :: !(IORef Int)
296− , switchSubscribedSubscribers :: !(IORef [WeakSubscriber a])
297− , switchSubscribedSelf :: !(Subscriber a)
298− , switchSubscribedSelfWeak :: !(IORef (Weak (Subscriber a)))
299− , switchSubscribedOwnInvalidator :: !Invalidator
300− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak Invalidator))
301− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed])
302− , switchSubscribedParent :: !(Behavior (Event a))
303− , switchSubscribedCurrentParent :: !(IORef (EventSubscribed a))
1140+data SwitchSubscribed x a
1141+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1142+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1143+ , switchSubscribedHeight :: !(IORef Height)
1144+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1145+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1146+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1147+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1148+ , switchSubscribedParent :: !(Behavior x (Event x a))
1149+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1150+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
3041151#ifdef DEBUG_NODEIDS
3051152 , switchSubscribedNodeId :: Int
3061153#endif
3071154 }
3081155
309−data Switch a
310− = Switch { switchParent :: !(Behavior (Event a))
311− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed a)))
1156+data Switch x a
1157+ = Switch { switchParent :: !(Behavior x (Event x a))
1158+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
3121159 }
3131160
314−data CoincidenceSubscribed a
315− = CoincidenceSubscribed { coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
316− , coincidenceSubscribedSubscribers :: !(IORef [WeakSubscriber a])
317− , coincidenceSubscribedHeight :: !(IORef Int)
318− , coincidenceSubscribedOuter :: !(Subscriber (Event a))
319− , coincidenceSubscribedOuterParent :: !(EventSubscribed (Event a))
320− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed a)))
1161+#ifdef USE_TEMPLATE_HASKELL
1162+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1163+#endif
1164+data CoincidenceSubscribed x a
1165+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1166+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1167+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1168+ , coincidenceSubscribedHeight :: !(IORef Height)
1169+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1170+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1171+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1172+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
3211173#ifdef DEBUG_NODEIDS
3221174 , coincidenceSubscribedNodeId :: Int
3231175#endif
3241176 }
3251177
326−data Coincidence a
327− = Coincidence { coincidenceParent :: !(Event (Event a))
328− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a)))
1178+data Coincidence x a
1179+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1180+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
3291181 }
3301182
331−data Box a = Box { unBox :: a }
332−
333−--type WeakSubscriber a = Weak (Subscriber a)
334−data WeakSubscriber a
335− = forall k. GCompare k => WeakSubscriberMerge !(k a) !(Weak (Box (MergeSubscribed k))) --TODO: Can we inline the GCompare?
336− | WeakSubscriberSimple !(Weak (Subscriber a))
337−
338−showWeakSubscriberType :: WeakSubscriber a -> String
339−showWeakSubscriberType = \case
340− WeakSubscriberMerge _ _ -> "WeakSubscriberMerge"
341− WeakSubscriberSimple _ -> "WeakSubscriberSimple"
342−
343−deRefWeakSubscriber :: WeakSubscriber a -> IO (Maybe (Subscriber a))
344−deRefWeakSubscriber ws = case ws of
345− WeakSubscriberSimple w -> deRefWeak w
346− WeakSubscriberMerge k w -> liftM (fmap $ SubscriberMerge k . unBox) $ deRefWeak w
347−
348−data Subscriber a
349− = forall b. SubscriberPush !(a -> EventM (Maybe b)) (PushSubscribed a b)
350− | forall k. GCompare k => SubscriberMerge !(k a) (MergeSubscribed k) --TODO: Can we inline the GCompare?
351− | forall k. (GCompare k, a ~ DMap k) => SubscriberFan (FanSubscribed k)
352− | SubscriberHold !(Hold a)
353− | SubscriberSwitch (SwitchSubscribed a)
354− | forall b. a ~ Event b => SubscriberCoincidenceOuter (CoincidenceSubscribed b)
355− | SubscriberCoincidenceInner (CoincidenceSubscribed a)
356−
357−showSubscriberType :: Subscriber a -> String
358−showSubscriberType = \case
359− SubscriberPush _ _ -> "SubscriberPush"
360− SubscriberMerge _ _ -> "SubscriberMerge"
361− SubscriberFan _ -> "SubscriberFan"
362− SubscriberHold _ -> "SubscriberHold"
363− SubscriberSwitch _ -> "SubscriberSwitch"
364− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
365− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
366−
367−data Event a
368− = EventRoot !(Root a)
369− | EventNever
370− | forall b. EventPush !(Push b a)
371− | forall k. (GCompare k, a ~ DMap k) => EventMerge !(Merge k)
372− | forall k. GCompare k => EventFan !(k a) !(Fan k)
373− | EventSwitch !(Switch a)
374− | EventCoincidence !(Coincidence a)
375−
376−showEventType :: Event a -> String
377−showEventType = \case
378− EventRoot _ -> "EventRoot"
379− EventNever -> "EventNever"
380− EventPush _ -> "EventPush"
381− EventMerge _ -> "EventMerge"
382− EventFan _ _ -> "EventFan"
383− EventSwitch _ -> "EventSwitch"
384− EventCoincidence _ -> "EventCoincidence"
385−
386−data EventSubscribed a
387− = EventSubscribedRoot !(RootSubscribed a)
388− | EventSubscribedNever
389− | forall b. EventSubscribedPush !(PushSubscribed b a)
390− | forall k. (GCompare k, a ~ DMap k) => EventSubscribedMerge !(MergeSubscribed k)
391− | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed k)
392− | EventSubscribedSwitch !(SwitchSubscribed a)
393− | EventSubscribedCoincidence !(CoincidenceSubscribed a)
394−
395−--type role Behavior representational
396−data Behavior a
397− = BehaviorHold !(Hold a)
398− | BehaviorConst !a
399− | BehaviorPull !(Pull a)
1183+{-# NOINLINE newInvalidatorSwitch #-}
1184+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1185+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
4001186
401−-- ResultM can read behaviors and events
402−type ResultM = EventM
1187+{-# NOINLINE newInvalidatorPull #-}
1188+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1189+newInvalidatorPull p = return $! InvalidatorPull p
4031190
404−{-# NOINLINE unsafeNewIORef #-}
405−unsafeNewIORef :: a -> b -> IORef b
406−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1191+instance HasSpiderTimeline x => Filterable (Event x) where
1192+ mapMaybe f = push $ return . f
4071193
408−instance Functor Event where
409− fmap f = push $ return . Just . f
1194+instance HasSpiderTimeline x => Align (Event x) where
1195+ nil = eventNever
1196+#if MIN_VERSION_these(0, 8, 0)
1197+instance HasSpiderTimeline x => Semialign (Event x) where
1198+#endif
1199+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1200+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
4101201
411−instance Functor Behavior where
412− fmap f = pull . liftM f . readBehaviorTracked
1202+#ifdef MIN_VERSION_semialign
1203+#if MIN_VERSION_semialign(1,1,0)
1204+instance HasSpiderTimeline x => Zip (Event x) where
1205+#endif
1206+ zip x y = mapMaybe justThese $ align x y
1207+#endif
4131208
414−{-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
415−push :: (a -> EventM (Maybe b)) -> Event a -> Event b
416−push f e = EventPush $ Push
417− { pushCompute = f
418− , pushParent = e
419− , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
420− }
421−{-# RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
1209+data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
1210+ | BuildDyn !(EventM x (PatchTarget p), Event x p)
1211+ | HoldDyn !(Hold x p)
1212+
1213+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
1214+
1215+newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
1216+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1217+
1218+--TODO: Avoid the duplication between this and R.zipDynWith
1219+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
1220+zipDynWith f da db =
1221+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1222+ ec = flip push eab $ \o -> do
1223+ (a, b) <- case o of
1224+ This (Identity a) -> do
1225+ b <- readBehaviorUntracked $ dynamicCurrent db
1226+ return (a, b)
1227+ That (Identity b) -> do
1228+ a <- readBehaviorUntracked $ dynamicCurrent da
1229+ return (a, b)
1230+ These (Identity a) (Identity b) -> return (a, b)
1231+ return $ Just $ Identity $ f a b
1232+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1233+
1234+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1235+buildDynamic readV0 v' = do
1236+ result <- liftIO $ newIORef $ BuildDyn (readV0, v')
1237+ let !d = Dyn result
1238+ defer $ SomeDynInit d
1239+ return d
1240+
1241+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1242+unsafeBuildDynamic readV0 v' =
1243+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
4221244
423−{-# NOINLINE pull #-}
424−pull :: BehaviorM a -> Behavior a
425−pull a = BehaviorPull $ Pull
426− { pullCompute = a
427− , pullValue = unsafeNewIORef a Nothing
428− }
429−{-# RULES "pull/pull" forall a. pull (readBehaviorTracked (pull a)) = pull a #-}
1245+-- ResultM can read behaviors and events
1246+type ResultM = EventM
4301247
431−{-# NOINLINE switch #-}
432−switch :: Behavior (Event a) -> Event a
433−switch a = EventSwitch $ Switch
434− { switchParent = a
435− , switchSubscribed = unsafeNewIORef a Nothing
436− }
437−{-# RULES "switch/constB" forall e. switch (BehaviorConst e) = e #-}
1248+instance HasSpiderTimeline x => Functor (Event x) where
1249+ fmap f = push $ return . Just . f
4381250
439−coincidence :: Event (Event a) -> Event a
440−coincidence a = EventCoincidence $ Coincidence
441− { coincidenceParent = a
442− , coincidenceSubscribed = unsafeNewIORef a Nothing
443− }
1251+instance Functor (Behavior x) where
1252+ fmap f = pull . fmap f . readBehaviorTracked
1253+
1254+{-# INLINE push #-}
1255+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1256+push f e = cacheEvent (pushCheap f e)
4441257
445−newRoot :: IO (Root a)
446−newRoot = do
447− occRef <- newIORef Nothing
448− subscribedRef <- newIORef Nothing
449− return $ Root
450− { rootOccurrence = occRef
451− , rootSubscribed = subscribedRef
452− , rootInit = const $ return $ return ()
1258+{-# INLINABLE pull #-}
1259+pull :: BehaviorM x a -> Behavior x a
1260+pull a = unsafePerformIO $ do
1261+ ref <- newIORef Nothing
1262+#ifdef DEBUG_NODEIDS
1263+ nid <- newNodeId
1264+#endif
1265+ pure $ behaviorPull $ Pull
1266+ { pullCompute = a
1267+ , pullValue = ref
1268+#ifdef DEBUG_NODEIDS
1269+ , pullNodeId = nid
1270+#endif
4531271 }
4541272
455−propagateAndUpdateSubscribersRef subscribersRef a = do
456− subscribers <- liftIO $ readIORef subscribersRef
457− liftIO $ writeIORef subscribersRef []
458− stillAlive <- propagate a subscribers
459− liftIO $ modifyIORef' subscribersRef (++stillAlive)
1273+{-# INLINABLE switch #-}
1274+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1275+switch a = unsafePerformIO $ do
1276+ ref <- newIORef Nothing
1277+ pure $ eventSwitch $ Switch
1278+ { switchParent = a
1279+ , switchSubscribed = ref
1280+ }
1281+
1282+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1283+coincidence a = unsafePerformIO $ do
1284+ ref <- newIORef Nothing
1285+ pure $ eventCoincidence $ Coincidence
1286+ { coincidenceParent = a
1287+ , coincidenceSubscribed = ref
1288+ }
4601289
4611290-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
462−run :: [DSum RootTrigger] -> ResultM b -> IO b
1291+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
4631292run roots after = do
464− when debugPropagate $ putStrLn "Running an event frame"
465− result <- runFrame $ do
466− forM_ roots $ \(RootTrigger (_, occRef) :=> a) -> do
467− liftIO $ writeIORef occRef $ Just a
468− scheduleClear occRef
469− forM_ roots $ \(RootTrigger (subscribersRef, _) :=> a) -> do
470− propagateAndUpdateSubscribersRef subscribersRef a
471− delayedRef <- EventM $ asks eventEnvDelayedMerges
1293+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1294+ let t = spiderTimeline :: SpiderTimelineEnv x
1295+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
1296+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1297+ occBefore <- liftIO $ do
1298+ occBefore <- readIORef occRef
1299+ writeIORef occRef $! DMap.insert k a occBefore
1300+ return occBefore
1301+ if DMap.null occBefore
1302+ then do scheduleRootClear occRef
1303+ return $ Just r
1304+ else return Nothing
1305+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1306+ propagate a subscribersRef
1307+ delayedRef <- asksEventEnv eventEnvDelayedMerges
4721308 let go = do
4731309 delayed <- liftIO $ readIORef delayedRef
4741310 case IntMap.minViewWithKey delayed of
4751311 Nothing -> return ()
476− Just ((currentHeight, current), future) -> do
477− when debugPropagate $ liftIO $ putStrLn $ "Running height " ++ show currentHeight
478− putCurrentHeight currentHeight
479− liftIO $ writeIORef delayedRef future
480− forM_ current $ \d -> case d of
481− DelayedMerge subscribed -> do
482− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
483− case height `compare` currentHeight of
484− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
485− GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
486− EQ -> do
487− m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
488− liftIO $ writeIORef (mergeSubscribedAccum subscribed) DMap.empty
489− --TODO: Assert that m is not empty
490− liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m
491− scheduleClear $ mergeSubscribedOccurrence subscribed
492− propagateAndUpdateSubscribersRef (mergeSubscribedSubscribers subscribed) m
1312+ Just ((currentHeight, cur), future) -> do
1313+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1314+ putCurrentHeight $ Height currentHeight
1315+ liftIO $ writeIORef delayedRef $! future
1316+ sequence_ cur
4931317 go
4941318 go
4951319 putCurrentHeight maxBound
4961320 after
497− when debugPropagate $ putStrLn "Done running an event frame"
1321+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
4981322 return result
4991323
500−data SomeMaybeIORef = forall a. SomeMaybeIORef (IORef (Maybe a))
1324+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1325+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1326+ height <- liftIO $ readIORef heightRef
1327+ currentHeight <- getCurrentHeight
1328+ case height `compare` currentHeight of
1329+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1330+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1331+ EQ -> a
1332+
1333+newtype Clear a = Clear (IORef (Maybe a))
5011334
502−data SomeAssignment = forall a. SomeAssignment (Hold a) a
1335+newtype IntClear a = IntClear (IORef (IntMap a))
5031336
504−data DelayedMerge = forall k. DelayedMerge (MergeSubscribed k)
1337+newtype RootClear k = RootClear (IORef (DMap k Identity))
1338+
1339+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
5051340
5061341debugFinalize :: Bool
5071342debugFinalize = False
5081343
5091344mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
510−mkWeakPtrWithDebug x debugNote = mkWeakPtr x $
511− if debugFinalize
512− then Just $ putStrLn $ "finalizing: " ++ debugNote
513− else Nothing
1345+mkWeakPtrWithDebug x debugNote = do
1346+ x' <- evaluate x
1347+ mkWeakPtr x' $
1348+ if debugFinalize
1349+ then Just $ debugStrLn $ "finalizing: " ++ debugNote
1350+ else Nothing
5141351
5151352type WeakList a = [Weak a]
5161353
517−--TODO: Is it faster to clean up every time, or to occasionally go through and clean up as needed?
518−traverseAndCleanWeakList_ :: Monad m => (wa -> m (Maybe a)) -> [wa] -> (a -> m ()) -> m [wa]
519−traverseAndCleanWeakList_ deRef ws f = go ws
520− where go [] = return []
521− go (h:t) = do
522− ma <- deRef h
523− case ma of
524− Just a -> do
525− f a
526− t' <- go t
527− return $ h : t'
528− Nothing -> go t
1354+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
5291355
530−-- | Propagate everything at the current height
531−propagate :: a -> [WeakSubscriber a] -> EventM [WeakSubscriber a]
532−propagate a subscribers = do
533− traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subscribers $ \s -> case s of
534− SubscriberPush compute subscribed -> do
535− when debugPropagate $ liftIO $ putStrLn $ "SubscriberPush" <> showNodeId subscribed
536− occ <- compute a
537− case occ of
538− Nothing -> return () -- No need to write a Nothing back into the Ref
539− Just o -> do
540− liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
541− scheduleClear $ pushSubscribedOccurrence subscribed
542− liftIO . writeIORef (pushSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (pushSubscribedSubscribers subscribed))
543− SubscriberMerge k subscribed -> do
544− when debugPropagate $ liftIO $ putStrLn $ "SubscriberMerge" <> showNodeId subscribed
545− oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
546− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $ DMap.insertWith (error "Same key fired multiple times for") k a oldM
547− when (DMap.null oldM) $ do -- Only schedule the firing once
548− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
549− --TODO: assertions about height
550− currentHeight <- getCurrentHeight
551− when (height <= currentHeight) $ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")"
552− scheduleMerge height subscribed
553− SubscriberFan subscribed -> do
554− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
555− when debugPropagate $ liftIO $ putStrLn $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
556− --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large
557− forM_ (DMap.toList a) $ \(k :=> v) -> case DMap.lookup (FanSubscriberKey k) subs of
558− Nothing -> do
559− when debugPropagate $ liftIO $ putStrLn "No subscriber for key"
560− return ()
561− Just subsubs -> do
562− _ <- propagate v subsubs --TODO: use the value of this
563− return ()
564− --TODO: The following is way too slow to do all the time
565− subs' <- liftIO $ forM (DMap.toList subs) $ ((\(FanSubscriberKey k :=> subsubs) -> do
566− subsubs' <- traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subsubs (const $ return ())
567− return $ if null subsubs' then Nothing else Just $ FanSubscriberKey k :=> subsubs') :: DSum (FanSubscriberKey k) -> IO (Maybe (DSum (FanSubscriberKey k))))
568− liftIO $ writeIORef (fanSubscribedSubscribers subscribed) $ DMap.fromDistinctAscList $ catMaybes subs'
569− SubscriberHold h -> do
570− invalidators <- liftIO $ readIORef $ holdInvalidators h
571− when debugPropagate $ liftIO $ putStrLn $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
572− toAssignRef <- askToAssignRef
573− liftIO $ modifyIORef' toAssignRef (SomeAssignment h a :)
574− SubscriberSwitch subscribed -> do
575− when debugPropagate $ liftIO $ putStrLn $ "SubscriberSwitch" <> showNodeId subscribed
576− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
577− scheduleClear $ switchSubscribedOccurrence subscribed
578− subs <- liftIO $ readIORef $ switchSubscribedSubscribers subscribed
579− liftIO . writeIORef (switchSubscribedSubscribers subscribed) =<< propagate a subs
580− SubscriberCoincidenceOuter subscribed -> do
581− when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
582− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
583− when debugPropagate $ liftIO $ putStrLn $ " outerHeight = " <> show outerHeight
584− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
585− when debugPropagate $ liftIO $ putStrLn $ " isJust occ = " <> show (isJust occ)
586− when debugPropagate $ liftIO $ putStrLn $ " innerHeight = " <> show innerHeight
587− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
588− scheduleClear $ coincidenceSubscribedInnerParent subscribed
589− case occ of
590− Nothing -> do
591− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
592− writeIORef (coincidenceSubscribedHeight subscribed) innerHeight
593− mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
594− mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
595− Just o -> do -- Since it's already firing, no need to adjust height
596− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
597− scheduleClear $ coincidenceSubscribedOccurrence subscribed
598− liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed))
599− SubscriberCoincidenceInner subscribed -> do
600− when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceInner" <> showNodeId subscribed
601− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
602− scheduleClear $ coincidenceSubscribedOccurrence subscribed
603− liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate a =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed))
604−
605−data SomeCoincidenceInfo = forall a. SomeCoincidenceInfo (Weak (Subscriber a)) (Subscriber a) (Maybe (CoincidenceSubscribed a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
606−
607−subscribeCoincidenceInner :: Event a -> Int -> CoincidenceSubscribed a -> EventM (Maybe a, Int, EventSubscribed a)
608−subscribeCoincidenceInner o outerHeight subscribedUnsafe = do
609− let !subInner = SubscriberCoincidenceInner subscribedUnsafe
610− wsubInner <- liftIO $ mkWeakPtrWithDebug subInner "SubscriberCoincidenceInner"
611− innerSubd <- {-# SCC "innerSubd" #-} (subscribe o $ WeakSubscriberSimple wsubInner)
612− innerOcc <- liftIO $ getEventSubscribedOcc innerSubd
613− innerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef innerSubd
614− let height = max innerHeight outerHeight
615− emitCoincidenceInfo $ SomeCoincidenceInfo wsubInner subInner $ if height > outerHeight then Just subscribedUnsafe else Nothing
616− return (innerOcc, height, innerSubd)
6171356
618−readBehavior :: Behavior a -> IO a
619−readBehavior b = runBehaviorM (readBehaviorTracked b) Nothing --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
6201357
621−runBehaviorM :: BehaviorM a -> Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]) -> IO a
622−runBehaviorM a mwi = runReaderT (unBehaviorM a) mwi
6231358
624−askInvalidator :: BehaviorM (Maybe (Weak Invalidator))
625−askInvalidator = liftM (fmap fst) $ BehaviorM ask
1359+#ifdef DEBUG
6261360
627−askParentsRef :: BehaviorM (Maybe (IORef [SomeBehaviorSubscribed]))
628−askParentsRef = liftM (fmap snd) $ BehaviorM ask
1361+debugSubscriber :: forall x a. HasSpiderTimeline x => String -> Subscriber x a -> IO (Subscriber x a)
1362+debugSubscriber description = return . debugSubscriber' description
1363+
1364+debugSubscriber' :: forall x a. HasSpiderTimeline x => String -> Subscriber x a -> Subscriber x a
1365+debugSubscriber' description subscribed = Subscriber
1366+ {
1367+ subscriberPropagate = \m -> do
1368+ tracePropagate (Proxy :: Proxy x) ("subscriberPropagate: " <> description)
1369+ subscriberPropagate subscribed m
1370+ , subscriberInvalidateHeight = \old -> do
1371+ traceInvalidateHeight $ "invalidateSubscriberHeight: " <> description <> ", old = " <> show (unHeight old)
1372+ subscriberInvalidateHeight subscribed old
1373+ traceInvalidateHeight $ "invalidateSubscriberHeight: " <> description <> ", done"
1374+ , subscriberRecalculateHeight = \new -> do
1375+ traceInvalidateHeight $ "subscriberRecalculateHeight: " <> description <> ", new = " <> show (unHeight new)
1376+ subscriberRecalculateHeight subscribed new
1377+ traceInvalidateHeight $ "subscriberRecalculateHeight: " <> description <> ", done"
1378+ }
6291379
630−readBehaviorTracked :: Behavior a -> BehaviorM a
631−readBehaviorTracked b = case b of
632− BehaviorHold h -> do
633− result <- liftIO $ readIORef $ holdValue h
634− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
635− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
636− liftIO $ touch $ holdSubscriber h
637− return result
638− BehaviorConst a -> return a
639− BehaviorPull p -> do
640− val <- liftIO $ readIORef $ pullValue p
641− case val of
642− Just subscribed -> do
643− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
644− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
645− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
646− return $ pullSubscribedValue subscribed
647− Nothing -> do
648− let !i = InvalidatorPull p
649− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
650− parentsRef <- liftIO $ newIORef []
651− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) $ Just (wi, parentsRef)
652− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
653− parents <- liftIO $ readIORef parentsRef
654− let subscribed = PullSubscribed
655− { pullSubscribedValue = a
656− , pullSubscribedInvalidators = invsRef
657− , pullSubscribedOwnInvalidator = i
658− , pullSubscribedParents = parents
659− }
660− liftIO $ writeIORef (pullValue p) $ Just subscribed
661− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
662− return a
6631380
664−readEvent :: Event a -> ResultM (Maybe a)
665−readEvent e = case e of
666− EventRoot r -> liftIO $ readIORef $ rootOccurrence r
667− EventNever -> return Nothing
668− EventPush p -> do
669− subscribed <- getPushSubscribed p
670− liftIO $ do
671− result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid
672− touch $ pushSubscribedSelf subscribed
673− return result
674− EventMerge m -> do
675− subscribed <- getMergeSubscribed m
676− liftIO $ do
677− result <- readIORef $ mergeSubscribedOccurrence subscribed
678− touch $ mergeSubscribedSelf subscribed
679− return result
680− EventFan k f -> do
681− parentOcc <- readEvent $ fanParent f
682− return $ DMap.lookup k =<< parentOcc
683− EventSwitch s -> do
684− subscribed <- getSwitchSubscribed s
685− liftIO $ do
686− result <- readIORef $ switchSubscribedOccurrence subscribed
687− touch $ switchSubscribedSelf subscribed
688− touch $ switchSubscribedOwnInvalidator subscribed
689− return result
690− EventCoincidence c -> do
691− subscribed <- getCoincidenceSubscribed c
692− liftIO $ do
693− result <- readIORef $ coincidenceSubscribedOccurrence subscribed
694− touch $ coincidenceSubscribedOuter subscribed
695− --TODO: do we need to touch the inner subscriber?
696− return result
1381+{-# INLINE withIncreasedDepth #-}
1382+withIncreasedDepth :: forall proxy x m a. CanTrace x m => proxy x -> m a -> m a
1383+withIncreasedDepth _ a = do
1384+ liftIO $ modifyIORef' (_spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)) succ
1385+ result <- a
1386+ liftIO $ modifyIORef' (_spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)) pred
1387+ return result
1388+
1389+{-# INLINE tracePropagate #-}
1390+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1391+tracePropagate p = when debugPropagate . trace p
1392+
1393+{-# INLINE traceInvalidate #-}
1394+traceInvalidate :: String -> IO ()
1395+traceInvalidate = when debugInvalidate . liftIO . debugStrLn
1396+
1397+{-# INLINE traceInvalidateHeight #-}
1398+traceInvalidateHeight :: String -> IO ()
1399+traceInvalidateHeight = when debugInvalidateHeight . liftIO . debugStrLn
1400+
1401+{-# INLINE trace #-}
1402+trace :: (CanTrace x m) => proxy x -> String -> m ()
1403+trace p message = traceM p $ return message
1404+
1405+{-# INLINE traceM #-}
1406+traceM :: forall x proxy m. (CanTrace x m) => proxy x -> m String -> m ()
1407+traceM _ getMessage = do
1408+ message <- getMessage
1409+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
1410+ liftIO $ debugStrLn $ replicate d ' ' <> message
1411+
1412+#else
1413+
1414+{-# INLINE withIncreasedDepth #-}
1415+withIncreasedDepth :: proxy x -> m a -> m a
1416+withIncreasedDepth _ = id
1417+
1418+{-# INLINE tracePropagate #-}
1419+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1420+tracePropagate _ _ = return ()
1421+
1422+{-# INLINE traceInvalidate #-}
1423+traceInvalidate :: String -> IO ()
1424+traceInvalidate _ = return ()
1425+
1426+{-# INLINE traceInvalidateHeight #-}
1427+traceInvalidateHeight :: String -> IO ()
1428+traceInvalidateHeight _ = return ()
1429+
1430+{-# INLINE debugSubscriber #-}
1431+debugSubscriber :: String -> Subscriber x a -> IO (Subscriber x a)
1432+debugSubscriber _ = return
1433+
1434+{-# INLINE debugSubscriber' #-}
1435+debugSubscriber' :: String -> Subscriber x a -> Subscriber x a
1436+debugSubscriber' _ = id
1437+
1438+
1439+
1440+{-# INLINE trace #-}
1441+trace :: (CanTrace x m) => proxy x -> String -> m ()
1442+trace _ _ = return ()
1443+
1444+{-# INLINE traceM #-}
1445+traceM :: (CanTrace x m) => proxy x -> m String -> m ()
1446+traceM _ _ = return ()
1447+
1448+#endif
1449+
1450+whoCreatedIORef :: IORef a -> IO [String]
1451+whoCreatedIORef (IORef a) = whoCreated $! a
1452+
1453+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1454+groupByHead = \case
1455+ [] -> []
1456+ (x :| xs) : t -> case groupByHead t of
1457+ [] -> [(x, xs :| [])]
1458+ l@((y, yss) : t')
1459+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1460+ | otherwise -> (x, xs :| []) : l
1461+
1462+listsToForest :: Eq a => [[a]] -> Forest a
1463+listsToForest lists = buildForest <$> groupByHead (mapMaybe nonEmpty lists)
1464+ where buildForest (a, lists') = Node a $ listsToForest $ toList lists'
1465+
1466+showStacks :: [[String]] -> String
1467+showStacks = drawForest . listsToForest . fmap (filterStack "Reflex.Spider.Internal")
1468+
1469+filterStack :: String -> [String] -> [String]
1470+#ifdef DEBUG_HIDE_INTERNALS
1471+filterStack prefix = filter (not . (prefix `isPrefixOf`))
1472+#else
1473+filterStack prefix = id
1474+#endif
1475+
1476+#ifdef DEBUG_CYCLES
1477+
1478+data EventLoopException = EventLoopException [[String]]
1479+instance Exception EventLoopException
1480+
1481+instance Show EventLoopException where
1482+ show (EventLoopException stacks) = "causality loop detected:\n" <> if null stacks
1483+ then "no location information, compile with profiling enabled for stack tree"
1484+ else showStacks stacks
1485+
1486+#else
1487+
1488+data EventLoopException = EventLoopException
1489+instance Exception EventLoopException
1490+
1491+instance Show EventLoopException where
1492+ show EventLoopException = "causality loop detected: \n" <>
1493+ "compile reflex with flag 'debug-cycles' and compile with profiling enabled for stack tree"
1494+
1495+#endif
1496+
1497+
1498+{-# INLINE propagateSubscriberHold #-}
1499+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1500+propagateSubscriberHold h a = do
1501+ {-# SCC "trace" #-} when debugPropagate $ traceM (Proxy :: Proxy x) $ liftIO $ do
1502+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1503+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1504+
1505+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1506+ case {-# SCC "apply" #-} apply a v of
1507+ Nothing -> return ()
1508+ Just v' -> do
1509+ {-# SCC "trace2" #-} withIncreasedDepth (Proxy :: Proxy x) $
1510+ tracePropagate (Proxy :: Proxy x) ("propagateSubscriberHold: assigning Hold" <> showNodeId h)
1511+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1512+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1513+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1514+
1515+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1516+
1517+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1518+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
1519+
1520+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1521+askInvalidator = do
1522+ (!m, _) <- ask
1523+ case m of
1524+ Nothing -> return Nothing
1525+ Just (!wi, _) -> return $ Just wi
1526+
1527+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1528+askParentsRef = do
1529+ (!m, _) <- ask
1530+ case m of
1531+ Nothing -> return Nothing
1532+ Just (_, !p) -> return $ Just p
1533+
1534+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1535+askBehaviorHoldInits = do
1536+ (_, !his) <- ask
1537+ return his
1538+
1539+{-# INLINE getDynHold #-}
1540+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1541+getDynHold d = do
1542+ mh <- liftIO $ readIORef $ unDyn d
1543+ case mh of
1544+ HoldDyn h -> return h
1545+ UnsafeDyn (readV0, v') -> do
1546+ holdInits <- getDeferralQueue
1547+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1548+ hold' v0 v'
1549+ BuildDyn (readV0, v') -> do
1550+ v0 <- liftIO $ runEventM readV0
1551+ hold' v0 v'
1552+ where
1553+ hold' v0 v' = do
1554+ h <- hold v0 v'
1555+ liftIO $ writeIORef (unDyn d) $ HoldDyn h
1556+ return h
1557+
6971558
6981559-- Always refers to 0
6991560{-# NOINLINE zeroRef #-}
700−zeroRef :: IORef Int
701−zeroRef = unsafePerformIO $ newIORef 0
702−
703−getEventSubscribed :: Event a -> EventM (EventSubscribed a)
704−getEventSubscribed e = case e of
705− EventRoot r -> liftM EventSubscribedRoot $ getRootSubscribed r
706− EventNever -> return EventSubscribedNever
707− EventPush p -> liftM EventSubscribedPush $ getPushSubscribed p
708− EventFan k f -> liftM (EventSubscribedFan k) $ getFanSubscribed f
709− EventMerge m -> liftM EventSubscribedMerge $ getMergeSubscribed m
710− EventSwitch s -> liftM EventSubscribedSwitch $ getSwitchSubscribed s
711− EventCoincidence c -> liftM EventSubscribedCoincidence $ getCoincidenceSubscribed c
712−
713−debugSubscribe :: Bool
714−debugSubscribe = False
715−
716−subscribeEventSubscribed :: EventSubscribed a -> WeakSubscriber a -> IO ()
717−subscribeEventSubscribed es ws = case es of
718− EventSubscribedRoot r -> do
719− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Root"
720− modifyIORef' (rootSubscribedSubscribers r) (ws:)
721− EventSubscribedNever -> do
722− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Never"
723− return ()
724− EventSubscribedPush subscribed -> do
725− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Push"
726− modifyIORef' (pushSubscribedSubscribers subscribed) (ws:)
727− EventSubscribedFan k subscribed -> do
728− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Fan"
729− modifyIORef' (fanSubscribedSubscribers subscribed) $ DMap.insertWith (++) (FanSubscriberKey k) [ws]
730− EventSubscribedMerge subscribed -> do
731− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Merge"
732− modifyIORef' (mergeSubscribedSubscribers subscribed) (ws:)
733− EventSubscribedSwitch subscribed -> do
734− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Switch"
735− modifyIORef' (switchSubscribedSubscribers subscribed) (ws:)
736− EventSubscribedCoincidence subscribed -> do
737− when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Coincidence"
738− modifyIORef' (coincidenceSubscribedSubscribers subscribed) (ws:)
739−
740−getEventSubscribedOcc :: EventSubscribed a -> IO (Maybe a)
741−getEventSubscribedOcc es = case es of
742− EventSubscribedRoot r -> readIORef $ rootSubscribedOccurrence r
743− EventSubscribedNever -> return Nothing
744− EventSubscribedPush subscribed -> readIORef $ pushSubscribedOccurrence subscribed
745− EventSubscribedFan k subscribed -> do
746− parentOcc <- getEventSubscribedOcc $ fanSubscribedParent subscribed
747− let occ = DMap.lookup k =<< parentOcc
748− return occ
749− EventSubscribedMerge subscribed -> readIORef $ mergeSubscribedOccurrence subscribed
750− EventSubscribedSwitch subscribed -> readIORef $ switchSubscribedOccurrence subscribed
751− EventSubscribedCoincidence subscribed -> readIORef $ coincidenceSubscribedOccurrence subscribed
752−
753−eventSubscribedHeightRef :: EventSubscribed a -> IORef Int
754−eventSubscribedHeightRef es = case es of
755− EventSubscribedRoot _ -> zeroRef
756− EventSubscribedNever -> zeroRef
757− EventSubscribedPush subscribed -> pushSubscribedHeight subscribed
758− EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ fanSubscribedParent subscribed
759− EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed
760− EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed
761− EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed
762−
763−subscribe :: Event a -> WeakSubscriber a -> EventM (EventSubscribed a)
764−subscribe e ws = do
765− subd <- getEventSubscribed e
766− liftIO $ subscribeEventSubscribed subd ws
767− return subd
768−
769−getRootSubscribed :: Root a -> EventM (RootSubscribed a)
770−getRootSubscribed r = do
771− mSubscribed <- liftIO $ readIORef $ rootSubscribed r
772− case mSubscribed of
773− Just subscribed -> return subscribed
774− Nothing -> liftIO $ do
775− subscribersRef <- newIORef []
1561+zeroRef :: IORef Height
1562+zeroRef = unsafePerformIO $ newIORef zeroHeight
1563+
1564+getRootSubscribed :: forall k x a. (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1565+getRootSubscribed k r sub = do
1566+ mSubscribed <- readIORef $ rootSubscribed r
1567+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1568+ case DMap.lookup k mSubscribed of
1569+ Just subscribed -> {-# SCC "hitRoot" #-} do
1570+ sln <- subscribeRootSubscribed subscribed sub
1571+ occ <- getOcc
1572+ return (sln, subscribed, occ)
1573+ Nothing -> {-# SCC "missRoot" #-} do
1574+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1575+ let !cached = rootSubscribed r
1576+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1577+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1578+
1579+ tracePropagate (Proxy::Proxy x) $ "getRootSubscribed: calling rootInit"
1580+
1581+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1582+ writeIORef uninitRef $! uninit
1583+#ifdef DEBUG_NODEIDS
1584+ nid <- newNodeId
1585+#endif
7761586 let !subscribed = RootSubscribed
777− { rootSubscribedOccurrence = rootOccurrence r
778− , rootSubscribedSubscribers = subscribersRef
779− }
780− -- Strangely, init needs the same stuff as a RootSubscribed has, but it must not be the same as the one that everyone's subscribing to, or it'll leak memory
781− uninit <- rootInit r $ RootTrigger (subscribersRef, rootOccurrence r)
782− addFinalizer subscribed $ do
783−-- putStrLn "Uninit root"
784− uninit
785− liftIO $ writeIORef (rootSubscribed r) $ Just subscribed
786− return subscribed
787−
788−-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
789−getPushSubscribed :: Push a b -> EventM (PushSubscribed a b)
790−getPushSubscribed p = do
791− mSubscribed <- liftIO $ readIORef $ pushSubscribed p
792− case mSubscribed of
793− Just subscribed -> return subscribed
794− Nothing -> do -- Not yet subscribed
795− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ pushSubscribed p
796− let !s = SubscriberPush (pushCompute p) subscribedUnsafe
797− ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberPush"
798− subd <- subscribe (pushParent p) $ WeakSubscriberSimple ws
799− parentOcc <- liftIO $ getEventSubscribedOcc subd
800− occ <- liftM join $ mapM (pushCompute p) parentOcc
801− occRef <- liftIO $ newIORef occ
802− when (isJust occ) $ scheduleClear occRef
803− subscribersRef <- liftIO $ newIORef []
804− let subscribed = PushSubscribed
805− { pushSubscribedOccurrence = occRef
806− , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
807− , pushSubscribedSubscribers = subscribersRef
808− , pushSubscribedSelf = unsafeCoerce s
809− , pushSubscribedParent = subd
1587+ { rootSubscribedKey = k
1588+ , rootSubscribedCachedSubscribed = cached
1589+ , rootSubscribedOccurrence = getOcc
1590+ , rootSubscribedSubscribers = subs
1591+ , rootSubscribedUninit = uninit
1592+ , rootSubscribedWeakSelf = weakSelf
8101593#ifdef DEBUG_NODEIDS
811− , pushSubscribedNodeId = unsafeNodeId p
1594+ , rootSubscribedNodeId = nid
8121595#endif
8131596 }
814− liftIO $ writeIORef (pushSubscribed p) $ Just subscribed
815− return subscribed
1597+ -- If we die at the same moment that all our children die, they will
1598+ -- try to clean us up but will fail because their Weak reference to us
1599+ -- will also be dead. So, if we are dying, check if there are any
1600+ -- children; since children don't bother cleaning themselves up if
1601+ -- their parents are already dead, I don't think there's a race
1602+ -- condition here. However, if there are any children, then we can
1603+ -- infer that we need to clean ourselves up, so we do.
1604+ finalCleanup = do
1605+ cs <- readIORef $ _weakBag_children subs
1606+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1607+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1608+ 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
1609+ occ <- getOcc
1610+ return (sln, subscribed, occ)
1611+
1612+#ifdef USE_TEMPLATE_HASKELL
1613+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1614+#endif
1615+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1616+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1617+ rootSubscribedUninit self
1618+ modifyIORef' cached $ DMap.delete k
8161619
817−getMergeSubscribed :: forall k. GCompare k => Merge k -> EventM (MergeSubscribed k)
818−getMergeSubscribed m = {-# SCC "getMergeSubscribed.entire" #-} do
819− mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
820− case mSubscribed of
821− Just subscribed -> return subscribed
822− Nothing -> if DMap.null $ mergeParents m then emptyMergeSubscribed else do
823− subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
824− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
825− let !s = Box subscribedUnsafe
826− ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberMerge"
827− subscribers :: [(Any, Maybe (DSum k), Int, DSum (WrapArg EventSubscribed k))] <- forM (DMap.toList $ mergeParents m) $ {-# SCC "getMergeSubscribed.a" #-} \(WrapArg k :=> e) -> {-# SCC "getMergeSubscribed.a1" #-} do
828− parentSubd <- {-# SCC "getMergeSubscribed.a.parentSubd" #-} subscribe e $ WeakSubscriberMerge k ws
829− parentOcc <- {-# SCC "getMergeSubscribed.a.parentOcc" #-} liftIO $ getEventSubscribedOcc parentSubd
830− height <- {-# SCC "getMergeSubscribed.a.height" #-} liftIO $ readIORef $ eventSubscribedHeightRef parentSubd
831− return $ {-# SCC "getMergeSubscribed.a.returnVal" #-} (unsafeCoerce s :: Any, fmap (k :=>) parentOcc, height, WrapArg k :=> parentSubd)
832− let dm = DMap.fromDistinctAscList $ catMaybes $ map (^._2) subscribers
833− subscriberHeights = map (^._3) subscribers
834− myHeight =
835− if any (==invalidHeight) subscriberHeights --TODO: Replace 'any' with invalidHeight-preserving 'maximum'
836− then invalidHeight
837− else succ $ Prelude.maximum subscriberHeights -- This is safe because the DMap will never be empty here
838− currentHeight <- getCurrentHeight
839− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
840− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
841− else (Nothing, dm)
842− when (not $ DMap.null accum) $ do
843− scheduleMerge myHeight subscribedUnsafe
844− occRef <- liftIO $ newIORef occ
845− when (isJust occ) $ scheduleClear occRef
846− accumRef <- liftIO $ newIORef accum
847− heightRef <- liftIO $ newIORef myHeight
848− subsRef <- liftIO $ newIORef []
849− let subscribed = MergeSubscribed
850− { mergeSubscribedOccurrence = occRef
851− , mergeSubscribedAccum = accumRef
852− , mergeSubscribedHeight = heightRef
853− , mergeSubscribedSubscribers = subsRef
854− , mergeSubscribedSelf = unsafeCoerce $ map (\(x, _, _, _) -> x) subscribers --TODO: Does lack of strictness make this leak?
855− , mergeSubscribedParents = DMap.fromDistinctAscList $ map (^._4) subscribers
1620+{-# INLINE subscribeRootSubscribed #-}
1621+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1622+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1623+
1624+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1625+
1626+data FanInt x a = FanInt
1627+ { _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
1628+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1629+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
8561630#ifdef DEBUG_NODEIDS
857− , mergeSubscribedNodeId = unsafeNodeId m
1631+ , _fanInt_nodeId :: {-# UNPACK #-} !Int
8581632#endif
859− }
860− liftIO $ writeIORef subscribedRef subscribed
861− return subscribed
862− where emptyMergeSubscribed = do --TODO: This should never happen
863− occRef <- liftIO $ newIORef Nothing
864− accumRef <- liftIO $ newIORef DMap.empty
865− subsRef <- liftIO $ newIORef []
866− return $ MergeSubscribed
867− { mergeSubscribedOccurrence = occRef
868− , mergeSubscribedAccum = accumRef
869− , mergeSubscribedHeight = zeroRef
870− , mergeSubscribedSubscribers = subsRef --TODO: This will definitely leak
871− , mergeSubscribedSelf = unsafeCoerce ()
872− , mergeSubscribedParents = DMap.empty
1633+ }
1634+
1635+newFanInt :: IO (FanInt x a)
1636+newFanInt = do
1637+ 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
1638+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1639+ occRef <- newIORef $ error "fanInt: no occurrence"
8731640#ifdef DEBUG_NODEIDS
874− , mergeSubscribedNodeId = -1
1641+ nodeId <- newNodeId
8751642#endif
876− }
1643+ return $ FanInt
1644+ { _fanInt_subscribers = subscribers
1645+ , _fanInt_subscriptionRef = subscriptionRef
1646+ , _fanInt_occRef = occRef
1647+#ifdef DEBUG_NODEIDS
1648+ , _fanInt_nodeId = nodeId
1649+#endif
1650+ }
1651+
1652+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1653+fanInt p = unsafePerformIO $ do
1654+ self <- newFanInt
1655+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
1656+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1657+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1658+ let desc = "fanInt" <> showNodeId self <> ", k = " <> show k
1659+ (subscription, parentOcc) <- subscribeAndRead p $ debugSubscriber' desc $ Subscriber
1660+ { subscriberPropagate = \m -> do
1661+ liftIO $ writeIORef (_fanInt_occRef self) m
1662+ scheduleIntClear $ _fanInt_occRef self
1663+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> --TODO: Do we need to know that no subscribers are being added as we traverse?
1664+ FastWeakBag.traverse_ b $ \s ->
1665+ subscriberPropagate s v
1666+ , subscriberInvalidateHeight = \old ->
1667+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b ->
1668+ FastWeakBag.traverse_ b $ \s ->
1669+ subscriberInvalidateHeight s old
1670+ , subscriberRecalculateHeight = \new ->
1671+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b ->
1672+ FastWeakBag.traverse_ b $ \s ->
1673+ subscriberRecalculateHeight s new
1674+ }
1675+ liftIO $ do
1676+ writeIORef (_fanInt_subscriptionRef self) subscription
1677+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1678+ scheduleIntClear $ _fanInt_occRef self
1679+ liftIO $ do
1680+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1681+ Nothing -> do
1682+ b <- FastWeakBag.empty
1683+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1684+ return b
1685+ Just b -> return b
1686+ ticket <- liftIO $ FastWeakBag.insert sub b
1687+ currentOcc <- readIORef (_fanInt_occRef self)
1688+
1689+ subscribed <- fanIntSubscribed ticket self
1690+ return (EventSubscription (FastWeakBag.remove ticket) subscribed, IntMap.lookup k currentOcc)
1691+
1692+fanIntSubscribed :: FastWeakBagTicket k -> FanInt x a -> IO (EventSubscribed x)
1693+fanIntSubscribed ticket self = do
1694+ subscribedParent <- _eventSubscription_subscribed <$> readIORef (_fanInt_subscriptionRef self)
1695+ return $ EventSubscribed
1696+ { eventSubscribedHeightRef = eventSubscribedHeightRef subscribedParent
1697+ , eventSubscribedRetained = toAny (_fanInt_subscriptionRef self, ticket)
1698+#ifdef DEBUG_CYCLES
1699+ , eventSubscribedGetParents = return [subscribedParent]
1700+ , eventSubscribedHasOwnHeightRef = False
1701+ , eventSubscribedWhoCreated = whoCreatedIORef $ _fanInt_subscriptionRef self
1702+#endif
1703+ }
8771704
878−getFanSubscribed :: GCompare k => Fan k -> EventM (FanSubscribed k)
879−getFanSubscribed f = do
1705+
1706+{-# INLINABLE getFanSubscribed #-}
1707+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))
1708+getFanSubscribed k f sub = do
8801709 mSubscribed <- liftIO $ readIORef $ fanSubscribed f
8811710 case mSubscribed of
882− Just subscribed -> return subscribed
883− Nothing -> do
884− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ fanSubscribed f
885− let !sub = SubscriberFan subscribedUnsafe
886− wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberFan"
887− subd <- subscribe (fanParent f) $ WeakSubscriberSimple wsub
888− subscribersRef <- liftIO $ newIORef DMap.empty
1711+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1712+ sln <- subscribeFanSubscribed k subscribed sub
1713+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1714+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1715+ Nothing -> {-# SCC "missFan" #-} do
1716+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1717+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1718+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1719+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1720+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1721+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1722+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1723+ occRef <- liftIO $ newIORef parentOcc
1724+ when (isJust parentOcc) $ scheduleClear occRef
1725+#ifdef DEBUG_NODEIDS
1726+ nid <- liftIO newNodeId
1727+#endif
8891728 let subscribed = FanSubscribed
890− { fanSubscribedParent = subd
1729+ { fanSubscribedCachedSubscribed = fanSubscribed f
1730+ , fanSubscribedOccurrence = occRef
1731+ , fanSubscribedParent = subscription
8911732 , fanSubscribedSubscribers = subscribersRef
892− , fanSubscribedSelf = sub
8931733#ifdef DEBUG_NODEIDS
894− , fanSubscribedNodeId = unsafeNodeId f
1734+ , fanSubscribedNodeId = nid
8951735#endif
8961736 }
1737+ let !self = (k, subscribed)
1738+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1739+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1740+ liftIO $ writeIORef subscribedRef $! subscribed
8971741 liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
898− return subscribed
899−
900−getSwitchSubscribed :: Switch a -> EventM (SwitchSubscribed a)
901−getSwitchSubscribed s = do
1742+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1743+
1744+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
1745+cleanupFanSubscribed (k, subscribed) = do
1746+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1747+ let reducedSubscribers = DMap.delete k subscribers
1748+ if DMap.null reducedSubscribers
1749+ then do
1750+ unsubscribe $ fanSubscribedParent subscribed
1751+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1752+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1753+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1754+
1755+{-# INLINE subscribeFanSubscribed #-}
1756+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
1757+subscribeFanSubscribed k subscribed sub = do
1758+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1759+ case DMap.lookup k subscribers of
1760+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1761+ let !self = (k, subscribed)
1762+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1763+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1764+ 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
1765+ return sln
1766+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1767+
1768+{-# INLINABLE getSwitchSubscribed #-}
1769+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1770+getSwitchSubscribed s sub = do
9021771 mSubscribed <- liftIO $ readIORef $ switchSubscribed s
9031772 case mSubscribed of
904− Just subscribed -> return subscribed
905− Nothing -> do
1773+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1774+ sln <- subscribeSwitchSubscribed subscribed sub
1775+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1776+ return (sln, subscribed, occ)
1777+ Nothing -> {-# SCC "missSwitch" #-} do
9061778 subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
9071779 subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
908− let !i = InvalidatorSwitch subscribedUnsafe
909− !sub = SubscriberSwitch subscribedUnsafe
1780+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1781+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
9101782 wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
9111783 wiRef <- liftIO $ newIORef wi
912− wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberSwitch"
913− selfWeakRef <- liftIO $ newIORef wsub
9141784 parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
915− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) $ Just (wi, parentsRef)
916− subd <- subscribe e $ WeakSubscriberSimple wsub
917− subdRef <- liftIO $ newIORef subd
918− parentOcc <- liftIO $ getEventSubscribedOcc subd
1785+ holdInits <- getDeferralQueue
1786+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1787+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1788+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1789+ subscriptionRef <- liftIO $ newIORef subscription
9191790 occRef <- liftIO $ newIORef parentOcc
9201791 when (isJust parentOcc) $ scheduleClear occRef
921− heightRef <- liftIO $ newIORef =<< readIORef (eventSubscribedHeightRef subd)
922− subscribersRef <- liftIO $ newIORef []
923− let subscribed = SwitchSubscribed
924− { switchSubscribedOccurrence = occRef
1792+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1793+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1794+#ifdef DEBUG_NODEIDS
1795+ nid <- liftIO newNodeId
1796+#endif
1797+ let !subscribed = SwitchSubscribed
1798+ { switchSubscribedCachedSubscribed = switchSubscribed s
1799+ , switchSubscribedOccurrence = occRef
9251800 , switchSubscribedHeight = heightRef
926− , switchSubscribedSubscribers = subscribersRef
927− , switchSubscribedSelf = sub
928− , switchSubscribedSelfWeak = selfWeakRef
1801+ , switchSubscribedSubscribers = subs
9291802 , switchSubscribedOwnInvalidator = i
9301803 , switchSubscribedOwnWeakInvalidator = wiRef
9311804 , switchSubscribedBehaviorParents = parentsRef
9321805 , switchSubscribedParent = switchParent s
933− , switchSubscribedCurrentParent = subdRef
1806+ , switchSubscribedCurrentParent = subscriptionRef
1807+ , switchSubscribedWeakSelf = weakSelf
9341808#ifdef DEBUG_NODEIDS
935− , switchSubscribedNodeId = unsafeNodeId s
1809+ , switchSubscribedNodeId = nid
9361810#endif
9371811 }
938− liftIO $ writeIORef subscribedRef subscribed
1812+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1813+ liftIO $ writeIORef subscribedRef $! subscribed
9391814 liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
940− return subscribed
1815+ return (slnForSub, subscribed, parentOcc)
1816+
1817+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1818+cleanupSwitchSubscribed subscribed = do
1819+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1820+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1821+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
9411822
942−getCoincidenceSubscribed :: forall a. Coincidence a -> EventM (CoincidenceSubscribed a)
943−getCoincidenceSubscribed c = do
1823+{-# INLINE subscribeSwitchSubscribed #-}
1824+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1825+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1826+
1827+{-# INLINABLE getCoincidenceSubscribed #-}
1828+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1829+getCoincidenceSubscribed c sub = do
9441830 mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
9451831 case mSubscribed of
946− Just subscribed -> return subscribed
947− Nothing -> do
1832+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1833+ sln <- subscribeCoincidenceSubscribed subscribed sub
1834+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1835+ return (sln, subscribed, occ)
1836+ Nothing -> {-# SCC "missCoincidence" #-} do
9481837 subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
9491838 subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
950− let !subOuter = SubscriberCoincidenceOuter subscribedUnsafe
951− wsubOuter <- liftIO $ mkWeakPtrWithDebug subOuter "subOuter"
952− outerSubd <- subscribe (coincidenceParent c) $ WeakSubscriberSimple wsubOuter
953− outerOcc <- liftIO $ getEventSubscribedOcc outerSubd
954− outerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef outerSubd
1839+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1840+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1841+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
9551842 (occ, height, mInnerSubd) <- case outerOcc of
9561843 Nothing -> return (Nothing, outerHeight, Nothing)
9571844 Just o -> do
@@ -962,267 +1849,647 @@ getCoincidenceSubscribed c = do
9621849 heightRef <- liftIO $ newIORef height
9631850 innerSubdRef <- liftIO $ newIORef mInnerSubd
9641851 scheduleClear innerSubdRef
965− subscribersRef <- liftIO $ newIORef []
1852+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1853+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1854+#ifdef DEBUG_NODEIDS
1855+ nid <- liftIO newNodeId
1856+#endif
9661857 let subscribed = CoincidenceSubscribed
967− { coincidenceSubscribedOccurrence = occRef
1858+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1859+ , coincidenceSubscribedOccurrence = occRef
9681860 , coincidenceSubscribedHeight = heightRef
969− , coincidenceSubscribedSubscribers = subscribersRef
1861+ , coincidenceSubscribedSubscribers = subs
9701862 , coincidenceSubscribedOuter = subOuter
971− , coincidenceSubscribedOuterParent = outerSubd
1863+ , coincidenceSubscribedOuterParent = outerSubscription
9721864 , coincidenceSubscribedInnerParent = innerSubdRef
1865+ , coincidenceSubscribedWeakSelf = weakSelf
9731866#ifdef DEBUG_NODEIDS
974− , coincidenceSubscribedNodeId = unsafeNodeId c
1867+ , coincidenceSubscribedNodeId = nid
9751868#endif
9761869 }
977− liftIO $ writeIORef subscribedRef subscribed
1870+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1871+ liftIO $ writeIORef subscribedRef $! subscribed
9781872 liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
979− return subscribed
1873+ return (slnForSub, subscribed, occ)
1874+
1875+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1876+cleanupCoincidenceSubscribed subscribed = do
1877+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1878+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1879+
1880+{-# INLINE subscribeCoincidenceSubscribed #-}
1881+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1882+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1883+
1884+{-# INLINE mergeG #-}
1885+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1886+ => (forall a. q a -> Event x (v a))
1887+ -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1888+mergeG nt d = cacheEvent (mergeCheap nt d)
1889+
1890+{-# INLINE mergeWithMove #-}
1891+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1892+ => (forall a. q a -> Event x (v a))
1893+ -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1894+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
1895+
1896+{-# INLINE [1] mergeCheap #-}
1897+mergeCheap
1898+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1899+ => (forall a. q a -> Event x (v a))
1900+ -> DynamicS x (PatchDMap k q)
1901+ -> Event x (DMap k v)
1902+mergeCheap nt = mergeGCheap' unMergeSubscribedParent getInitialSubscribers updateMe destroy
1903+ where
1904+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
1905+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1906+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1907+ (mOldSubd, newPs) <- case me of
1908+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1909+ Just e -> do
1910+ let s = subscriber $ return k
1911+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
1912+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1913+ let newParent = MergeSubscribedParent subscription
1914+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1915+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1916+ forM_ mOldSubd $ \oldSubd -> do
1917+ oldHeight <- liftIO $ getEventSubscribedHeight $
1918+ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1919+
1920+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1921+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1922+ foldM f ([], oldParents) $ DMap.toList p
1923+
1924+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
1925+ getInitialSubscribers initialParents subscriber = do
1926+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1927+ let s = subscriber $ return k
1928+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1929+ height <- liftIO $ getEventSubscribedHeight parentSubd
1930+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
1931+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1932+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1933+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1934+ )
1935+
1936+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1937+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1938+
1939+{-# INLINE [1] mergeCheapWithMove #-}
1940+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1941+ => (forall a. q a -> Event x (v a))
1942+ -> DynamicS x (PatchDMapWithMove k q)
1943+ -> Event x (DMap k v)
1944+mergeCheapWithMove nt = mergeGCheap' _mergeSubscribedParentWithMove_subscription getInitialSubscribers updateMe destroy
1945+ where
1946+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
1947+ updateMe subscriber heightBagRef oldParents p = do
1948+ -- Prepare new parents for insertion
1949+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
1950+ subscribeParent k e = do
1951+ keyRef <- liftIO $ newIORef k
1952+ let s = subscriber $ liftIO $ readIORef keyRef
1953+ subscription@(EventSubscription _ subd) <- subscribe e s
1954+ liftIO $ do
1955+ newParentHeight <- getEventSubscribedHeight subd
1956+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1957+ return $ MergeSubscribedParentWithMove subscription keyRef
1958+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
1959+ -- Collect old parents for deletion and update the keys of moved parents
1960+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1961+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1962+ Nothing -> do
1963+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $
1964+ _mergeSubscribedParentWithMove_subscription parent
1965+
1966+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1967+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1968+ Just toKey -> do
1969+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1970+ return Nothing
1971+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $
1972+ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1973+
1974+ return (toDelete, applyAlways p' oldParents)
1975+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
1976+ getInitialSubscribers initialParents subscriber = do
1977+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1978+ keyRef <- liftIO $ newIORef k
1979+ let s = subscriber $ liftIO $ readIORef keyRef
1980+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
1981+ height <- liftIO $ getEventSubscribedHeight parentSubd
1982+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1983+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1984+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1985+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1986+ )
1987+
1988+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1989+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1990+
1991+type MergeUpdateFunc k v x p s
1992+ = (forall a. EventM x (k a) -> Subscriber x (v a))
1993+ -> IORef HeightBag
1994+ -> DMap k s
1995+ -> p
1996+ -> EventM x ([EventSubscription x], DMap k s)
1997+
1998+type MergeGetSubscription x s = forall a. s a -> EventSubscription x
1999+
2000+type MergeInitFunc k v q x s
2001+ = DMap k q
2002+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
2003+ -> EventM x (DMap k v, [Height], DMap k s)
2004+
2005+type MergeDestroyFunc k s
2006+ = DMap k s
2007+ -> IO ()
2008+
2009+data Merge x k v s = Merge
2010+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
2011+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
2012+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
2013+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
2014+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
2015+ }
2016+
2017+invalidateMergeHeight :: Merge x k v s -> IO ()
2018+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
2019+
2020+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
2021+invalidateMergeHeight' heightRef sub = do
2022+ oldHeight <- readIORef heightRef
2023+ -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
2024+ when (oldHeight /= invalidHeight) $ do
2025+ writeIORef heightRef $! invalidHeight
2026+ subscriberInvalidateHeight sub oldHeight
2027+
2028+revalidateMergeHeight :: Merge x k v s -> IO ()
2029+revalidateMergeHeight m = do
2030+ currentHeight <- readIORef $ _merge_heightRef m
2031+
2032+ -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
2033+ when (currentHeight == invalidHeight) $ do
2034+ heights <- readIORef $ _merge_heightBagRef m
2035+ parents <- readIORef $ _merge_parentsRef m
2036+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
2037+ case heightBagSize heights `compare` DMap.size parents of
2038+ LT -> return ()
2039+ EQ -> do
2040+ let height = succHeight $ heightBagMax heights
2041+ traceInvalidateHeight $ "recalculateSubscriberHeight: height: " <> show height
2042+ writeIORef (_merge_heightRef m) $! height
2043+ subscriberRecalculateHeight (_merge_sub m) height
2044+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
2045+
2046+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
2047+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
2048+ vals <- liftIO $ readIORef $ _merge_accumRef m
2049+ -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us,
2050+ -- it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
2051+ liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty
2052+ --TODO: Assert that m is not empty
2053+ subscriberPropagate (_merge_sub m) vals
2054+
2055+checkCycle :: HasSpiderTimeline x => EventSubscribed x -> EventM x ()
2056+checkCycle subscribed = liftIO $ do
2057+ height <- readIORef (eventSubscribedHeightRef subscribed)
2058+
2059+ -- currentHeight <- getCurrentHeight
2060+ -- when (height <= currentHeight) $ if height /= invalidHeight
2061+ -- then do
2062+ -- myStack <- liftIO $ whoCreatedIORef undefined --TODO
2063+ -- error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
2064+ -- else liftIO $
2065+ when (height == invalidHeight) $
2066+#ifdef DEBUG_CYCLES
2067+ do
2068+ nodesInvolvedInCycle <- walkInvalidHeightParents subscribed
2069+ stacks <- forM nodesInvolvedInCycle whoCreatedEventSubscribed
2070+ throwIO (EventLoopException stacks)
2071+#else
2072+ throwIO EventLoopException
2073+#endif
2074+
9802075
981−merge :: GCompare k => DMap (WrapArg Event k) -> Event (DMap k)
982−merge m = EventMerge $ Merge
983− { mergeParents = m
984− , mergeSubscribed = unsafeNewIORef m Nothing
2076+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => EventSubscribed x -> Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
2077+mergeSubscriber subscribed m getKey = Subscriber
2078+ { subscriberPropagate = \a -> do
2079+ oldM <- liftIO $ readIORef $ _merge_accumRef m
2080+ k <- getKey
2081+ let newM = DMap.insertWith (error "Same key fired multiple times for Merge") k a oldM
2082+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
2083+ liftIO $ writeIORef (_merge_accumRef m) $! newM
2084+ when (DMap.null oldM) $ do -- Only schedule the firing once
2085+ height <- liftIO $ readIORef $ _merge_heightRef m
2086+ checkCycle subscribed
2087+
2088+ scheduleMergeSelf m height
2089+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
2090+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
2091+ invalidateMergeHeight m
2092+ , subscriberRecalculateHeight = \new -> do
2093+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
2094+ revalidateMergeHeight m
9852095 }
9862096
987−newtype EventSelector k = EventSelector { select :: forall a. k a -> Event a }
2097+--TODO: Be able to run as much of this as possible promptly
2098+updateMerge :: (HasSpiderTimeline x, GCompare k) => EventSubscribed x -> Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
2099+updateMerge subscribed m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
2100+ where updateMe = do
2101+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
2102+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber subscribed m) (_merge_heightBagRef m) oldParents p
2103+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
2104+ return subscriptionsToKill
2105+
2106+{-# INLINE mergeGCheap' #-}
2107+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
2108+ => MergeGetSubscription x s -> MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
2109+mergeGCheap' getParent getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
2110+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
2111+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
2112+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
2113+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
2114+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
2115+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2116+
2117+ let subscribed = EventSubscribed
2118+ { eventSubscribedHeightRef = heightRef
2119+ , eventSubscribedRetained = toAny (parentsRef, changeSubdRef)
2120+#ifdef DEBUG_CYCLES
2121+ , eventSubscribedGetParents = do
2122+ let getParent' (_ :=> v) = _eventSubscription_subscribed (getParent v)
2123+ fmap getParent' . DMap.toList <$> readIORef parentsRef
2124+ , eventSubscribedHasOwnHeightRef = False
2125+ , eventSubscribedWhoCreated = whoCreatedIORef heightRef
2126+#endif
2127+ }
2128+
2129+ m = Merge
2130+ { _merge_parentsRef = parentsRef
2131+ , _merge_heightBagRef = heightBagRef
2132+ , _merge_heightRef = heightRef
2133+ , _merge_sub = sub
2134+ , _merge_accumRef = accumRef
2135+ }
2136+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber subscribed m
2137+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
2138+ myHeight = if invalidHeight `elem` heights
2139+ then invalidHeight
2140+ else succHeight $ heightBagMax myHeightBag
2141+ currentHeight <- getCurrentHeight
2142+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
2143+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
2144+ else (Nothing, dm)
2145+ unless (DMap.null accum) $ scheduleMergeSelf m myHeight
2146+ liftIO $ writeIORef accumRef $! accum
2147+ liftIO $ writeIORef heightRef $! myHeight
2148+ liftIO $ writeIORef heightBagRef $! myHeightBag
2149+ liftIO $ writeIORef parentsRef $! initialParentState
2150+ defer $ SomeMergeInit $ do
2151+ let changeSubscriber = Subscriber
2152+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2153+ tracePropagate (Proxy :: Proxy x) "SubscriberMerge/Change"
2154+ defer $ updateMerge subscribed m updateFunc a
2155+ , subscriberInvalidateHeight = \_ -> return ()
2156+ , subscriberRecalculateHeight = \_ -> return ()
2157+ }
2158+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) changeSubscriber
2159+ forM_ change $ \c -> defer $ updateMerge subscribed m updateFunc c
2160+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2161+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2162+ -- its subscription.
2163+ liftIO $ writeIORef changeSubdRef (changeSubscriber, changeSubscription)
2164+ let unsubscribeAll = destroy =<< readIORef parentsRef
2165+
2166+ return (EventSubscription unsubscribeAll subscribed, occ)
2167+
2168+
2169+mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
2170+mergeInt = cacheEvent . mergeIntCheap
2171+
2172+{-# INLINABLE mergeIntCheap #-}
2173+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
2174+mergeIntCheap d = Event $ \sub -> do
2175+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
2176+ accum <- liftIO $ FastMutableIntMap.newEmpty
2177+ heightRef <- liftIO $ newIORef zeroHeight
2178+ heightBagRef <- liftIO $ newIORef heightBagEmpty
2179+ parents <- liftIO $ FastMutableIntMap.newEmpty
2180+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2181+ let subscribed = EventSubscribed
2182+ { eventSubscribedHeightRef = heightRef
2183+ , eventSubscribedRetained = toAny (parents, changeSubdRef)
2184+#ifdef DEBUG_CYCLES
2185+ , eventSubscribedGetParents = fmap (_eventSubscription_subscribed . snd) <$> FastMutableIntMap.toList parents
2186+ , eventSubscribedHasOwnHeightRef = False
2187+ , eventSubscribedWhoCreated = whoCreatedIORef heightRef
2188+#endif
2189+ }
2190+ let scheduleSelf = do
2191+ height <- liftIO $ readIORef $ heightRef
2192+ scheduleMerge' height heightRef $ do
2193+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
2194+ subscriberPropagate sub vals
2195+ invalidateMyHeight = invalidateMergeHeight' heightRef sub
2196+ recalculateMyHeight = do
2197+ currentHeight <- readIORef heightRef
2198+ 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?
2199+ heights <- readIORef heightBagRef
2200+ numParents <- FastMutableIntMap.size parents
2201+ case heightBagSize heights `compare` numParents of
2202+ LT -> return ()
2203+ EQ -> do
2204+ let height = succHeight $ heightBagMax heights
2205+ traceInvalidateHeight $ "recalculateSubscriberHeight: height: " <> show height
2206+ writeIORef heightRef $! height
2207+ subscriberRecalculateHeight sub height
2208+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
2209+ mySubscriber k = Subscriber
2210+ { subscriberPropagate = \a -> do
2211+ checkCycle subscribed
2212+
2213+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2214+ liftIO $ FastMutableIntMap.insert accum k a
2215+ when wasEmpty scheduleSelf
2216+ , subscriberInvalidateHeight = \old -> do
2217+ modifyIORef' heightBagRef $ heightBagRemove old
2218+ invalidateMyHeight
2219+ , subscriberRecalculateHeight = \new -> do
2220+ modifyIORef' heightBagRef $ heightBagAdd new
2221+ recalculateMyHeight
2222+ }
2223+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
2224+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
2225+ liftIO $ do
2226+ forM_ parentOcc $ FastMutableIntMap.insert accum k
2227+ FastMutableIntMap.insert parents k subscription
2228+ height <- getEventSubscribedHeight parentSubd
2229+ if height == invalidHeight
2230+ then writeIORef heightRef invalidHeight
2231+ else do
2232+ modifyIORef' heightBagRef $ heightBagAdd height
2233+ modifyIORef' heightRef $ \oldHeight ->
2234+ if oldHeight == invalidHeight
2235+ then invalidHeight
2236+ else max (succHeight height) oldHeight
2237+ myHeight <- liftIO $ readIORef heightRef
2238+ currentHeight <- getCurrentHeight
2239+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2240+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2241+ then if isEmpty
2242+ then return Nothing
2243+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2244+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2245+ return Nothing
2246+ defer $ SomeMergeInit $ do
2247+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2248+ where
2249+ u = do
2250+ let f k newParent = do
2251+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2252+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2253+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2254+ return subscription
2255+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2256+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2257+ liftIO $ for_ oldParents $ \oldParent -> do
2258+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2259+
2260+ print ("updateMe", oldParentHeight)
2261+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2262+ return $ IntMap.elems oldParents
2263+ let changeSubscriber = Subscriber
2264+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2265+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2266+ defer $ updateMe a
2267+ , subscriberInvalidateHeight = \_ -> return ()
2268+ , subscriberRecalculateHeight = \_ -> return ()
2269+ }
2270+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) changeSubscriber
2271+ forM_ change $ \c -> defer $ updateMe c
2272+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2273+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2274+ -- its subscription.
2275+ liftIO $ writeIORef changeSubdRef (changeSubscriber, changeSubscription)
2276+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2277+
2278+
2279+ return (EventSubscription unsubscribeAll subscribed, occ)
9882280
989−fan :: GCompare k => Event (DMap k) -> EventSelector k
990−fan e =
2281+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2282+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
2283+
2284+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2285+fanG e = unsafePerformIO $ do
2286+ ref <- newIORef Nothing
9912287 let f = Fan
9922288 { fanParent = e
993− , fanSubscribed = unsafeNewIORef e Nothing
2289+ , fanSubscribed = ref
9942290 }
995− in EventSelector $ \k -> EventFan k f
996−
997−-- | Run an event action outside of a frame
998−runFrame :: EventM a -> IO a
999−runFrame a = do
2291+ pure $ EventSelectorG $ \k -> eventFan k f
2292+
2293+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2294+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2295+ holdInits <- liftIO $ readIORef holdInitRef
2296+ dynInits <- liftIO $ readIORef dynInitRef
2297+ mergeInits <- liftIO $ readIORef mergeInitRef
2298+ unless (null holdInits && null dynInits && null mergeInits) $ do
2299+ liftIO $ writeIORef holdInitRef []
2300+ liftIO $ writeIORef dynInitRef []
2301+ liftIO $ writeIORef mergeInitRef []
2302+ mapM_ initHold holdInits
2303+ mapM_ initDyn dynInits
2304+ mapM_ unSomeMergeInit mergeInits
2305+ runHoldInits holdInitRef dynInitRef mergeInitRef
2306+
2307+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2308+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2309+
2310+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2311+initDyn (SomeDynInit d) = void $ getDynHold d
2312+
2313+newEventEnv :: IO (EventEnv x)
2314+newEventEnv = do
10002315 toAssignRef <- newIORef [] -- This should only actually get used when events are firing
10012316 holdInitRef <- newIORef []
1002− heightRef <- newIORef 0
2317+ dynInitRef <- newIORef []
2318+ mergeUpdateRef <- newIORef []
2319+ mergeInitRef <- newIORef []
2320+ heightRef <- newIORef zeroHeight
10032321 toClearRef <- newIORef []
2322+ toClearIntRef <- newIORef []
2323+ toClearRootRef <- newIORef []
10042324 coincidenceInfosRef <- newIORef []
1005− delayedRef <- liftIO $ newIORef IntMap.empty
1006− result <- flip runEventM (EventEnv toAssignRef holdInitRef toClearRef heightRef coincidenceInfosRef delayedRef) $ do
1007− result <- a
1008− let runHoldInits = do
1009− holdInits <- liftIO $ readIORef holdInitRef
1010− if null holdInits then return () else do
1011− liftIO $ writeIORef holdInitRef []
1012− forM_ holdInits $ \(SomeHoldInit e h) -> subscribeHold e h
1013− runHoldInits
1014− runHoldInits -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
1015− return result
1016− toClear <- readIORef toClearRef
1017− forM_ toClear $ \(SomeMaybeIORef ref) -> writeIORef ref Nothing
1018− toAssign <- readIORef toAssignRef
2325+ delayedRef <- newIORef IntMap.empty
2326+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2327+
2328+clearEventEnv :: EventEnv x -> IO ()
2329+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2330+ writeIORef toAssignRef []
2331+ writeIORef holdInitRef []
2332+ writeIORef dynInitRef []
2333+ writeIORef mergeUpdateRef []
2334+ writeIORef mergeInitRef []
2335+ writeIORef heightRef zeroHeight
2336+ writeIORef toClearRef []
2337+ writeIORef toClearIntRef []
2338+ writeIORef toClearRootRef []
2339+ writeIORef coincidenceInfosRef []
2340+ writeIORef delayedRef IntMap.empty
2341+
2342+-- | Run an event action outside of a frame
2343+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2344+runFrame a = SpiderHost $ do
2345+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
2346+ let go = do
2347+ result <- a
2348+ 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
2349+ return result
2350+ result <- runEventM go
2351+ toClear <- readIORef $ eventEnvClears env
2352+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2353+ toClearInt <- readIORef $ eventEnvIntClears env
2354+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2355+ toClearRoot <- readIORef $ eventEnvRootClears env
2356+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2357+ toAssign <- readIORef $ eventEnvAssignments env
10192358 toReconnectRef <- newIORef []
1020− forM_ toAssign $ \(SomeAssignment h v) -> do
1021− writeIORef (holdValue h) v
1022− writeIORef (holdInvalidators h) =<< invalidate toReconnectRef =<< readIORef (holdInvalidators h)
1023− coincidenceInfos <- readIORef coincidenceInfosRef
1024− forM_ coincidenceInfos $ \(SomeCoincidenceInfo wsubInner subInner mcs) -> do
1025− touch subInner
1026− finalize wsubInner
1027− mapM_ invalidateCoincidenceHeight mcs
2359+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2360+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2361+ writeIORef vRef v
2362+ traceInvalidate $ "Invalidating Hold"
2363+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2364+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2365+ writeIORef (eventEnvMergeUpdates env) []
2366+ tracePropagate (Proxy::Proxy x) $ "Updating merges"
2367+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2368+ tracePropagate (Proxy::Proxy x) $ "Updating merges done"
10282369 toReconnect <- readIORef toReconnectRef
1029− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1030− wsub <- readIORef $ switchSubscribedSelfWeak subscribed
1031− finalize wsub
2370+ clearEventEnv env
2371+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2372+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
10322373 wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2374+ traceInvalidate $ "Finalizing invalidator for Switch" <> showNodeId subscribed
10332375 finalize wi
1034− let !i = switchSubscribedOwnInvalidator subscribed
2376+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
10352377 wi' <- mkWeakPtrWithDebug i "wi'"
2378+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
10362379 writeIORef (switchSubscribedBehaviorParents subscribed) []
1037− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed))
2380+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2381+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2382+ 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
10382383 --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1039− let !sub = switchSubscribedSelf subscribed -- Must be done strictly, or the weak pointer will refer to a useless thunk
1040− wsub' <- mkWeakPtrWithDebug sub "wsub'"
1041− writeIORef (switchSubscribedSelfWeak subscribed) wsub'
1042− subd' <- runFrame $ subscribe e $ WeakSubscriberSimple wsub' --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient
2384+ sub <- newSubscriberSwitch subscribed
2385+ 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
10432386 {-
1044− stackTrace <- liftIO $ liftM renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1045− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2387+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2388+ liftIO $ debugStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
10462389 EventRoot _ -> "EventRoot"
10472390 EventNever -> "EventNever"
10482391 _ -> "something else"
10492392 -}
1050− writeIORef (switchSubscribedCurrentParent subscribed) subd'
1051− parentHeight <- readIORef $ eventSubscribedHeightRef subd'
2393+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2394+ return oldSubscription
2395+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2396+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2397+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2398+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2399+ parentHeight <- getEventSubscribedHeight subd'
10522400 myHeight <- readIORef $ switchSubscribedHeight subscribed
1053− if parentHeight == myHeight then return () else do
1054− writeIORef (switchSubscribedHeight subscribed) parentHeight
1055− mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1056− forM_ coincidenceInfos $ \(SomeCoincidenceInfo _ _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2401+ when (parentHeight /= myHeight) $ do
2402+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2403+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2404+ 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
2405+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2406+ unsubscribe subscription
2407+ mapM_ invalidateCoincidenceHeight mcs
2408+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2409+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
10572410 forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1058− mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
2411+ height <- calculateSwitchHeight subscribed
2412+ updateSwitchHeight height subscribed
10592413 return result
10602414
1061−invalidHeight :: Int
1062−invalidHeight = -1000
1063−
1064−invalidateSubscriberHeight :: WeakSubscriber a -> IO ()
1065−invalidateSubscriberHeight ws = do
1066− ms <- deRefWeakSubscriber ws
1067− case ms of
1068− Nothing -> return () --TODO: cleanup?
1069− Just s -> case s of
1070− SubscriberPush _ subscribed -> do
1071− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1072− mapM_ invalidateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed)
1073− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1074− SubscriberMerge _ subscribed -> do
1075− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1076− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1077− when (oldHeight /= invalidHeight) $ do
1078− writeIORef (mergeSubscribedHeight subscribed) $ invalidHeight
1079− mapM_ invalidateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed)
1080− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1081− SubscriberFan subscribed -> do
1082− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1083− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1084− forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ invalidateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ())
1085− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1086− SubscriberHold _ -> return ()
1087− SubscriberSwitch subscribed -> do
1088− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1089− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1090− when (oldHeight /= invalidHeight) $ do
1091− writeIORef (switchSubscribedHeight subscribed) $ invalidHeight
1092− mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1093− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1094− SubscriberCoincidenceOuter subscribed -> do
1095− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1096− invalidateCoincidenceHeight subscribed
1097− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1098− SubscriberCoincidenceInner subscribed -> do
1099− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1100− invalidateCoincidenceHeight subscribed
1101− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1102−
1103−invalidateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
2415+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2416+
2417+{-# INLINE zeroHeight #-}
2418+zeroHeight :: Height
2419+zeroHeight = Height 0
2420+
2421+{-# INLINE invalidHeight #-}
2422+invalidHeight :: Height
2423+invalidHeight = Height (-1000)
2424+
2425+#ifdef DEBUG_CYCLES
2426+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2427+{-# INLINE invalidHeightBeingTraversed #-}
2428+invalidHeightBeingTraversed :: Height
2429+invalidHeightBeingTraversed = Height (-1001)
2430+#endif
2431+
2432+{-# INLINE succHeight #-}
2433+succHeight :: Height -> Height
2434+succHeight h@(Height a) =
2435+ if h == invalidHeight
2436+ then invalidHeight
2437+ else Height $ succ a
2438+
2439+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
11042440invalidateCoincidenceHeight subscribed = do
11052441 oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
11062442 when (oldHeight /= invalidHeight) $ do
1107− writeIORef (coincidenceSubscribedHeight subscribed) $ invalidHeight
1108− mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed)
1109−
1110−--TODO: The recalculation algorithm seems a bit funky; make sure it doesn't miss stuff or hit stuff twice; also, it should probably be lazy
1111−
1112−recalculateSubscriberHeight :: WeakSubscriber a -> IO ()
1113−recalculateSubscriberHeight ws = do
1114− ms <- deRefWeakSubscriber ws
1115− case ms of
1116− Nothing -> return () --TODO: cleanup?
1117− Just s -> case s of
1118− SubscriberPush _ subscribed -> do
1119− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1120− mapM_ recalculateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed)
1121− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1122− SubscriberMerge _ subscribed -> do
1123− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1124− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1125− when (oldHeight == invalidHeight) $ do
1126− height <- calculateMergeHeight subscribed
1127− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1128− when (height /= invalidHeight) $ do -- If height == invalidHeight, that means some of the prereqs have not yet been recomputed; when they do recompute, they'll catch this node again --TODO: this is O(n*m), where n is the number of children of this noe and m is the number that have been invalidated
1129− writeIORef (mergeSubscribedHeight subscribed) height
1130− mapM_ recalculateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed)
1131− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1132− SubscriberFan subscribed -> do
1133− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1134− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1135− forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ recalculateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ())
1136− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1137− SubscriberHold _ -> return ()
1138− SubscriberSwitch subscribed -> do
1139− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1140− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1141− when (oldHeight == invalidHeight) $ do
1142− height <- calculateSwitchHeight subscribed
1143− when (height /= invalidHeight) $ do
1144− writeIORef (switchSubscribedHeight subscribed) height
1145− mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed)
1146− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1147− SubscriberCoincidenceOuter subscribed -> do
1148− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1149− void $ recalculateCoincidenceHeight subscribed
1150− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1151− SubscriberCoincidenceInner subscribed -> do
1152− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1153− void $ recalculateCoincidenceHeight subscribed
1154− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1155−
1156−recalculateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
2443+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2444+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2445+
2446+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2447+updateSwitchHeight new subscribed = do
2448+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2449+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2450+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2451+ writeIORef (switchSubscribedHeight subscribed) $! new
2452+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2453+
2454+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
11572455recalculateCoincidenceHeight subscribed = do
11582456 oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1159− when (oldHeight == invalidHeight) $ do
2457+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
11602458 height <- calculateCoincidenceHeight subscribed
11612459 when (height /= invalidHeight) $ do
1162− writeIORef (coincidenceSubscribedHeight subscribed) height
1163− mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: This should probably be mandatory, just like with the merge and switch ones
1164−
1165−calculateMergeHeight :: MergeSubscribed k -> IO Int
1166−calculateMergeHeight subscribed = if DMap.null (mergeSubscribedParents subscribed) then return 0 else do
1167− heights <- forM (DMap.toList $ mergeSubscribedParents subscribed) $ \(WrapArg _ :=> es) -> do
1168− readIORef $ eventSubscribedHeightRef es
1169− return $ if any (== invalidHeight) heights then invalidHeight else succ $ Prelude.maximum heights --TODO: Replace 'any' with invalidHeight-preserving 'maximum'
2460+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2461+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
11702462
1171−calculateSwitchHeight :: SwitchSubscribed a -> IO Int
1172−calculateSwitchHeight subscribed = readIORef . eventSubscribedHeightRef =<< readIORef (switchSubscribedCurrentParent subscribed)
2463+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2464+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
11732465
1174−calculateCoincidenceHeight :: CoincidenceSubscribed a -> IO Int
2466+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
11752467calculateCoincidenceHeight subscribed = do
1176− outerHeight <- readIORef $ eventSubscribedHeightRef $ coincidenceSubscribedOuterParent subscribed
1177− innerHeight <- maybe (return 0) (readIORef . eventSubscribedHeightRef) =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2468+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2469+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
11782470 return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
11792471
1180−{-
1181−recalculateEventSubscribedHeight :: EventSubscribed a -> IO Int
1182−recalculateEventSubscribedHeight es = case es of
1183− EventSubscribedRoot _ -> return 0
1184− EventSubscribedNever -> return 0
1185− EventSubscribedPush subscribed -> recalculateEventSubscribedHeight $ pushSubscribedParent subscribed
1186− EventSubscribedMerge subscribed -> do
1187− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1188− if oldHeight /= invalidHeight then return oldHeight else do
1189− height <- calculateMergeHeight subscribed
1190− writeIORef (mergeSubscribedHeight subscribed) height
1191− return height
1192− EventSubscribedFan _ subscribed -> recalculateEventSubscribedHeight $ fanSubscribedParent subscribed
1193− EventSubscribedSwitch subscribed -> do
1194− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1195− if oldHeight /= invalidHeight then return oldHeight else do
1196− height <- calculateSwitchHeight subscribed
1197− writeIORef (switchSubscribedHeight subscribed) height
1198− return height
1199− EventSubscribedCoincidence subscribed -> recalculateCoincidenceHeight subscribed
1200−-}
1201−
1202−data SomeSwitchSubscribed = forall a. SomeSwitchSubscribed (SwitchSubscribed a)
1203−
1204−debugInvalidate :: Bool
1205−debugInvalidate = False
2472+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
12062473
1207−invalidate :: IORef [SomeSwitchSubscribed] -> WeakList Invalidator -> IO (WeakList Invalidator)
2474+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
12082475invalidate toReconnectRef wis = do
12092476 forM_ wis $ \wi -> do
12102477 mi <- deRefWeak wi
12112478 case mi of
12122479 Nothing -> do
1213− when debugInvalidate $ liftIO $ putStrLn "invalidate Dead"
2480+ traceInvalidate "invalidate Dead"
12142481 return () --TODO: Should we clean this up here?
12152482 Just i -> do
12162483 finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
12172484 case i of
12182485 InvalidatorPull p -> do
1219− when debugInvalidate $ liftIO $ putStrLn "invalidate Pull"
2486+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
12202487 mVal <- readIORef $ pullValue p
12212488 forM_ mVal $ \val -> do
12222489 writeIORef (pullValue p) Nothing
1223− writeIORef (pullSubscribedInvalidators val) =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2490+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
12242491 InvalidatorSwitch subscribed -> do
1225− when debugInvalidate $ liftIO $ putStrLn "invalidate Switch"
2492+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
12262493 modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
12272494 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
12282495
@@ -1230,117 +2497,434 @@ invalidate toReconnectRef wis = do
12302497-- Reflex integration
12312498--------------------------------------------------------------------------------
12322499
1233−data Spider
1234−
1235−instance R.Reflex Spider where
1236− newtype Behavior Spider a = SpiderBehavior { unSpiderBehavior :: Behavior a }
1237− newtype Event Spider a = SpiderEvent { unSpiderEvent :: Event a }
1238− type PullM Spider = BehaviorM
1239− type PushM Spider = EventM
1240− {-# INLINE never #-}
1241− {-# INLINE constant #-}
1242− never = SpiderEvent EventNever
1243− constant = SpiderBehavior . BehaviorConst
1244− push f = SpiderEvent. push f . unSpiderEvent
1245− pull = SpiderBehavior . pull
1246− merge = SpiderEvent . merge . (unsafeCoerce :: DMap (WrapArg (R.Event Spider) k) -> DMap (WrapArg Event k))
1247− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1248− switch = SpiderEvent . switch . (unsafeCoerce :: Behavior (R.Event Spider a) -> Behavior (Event a)) . unSpiderBehavior
1249− coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event (R.Event Spider a) -> Event (Event a)) . unSpiderEvent
1250−
1251−instance R.MonadSample Spider SpiderHost where
1252− {-# INLINE sample #-}
1253− sample = SpiderHost . readBehavior . unSpiderBehavior
1254−
1255−instance R.MonadHold Spider SpiderHost where
1256− hold v0 = SpiderHost . liftM SpiderBehavior . runFrame . hold v0 . unSpiderEvent
1257−
1258−instance R.MonadSample Spider BehaviorM where
1259− {-# INLINE sample #-}
1260− sample = readBehaviorTracked . unSpiderBehavior
1261−
1262−instance R.MonadSample Spider EventM where
1263− {-# INLINE sample #-}
1264− sample = liftIO . readBehavior . unSpiderBehavior
1265−
1266−instance R.MonadHold Spider EventM where
1267− {-# INLINE hold #-}
1268− hold v0 e = SpiderBehavior <$> hold v0 (unSpiderEvent e)
1269−
1270−newtype RootTrigger a = RootTrigger (IORef [WeakSubscriber a], IORef (Maybe a))
1271−
1272−instance R.ReflexHost Spider where
1273− type EventTrigger Spider = RootTrigger
1274− type EventHandle Spider = R.Event Spider
1275− type HostFrame Spider = SpiderHostFrame
1276−
1277−instance R.MonadReadEvent Spider ResultM where
1278− {-# INLINE readEvent #-}
1279− readEvent = liftM (fmap return) . readEvent . unSpiderEvent
1280−
1281−--TODO: Can probably get rid of this now that we're not using it for performEvent
1282−instance MonadTypedId EventM where
1283− type TypedId EventM = TypedId IO
1284− {-# INLINE getTypedId #-}
1285− getTypedId = do
1286− liftIO getTypedId
1287−
1288−instance MonadRef EventM where
1289− type Ref EventM = Ref IO
1290− {-# INLINE newRef #-}
1291− {-# INLINE readRef #-}
1292− {-# INLINE writeRef #-}
1293− {-# INLINE atomicModifyRef #-}
2500+-- | Designates the default, global Spider timeline
2501+data SpiderTimeline x
2502+type role SpiderTimeline nominal
2503+
2504+-- | The default, global Spider environment
2505+type Spider = SpiderTimeline Global
2506+
2507+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where
2508+ {-# INLINABLE sample #-}
2509+ sample (SpiderBehavior b) = readBehaviorUntracked b
2510+
2511+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where
2512+ {-# INLINABLE hold #-}
2513+ hold = holdSpiderEventM
2514+ {-# INLINABLE holdDyn #-}
2515+ holdDyn = holdDynSpiderEventM
2516+ {-# INLINABLE holdIncremental #-}
2517+ holdIncremental = holdIncrementalSpiderEventM
2518+ {-# INLINABLE buildDynamic #-}
2519+ buildDynamic = buildDynamicSpiderEventM
2520+ {-# INLINABLE headE #-}
2521+ headE = R.slowHeadE
2522+-- headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e
2523+ {-# INLINABLE now #-}
2524+ now = nowSpiderEventM
2525+
2526+instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2527+ {-# INLINABLE sample #-}
2528+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2529+
2530+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2531+ {-# INLINABLE sample #-}
2532+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2533+
2534+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2535+ {-# INLINABLE hold #-}
2536+ hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e
2537+ {-# INLINABLE holdDyn #-}
2538+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e
2539+ {-# INLINABLE holdIncremental #-}
2540+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e
2541+ {-# INLINABLE buildDynamic #-}
2542+ buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e
2543+ {-# INLINABLE headE #-}
2544+ headE = R.slowHeadE
2545+-- headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2546+ {-# INLINABLE now #-}
2547+ now = SpiderPushM nowSpiderEventM
2548+
2549+
2550+instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where
2551+ {-# INLINE return #-}
2552+ return = pure
2553+ {-# INLINE (>>=) #-}
2554+ x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
2555+ {-# INLINE (>>) #-}
2556+ (>>) = (*>)
2557+#if !MIN_VERSION_base(4,13,0)
2558+ {-# INLINE fail #-}
2559+ fail _ = error "Dynamic does not support 'fail'"
2560+#endif
2561+
2562+{-# INLINABLE newJoinDyn #-}
2563+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2564+newJoinDyn d =
2565+ let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
2566+ eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
2567+ eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d
2568+ eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
2569+ v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
2570+ in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
2571+
2572+instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2573+ fmap = mapDynamicSpider
2574+ x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
2575+
2576+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2577+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2578+{-# INLINE [1] mapDynamicSpider #-}
2579+
2580+instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
2581+ pure = SpiderDynamic . dynamicConst
2582+#if MIN_VERSION_base(4,10,0)
2583+ liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)
2584+#endif
2585+ SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b
2586+ a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]
2587+ (<*) = flip (*>) -- There are no effects, so order doesn't matter
2588+
2589+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)
2590+holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2591+
2592+holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2593+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2594+
2595+holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)
2596+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2597+
2598+buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)
2599+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2600+
2601+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where
2602+ {-# INLINABLE hold #-}
2603+ hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e
2604+ {-# INLINABLE holdDyn #-}
2605+ holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e
2606+ {-# INLINABLE holdIncremental #-}
2607+ holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e
2608+ {-# INLINABLE buildDynamic #-}
2609+ buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e
2610+ {-# INLINABLE headE #-}
2611+ headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e
2612+ {-# INLINABLE now #-}
2613+ now = runFrame . runSpiderHostFrame $ Reflex.Class.now
2614+
2615+
2616+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2617+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2618+
2619+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2620+ {-# INLINABLE hold #-}
2621+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2622+ {-# INLINABLE holdDyn #-}
2623+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e
2624+ {-# INLINABLE holdIncremental #-}
2625+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e
2626+ {-# INLINABLE buildDynamic #-}
2627+ buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e
2628+ {-# INLINABLE headE #-}
2629+ headE = R.slowHeadE
2630+-- headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e
2631+ {-# INLINABLE now #-}
2632+ now = SpiderHostFrame Reflex.Class.now
2633+
2634+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where
2635+ {-# INLINABLE sample #-}
2636+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2637+
2638+instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2639+ {-# INLINABLE sample #-}
2640+ sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample
2641+
2642+instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2643+ {-# INLINABLE hold #-}
2644+ hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e
2645+ {-# INLINABLE holdDyn #-}
2646+ holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e
2647+ {-# INLINABLE holdIncremental #-}
2648+ holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e
2649+ {-# INLINABLE buildDynamic #-}
2650+ buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e
2651+ {-# INLINABLE headE #-}
2652+ headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e
2653+ {-# INLINABLE now #-}
2654+ now = Reflex.Spider.Internal.ReadPhase Reflex.Class.now
2655+
2656+--------------------------------------------------------------------------------
2657+-- Deprecated items
2658+--------------------------------------------------------------------------------
2659+
2660+-- | 'SpiderEnv' is the old name for 'SpiderTimeline'
2661+{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}
2662+type SpiderEnv = SpiderTimeline
2663+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2664+ {-# INLINABLE subscribeEvent #-}
2665+ subscribeEvent e = SpiderHostFrame $ do
2666+ --TODO: Unsubscribe eventually (manually and/or with weak ref)
2667+ val <- liftIO $ newIORef Nothing
2668+ subscription <- subscribe (unSpiderEvent e) $ Subscriber
2669+ { subscriberPropagate = \a -> do
2670+ liftIO $ writeIORef val $ Just a
2671+ scheduleClear val
2672+ , subscriberInvalidateHeight = \_ -> return ()
2673+ , subscriberRecalculateHeight = \_ -> return ()
2674+ }
2675+ return $ SpiderEventHandle
2676+ { spiderEventHandleSubscription = subscription
2677+ , spiderEventHandleValue = val
2678+ }
2679+
2680+instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where
2681+ type EventTrigger (SpiderTimeline x) = RootTrigger x
2682+ type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2683+ type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2684+
2685+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where
2686+ {-# NOINLINE readEvent #-}
2687+ readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do
2688+ result <- readIORef $ spiderEventHandleValue h
2689+ touch h
2690+ return result
2691+
2692+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2693+ newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO
2694+ newFanEventWithTrigger f = SpiderHost $ do
2695+ es <- newFanEventWithTriggerIO f
2696+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2697+
2698+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2699+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2700+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2701+ es <- newFanEventWithTriggerIO f
2702+ return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es
2703+
2704+instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2705+ {-# INLINABLE subscribeEvent #-}
2706+ subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent
2707+
2708+instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2709+ type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x
2710+ fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a
2711+ runHostFrame = runFrame . runSpiderHostFrame
2712+
2713+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2714+unsafeNewSpiderTimelineEnv = do
2715+ lock <- newMVar ()
2716+ env <- newEventEnv
2717+#ifdef DEBUG
2718+ depthRef <- newIORef 0
2719+#endif
2720+ return $ STE $ SpiderTimelineEnv
2721+ { _spiderTimeline_lock = lock
2722+ , _spiderTimeline_eventEnv = env
2723+#ifdef DEBUG
2724+ , _spiderTimeline_depth = depthRef
2725+#endif
2726+ }
2727+
2728+-- | Create a new SpiderTimelineEnv
2729+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2730+newSpiderTimeline = withSpiderTimeline (pure . Some)
2731+
2732+data LocalSpiderTimeline (x :: Type) s
2733+
2734+instance Reifies s (SpiderTimelineEnv x) =>
2735+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2736+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
2737+
2738+localSpiderTimeline
2739+ :: proxy s
2740+ -> SpiderTimelineEnv x
2741+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2742+localSpiderTimeline _ = coerce
2743+
2744+-- | Pass a new timeline to the given function.
2745+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2746+withSpiderTimeline k = do
2747+ env <- unsafeNewSpiderTimelineEnv
2748+ reify env $ \s -> k $ localSpiderTimeline s env
2749+
2750+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2751+
2752+type ComputeM = EventM
2753+
2754+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2755+
2756+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2757+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2758+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2759+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2760+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2761+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
2762+ type PullM (SpiderTimeline x) = SpiderPullM x
2763+ type PushM (SpiderTimeline x) = SpiderPushM x
2764+ {-# INLINABLE never #-}
2765+ never = SpiderEvent eventNever
2766+ {-# INLINABLE constant #-}
2767+ constant = SpiderBehavior . behaviorConst
2768+ {-# INLINE push #-}
2769+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2770+ {-# INLINE pushCheap #-}
2771+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2772+ {-# INLINABLE pull #-}
2773+ pull = SpiderBehavior . pull . coerce
2774+ {-# INLINABLE fanG #-}
2775+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2776+ {-# INLINABLE mergeG #-}
2777+ mergeG
2778+ :: forall k2 (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2779+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2780+ -> DMap k q
2781+ -> R.Event (SpiderTimeline x) (DMap k v)
2782+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
2783+ {-# INLINABLE switch #-}
2784+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2785+ {-# INLINABLE coincidence #-}
2786+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2787+ {-# INLINABLE current #-}
2788+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2789+ {-# INLINABLE updated #-}
2790+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
2791+ {-# INLINABLE unsafeBuildDynamic #-}
2792+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2793+ {-# INLINABLE unsafeBuildIncremental #-}
2794+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2795+ {-# INLINABLE mergeIncrementalG #-}
2796+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2797+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2798+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
2799+ {-# INLINABLE currentIncremental #-}
2800+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2801+ {-# INLINABLE updatedIncremental #-}
2802+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2803+ {-# INLINABLE incrementalToDynamic #-}
2804+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2805+ c <- readBehaviorUntracked $ dynamicCurrent i
2806+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2807+ eventCoercion Coercion = Coercion
2808+ behaviorCoercion Coercion = Coercion
2809+ dynamicCoercion Coercion = Coercion
2810+ incrementalCoercion Coercion Coercion = Coercion
2811+ {-# INLINABLE mergeIntIncremental #-}
2812+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
2813+ {-# INLINABLE fanInt #-}
2814+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2815+
2816+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2817+
2818+data SpiderEventHandle x a = SpiderEventHandle
2819+ { spiderEventHandleSubscription :: EventSubscription x
2820+ , spiderEventHandleValue :: IORef (Maybe a)
2821+ }
2822+
2823+instance MonadRef (EventM x) where
2824+ type Ref (EventM x) = Ref IO
2825+ {-# INLINABLE newRef #-}
2826+ {-# INLINABLE readRef #-}
2827+ {-# INLINABLE writeRef #-}
12942828 newRef = liftIO . newRef
12952829 readRef = liftIO . readRef
12962830 writeRef r a = liftIO $ writeRef r a
2831+
2832+instance MonadAtomicRef (EventM x) where
2833+ {-# INLINABLE atomicModifyRef #-}
12972834 atomicModifyRef r f = liftIO $ atomicModifyRef r f
12982835
1299−newtype SpiderHost a = SpiderHost { runSpiderHost :: IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO)
2836+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2837+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2838+
2839+instance Monad (SpiderHost x) where
2840+ {-# INLINABLE (>>=) #-}
2841+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2842+ {-# INLINABLE (>>) #-}
2843+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2844+ {-# INLINABLE return #-}
2845+ return x = SpiderHost $ return x
2846+#if !MIN_VERSION_base(4,13,0)
2847+ {-# INLINABLE fail #-}
2848+ fail = MonadFail.fail
2849+#endif
2850+
2851+instance MonadFail (SpiderHost x) where
2852+ {-# INLINABLE fail #-}
2853+ fail s = SpiderHost $ MonadFail.fail s
2854+
2855+-- | Run an action affecting the global Spider timeline; this will be guarded by
2856+-- a mutex for that timeline
2857+runSpiderHost :: SpiderHost Global a -> IO a
2858+runSpiderHost (SpiderHost a) = a
2859+
2860+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2861+-- mutex for that timeline
2862+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2863+runSpiderHostForTimeline (SpiderHost a) _ = a
2864+
2865+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2866+ deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2867+
2868+instance Monad (SpiderHostFrame x) where
2869+ {-# INLINABLE (>>=) #-}
2870+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2871+ {-# INLINABLE (>>) #-}
2872+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2873+ {-# INLINABLE return #-}
2874+ return x = SpiderHostFrame $ return x
2875+#if !MIN_VERSION_base(4,13,0)
2876+ {-# INLINABLE fail #-}
2877+ fail s = SpiderHostFrame $ fail s
2878+#endif
13002879
1301−newtype SpiderHostFrame a = SpiderHostFrame { runSpiderHostFrame :: EventM a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO)
2880+instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where
2881+ notReadyUntil _ = pure ()
2882+ notReady = pure ()
13022883
1303−instance R.MonadSample Spider SpiderHostFrame where
1304− sample = SpiderHostFrame . R.sample --TODO: This can cause problems with laziness, so we should get rid of it if we can
1305−
1306−instance R.MonadHold Spider SpiderHostFrame where
1307− {-# INLINE hold #-}
1308− hold v0 e = SpiderHostFrame $ R.hold v0 e
2884+newEventWithTriggerIO :: forall x a. HasSpiderTimeline x => (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2885+newEventWithTriggerIO f = do
2886+ es <- newFanEventWithTriggerIO $ \Refl -> f
2887+ return $ select es Refl
13092888
1310−newEventWithTriggerIO f= do
1311− occRef <- newIORef Nothing
1312− subscribedRef <- newIORef Nothing
2889+newFanEventWithTriggerIO :: (HasSpiderTimeline x, GCompare k) => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2890+newFanEventWithTriggerIO f = do
2891+ occRef <- newIORef DMap.empty
2892+ subscribedRef <- newIORef DMap.empty
13132893 let !r = Root
13142894 { rootOccurrence = occRef
13152895 , rootSubscribed = subscribedRef
13162896 , rootInit = f
13172897 }
1318− return $ SpiderEvent $ EventRoot r
2898+ return $ EventSelector $ \k -> eventRoot k r
13192899
1320−instance R.MonadReflexCreateTrigger Spider SpiderHost where
1321− newEventWithTrigger = SpiderHost . newEventWithTriggerIO
2900+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
13222901
1323−instance R.MonadReflexCreateTrigger Spider SpiderHostFrame where
1324− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . newEventWithTriggerIO
1325−
1326−instance R.MonadReflexHost Spider SpiderHost where
1327− fireEventsAndRead es a = SpiderHost $ run es a
1328− subscribeEvent e = SpiderHost $ do
1329− _ <- runFrame $ getEventSubscribed $ unSpiderEvent e --TODO: The result of this should actually be used
1330− return e
1331− runFrame = SpiderHost . runFrame
1332− runHostFrame = SpiderHost . runFrame . runSpiderHostFrame
1333−
1334−instance MonadRef SpiderHost where
1335− type Ref SpiderHost = Ref IO
2902+instance MonadRef (SpiderHost x) where
2903+ type Ref (SpiderHost x) = Ref IO
13362904 newRef = SpiderHost . newRef
13372905 readRef = SpiderHost . readRef
13382906 writeRef r = SpiderHost . writeRef r
2907+
2908+instance MonadAtomicRef (SpiderHost x) where
13392909 atomicModifyRef r = SpiderHost . atomicModifyRef r
13402910
1341−instance MonadRef SpiderHostFrame where
1342− type Ref SpiderHostFrame = Ref IO
2911+instance MonadRef (SpiderHostFrame x) where
2912+ type Ref (SpiderHostFrame x) = Ref IO
13432913 newRef = SpiderHostFrame . newRef
13442914 readRef = SpiderHostFrame . readRef
13452915 writeRef r = SpiderHostFrame . writeRef r
2916+
2917+instance MonadAtomicRef (SpiderHostFrame x) where
13462918 atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2919+
2920+instance PrimMonad (SpiderHostFrame x) where
2921+ type PrimState (SpiderHostFrame x) = PrimState IO
2922+ primitive = SpiderHostFrame . EventM . primitive
2923+
2924+instance NotReady (SpiderTimeline x) (SpiderHost x) where
2925+ notReadyUntil _ = return ()
2926+ notReady = return ()
2927+
2928+instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x)) where
2929+ notReadyUntil _ = return ()
2930+ notReady = return ()
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+150
@@ -0,0 +1,150 @@
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+ {-# INLINABLE now #-}
126+ now = lift now
127+
128+instance Adjustable t m => Adjustable t (TriggerEventT t m) where
129+ {-# INLINABLE runWithReplace #-}
130+ runWithReplace (TriggerEventT a0) a' = TriggerEventT $ runWithReplace a0 (coerceEvent a')
131+ {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
132+ traverseIntMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseIntMapWithKeyWithAdjust (coerce . f) dm0 dm'
133+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
134+ traverseDMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
135+ {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}
136+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
137+
138+-- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.
139+instance (Monoid a, Applicative m) => Monoid (TriggerEventT t m a) where
140+ mempty = pure mempty
141+ mappend = (<>)
142+
143+instance (S.Semigroup a, Applicative m) => S.Semigroup (TriggerEventT t m a) where
144+ (<>) = liftA2 (S.<>)
145+
146+
147+-- | Retrieve the current 'Chan'; event trigger invocations pushed into it will
148+-- be fired.
149+askEvents :: Monad m => TriggerEventT t m (Chan [DSum (EventTriggerRef t) TriggerInvocation])
150+askEvents = TriggerEventT ask
src/Reflex/TriggerEvent/Class.hsnew file+55
@@ -0,0 +1,55 @@
1+-- | This module defines 'TriggerEvent', which describes actions that may create
2+-- new 'Event's that can be triggered from 'IO'.
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE FunctionalDependencies #-}
5+{-# LANGUAGE UndecidableInstances #-}
6+module Reflex.TriggerEvent.Class
7+ ( TriggerEvent (..)
8+ ) where
9+
10+import Reflex.Class
11+
12+import Control.Monad.Reader
13+import Control.Monad.State
14+import qualified Control.Monad.State.Strict as Strict
15+import Control.Monad.Trans.Maybe (MaybeT)
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
51+
52+instance TriggerEvent t m => TriggerEvent t (MaybeT m) where
53+ newTriggerEvent = lift newTriggerEvent
54+ newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
55+ 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 Data.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 at post-build time and whenever the current 'Workflow' is replaced by the next 'Workflow'.
38+workflowView :: forall t m a. (Reflex t, NotReady t m, Adjustable t m, MonadFix m, MonadHold t m, PostBuild t m) => Workflow t m a -> m (Event t a)
39+workflowView w0 = do
40+ rec eResult <- networkView . fmap unWorkflow =<< holdDyn w0 eReplace
41+ eReplace <- fmap switch $ hold never $ fmap snd eResult
42+ return $ fmap fst eResult
43+
44+-- | Map a function over a 'Workflow', possibly changing the return type.
45+mapWorkflow :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
46+mapWorkflow f (Workflow x) = Workflow (fmap (f *** fmap (mapWorkflow f)) x)
47+
48+-- | Map a "cheap" function over a 'Workflow'. Refer to the documentation for 'pushCheap' for more information and performance considerations.
49+mapWorkflowCheap :: (Reflex t, Functor m) => (a -> b) -> Workflow t m a -> Workflow t m b
50+mapWorkflowCheap f (Workflow x) = Workflow (fmap (f *** fmapCheap (mapWorkflowCheap f)) x)
stylizenew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+
4+for x in **/*.hs ; do stylish-haskell -i "$x" ; done
test/Adjustable.hsnew file+62
@@ -0,0 +1,62 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE RankNTypes #-}
4+{-# LANGUAGE RecursiveDo #-}
5+
6+module Main where
7+
8+import Control.Monad.Fix
9+import Data.Maybe
10+import qualified Data.Map as Map
11+
12+import Reflex
13+import Reflex.EventWriter.Base
14+import Reflex.Network
15+import Reflex.Patch.MapWithMove
16+import Test.Run
17+
18+main :: IO ()
19+main = do
20+ let actions = [ Increment, Update0th, Increment, Swap, Increment, Increment ]
21+ os <- runAppB testPatchMapWithMove $ map Just actions
22+ -- If the final counter value in the adjusted widgets corresponds to the number of times it has
23+ -- been incremented, we know that the networks haven't broken.
24+ let expectedCount = length $ ffilter (== Increment) actions
25+ -- let !True = last (last os) == [expectedCount,expectedCount] -- TODO re-enable this test after issue #369 has been resolved
26+ return ()
27+
28+data PatchMapTestAction
29+ = Increment
30+ | Swap
31+ | Update0th
32+ deriving Eq
33+
34+-- See https://github.com/reflex-frp/reflex/issues/369 for the bug that this is testing.
35+testPatchMapWithMove
36+ :: forall t m
37+ . ( Reflex t
38+ , Adjustable t m
39+ , MonadHold t m
40+ , MonadFix m
41+ )
42+ => Event t PatchMapTestAction
43+ -> m (Behavior t [Int])
44+testPatchMapWithMove pulse = do
45+ let pulseAction = ffor pulse $ \case
46+ Increment -> Nothing
47+ Swap -> patchMapWithMove $ Map.fromList
48+ [ (0, NodeInfo (From_Move 1) (Just 1))
49+ , (1, NodeInfo (From_Move 0) (Just 0))
50+ ]
51+ Update0th -> patchMapWithMove $ Map.fromList
52+ [ (0, NodeInfo (From_Insert 'z') Nothing) ]
53+ (_, result) <- runBehaviorWriterT $ mdo
54+ counter <- foldDyn (+) 1 $ fmapMaybe (\e -> if isNothing e then Just 1 else Nothing) pulseAction
55+ _ <- mapMapWithAdjustWithMove
56+ (\_ _ -> networkHold
57+ (tellBehavior $ constant [])
58+ ((\t -> tellBehavior $ constant [t]) <$> updated counter))
59+ (Map.fromList $ zip [0..] "ab")
60+ (fmapMaybe id pulseAction)
61+ return ()
62+ return result
test/DebugCycles.hsnew file+171
@@ -0,0 +1,171 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE RecursiveDo #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE PatternSynonyms #-}
8+{-# LANGUAGE RankNTypes #-}
9+
10+module Main where
11+
12+import Data.Foldable
13+import Control.Lens
14+import Control.Applicative
15+import Control.Monad
16+import Control.Monad.Fix
17+import Control.Exception
18+import System.Timeout
19+import Data.Maybe (isJust)
20+import Data.Functor.Misc
21+import qualified Data.Map as Map
22+import Data.Map (Map)
23+import qualified Data.IntMap as IntMap
24+import Data.IntMap (IntMap)
25+import Data.These
26+import Data.Align
27+import Reflex
28+import Reflex.EventWriter.Base
29+import Test.Run
30+import Test.Hspec
31+import Reflex.Spider.Internal (EventLoopException)
32+import Data.Witherable (Filterable)
33+
34+#if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))
35+import Data.These.Lens
36+#endif
37+
38+type Widget t m = (MonadHold t m, Reflex t, MonadFix m)
39+
40+connectDyn :: Widget t m => Event t () -> (Dynamic t a, Dynamic t a) -> m (Dynamic t a)
41+connectDyn e (d, d') = do
42+ dd <- holdDyn d (d' <$ e)
43+ return $ join dd
44+
45+dynLoop :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
46+dynLoop (e1, e2) = do
47+ -- "heightBagRemove: Height 2 not present in bag HeightBag {_heightBag_size = 2, _heightBag_contents = fromList [(0,1)]}"
48+ rec
49+ d <- count e1
50+ d' <- connectDyn e2 (d, liftA2 (+) d d')
51+ return $ updated d'
52+
53+connectOnCoincidence :: Widget t m => Event t () -> Event t a -> m (Event t a)
54+connectOnCoincidence click e = do
55+ d <- holdDyn never (e <$ click)
56+ return $ coincidence (updated d)
57+
58+coincidenceLoop :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
59+coincidenceLoop (e1, e2) = do
60+-- "heightBagRemove: Height 1 not present in bag HeightBag {_heightBag_size = 1, _heightBag_contents = fromList [(0,0)]}"
61+-- (simpler version of dynLoop)
62+ rec
63+ e' <- connectOnCoincidence e2 (updated d)
64+ d <- count (align e' e1)
65+ return $ updated d
66+
67+addHeight :: Reflex t => Event t a -> Event t a
68+addHeight e = leftmost [e4, e4] where
69+ e1 = leftmost [e, e]
70+ e2 = leftmost [e1, e1]
71+ e3 = leftmost [e2, e2]
72+ e4 = leftmost [e3, e3]
73+
74+-- Take an existing test and build it inside a
75+buildLoop :: Widget t m => (forall t m. Widget t m => (Event t Int, Event t ()) -> m (Event t Int)) -> (Event t Int, Event t ()) -> m (Event t Int)
76+buildLoop test (e1, e2) = switchHold never buildLoop
77+ where buildLoop = pushAlways (const $ test (e1, e2)) e2
78+
79+connectButtonPromptly :: Widget t m => Event t () -> Event t a -> m (Event t a)
80+connectButtonPromptly click e = do
81+ d <- holdDyn never (e <$ click)
82+ return (switchDyn d)
83+
84+connectButton :: Widget t m => Event t () -> Event t a -> m (Event t a)
85+connectButton click e = do
86+ d <- hold never (e <$ click)
87+ return (switch d)
88+
89+switchLoop01 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
90+switchLoop01 (e1, e2) = do
91+ rec
92+ e' <- connectButton e2 (updated d)
93+ d <- count (align e' e1)
94+ return $ updated d
95+
96+mergeLoop :: forall t m. (Adjustable t m, Widget t m) => (Event t Int, Event t ()) -> m (Event t Int)
97+mergeLoop (e1, e2) = do
98+ rec
99+ (_, e) <- runEventWriterT $
100+ runWithReplace w (leftmost [w <$ e1])
101+ return (sum <$> e)
102+ where
103+ w = do
104+ c <- count e1
105+ tellEvent (updated ((pure <$> c) :: Dynamic t [Int]))
106+
107+switchLoop02 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
108+switchLoop02 (e1, e2) = do
109+ rec
110+ e' <- connectButton e2 (updated d)
111+ d <- count (leftmost [e', e1])
112+ return $ updated d
113+
114+switchLoop03 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
115+switchLoop03 (e1, e2) = do
116+ rec
117+ e' <- connectButton e2 (addHeight $ updated d)
118+ d <- count (align e' e1)
119+ return $ updated d
120+
121+staticLoop01 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
122+staticLoop01 (e1, e2) = do
123+ rec
124+ d <- foldDyn (+) (0 :: Int) (1 <$ align e1 (updated d))
125+ return $ updated d
126+
127+staticLoop02 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
128+staticLoop02 (e1, e2) = do
129+ rec
130+ d <- foldDyn (+) (0 :: Int) (leftmost [e1, updated d])
131+ return $ updated d
132+
133+buildStaticLoop :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int)
134+buildStaticLoop (e1, e2) = switchHold never buildLoop
135+ where buildLoop = pushAlways (const $ staticLoop01 (e1, e2)) e2
136+
137+splitThese :: Filterable f => f (These a b) -> (f a, f b)
138+splitThese f = (mapMaybe (preview here) f, mapMaybe (preview there) f)
139+
140+main :: IO ()
141+main = hspec $ do
142+ describe "DebugCycles" $ do
143+ it "throws EventLoopException on switchLoop01" $ do
144+ check switchLoop01
145+ it "throws EventLoopException on switchLoop02" $ do
146+ check switchLoop02
147+ it "throws EventLoopException on switchLoop03" $ do
148+ check switchLoop03
149+ it "throws EventLoopException on buildSwitchLoop" $ do
150+ check $ buildLoop switchLoop01
151+ xit "throws EventLoopException on mergeLoop" $ do
152+ check mergeLoop
153+ xit "throws EventLoopException on staticLoop01" $ do
154+ check staticLoop01
155+ xit "throws EventLoopException on staticLoop02" $ do
156+ check staticLoop02
157+ xit "throws EventLoopException on buildStaticLoop" $ do
158+ check buildStaticLoop
159+ xit "throws EventLoopException on coincidenceLoop" $ do
160+ check coincidenceLoop
161+ xit "throws EventLoopException on dynLoop" $ do
162+ check dynLoop
163+ xit "throws EventLoopException on buildCoincidenceLoop" $ do
164+ check $ buildLoop coincidenceLoop
165+ where
166+ milliseconds = (*1000)
167+ occs = [ This 1, This 2, That (), This 3, That (), This 1 ]
168+ check test = do
169+ let action = timeout (milliseconds 50) $ do
170+ runApp' (test . splitThese) (Just <$> occs)
171+ action `shouldThrow` (const True :: Selector EventLoopException)
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+import Data.Type.Equality ((:~:)(Refl))
22+
23+import Data.Functor.Misc
24+import Data.Patch
25+
26+import qualified Reflex.Host.Class as Host
27+import qualified Reflex.Spider.Internal as S
28+
29+import System.Exit
30+import System.Mem
31+import Data.Coerce
32+
33+main :: IO ()
34+main = do
35+ ref <- newIORef Nothing
36+ hostPerf ref
37+ readIORef ref >>= maybe exitFailure (putStrLn . ("Result " <>) . show)
38+
39+hostPerf :: IORef (Maybe Int) -> IO ()
40+hostPerf ref = S.runSpiderHost $ do
41+ ---- body
42+ liftIO $ putStrLn "#creating triggers"
43+ (response', responseTrigger) <- Host.newEventWithTriggerRef
44+ (eadd', addTriggerRef) <- Host.newEventWithTriggerRef
45+ let response = S.unSpiderEvent response'
46+ eadd = S.unSpiderEvent eadd'
47+ liftIO $ putStrLn "#creating event graph"
48+ eventToPerform <- Host.runHostFrame $ do
49+ (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity))
50+ <- S.SpiderHostFrame
51+ $ fmap ( S.mergeG coerce
52+ . S.dynamicHold)
53+ $ S.hold DMap.empty
54+ -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained
55+ $ (\e -> S.Event $ \sub -> do
56+ (s, o) <- S.subscribeAndRead e $ sub
57+ { S.subscriberPropagate = S.subscriberPropagate sub
58+ }
59+ return (s, o))
60+ $ runIdentity . runIdentity <$> S.selectG
61+ (S.fanG $ S.pushCheap (return . Just . mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e)) response)
62+ (WrapArg Request)
63+ return $ alignWith (mergeThese (<>))
64+ (flip S.pushCheap eadd $ \_ -> return $ Just $ DMap.singleton Request $ do
65+ liftIO $ putStrLn "#eadd fired"
66+ return $ PatchDMap $ DMap.singleton (Const2 (1 :: Int)) $ ComposeMaybe $ Just
67+ $ S.pushCheap (return . Just . DMap.singleton Action . (\_ -> liftIO (writeIORef ref (Just 1)))) $ eadd)
68+ (flip S.pushCheap reqMap $ \m -> return $ Just $ mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m)
69+ ---- epilogue
70+ eventToPerformHandle <- Host.subscribeEvent (S.SpiderEvent eventToPerform)
71+ liftIO $ putStrLn "#performing GC" >> performMajorGC
72+ liftIO $ putStrLn "#attempting to fire eadd"
73+ mAddTrigger <- readRef addTriggerRef
74+ forM_ mAddTrigger $ \t -> replicateM_ 2 $ do
75+ liftIO $ putStrLn "#firing eadd"
76+ mToPerform <- Host.fireEventsAndRead [t :=> Identity ()] $ sequence =<< Host.readEvent eventToPerformHandle
77+ case mToPerform of
78+ Nothing -> return ()
79+ Just toPerform -> do
80+ responses <- Host.runHostFrame $ DMap.traverseWithKey (\_ v -> Identity <$> v) toPerform
81+ mrt <- readRef responseTrigger
82+ let followupEventTriggers = case mrt of
83+ Just rt -> [rt :=> Identity responses]
84+ Nothing -> []
85+ Host.fireEventsAndRead followupEventTriggers $ 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/Headless.hsnew file+10
@@ -0,0 +1,10 @@
1+module Main where
2+
3+import Reflex
4+import Reflex.Host.Headless (runHeadlessApp)
5+
6+main :: IO ()
7+main = do
8+ runHeadlessApp $ do
9+ pb <- getPostBuild
10+ performEvent (pure <$> pb)
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 Data.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+381
@@ -0,0 +1,381 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE RankNTypes #-}
7+{-# LANGUAGE RecursiveDo #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE TupleSections #-}
10+{-# LANGUAGE TypeSynonymInstances #-}
11+
12+module Reflex.Bench.Focused where
13+
14+import Reflex
15+import Reflex.TestPlan
16+
17+import Control.Applicative
18+import Control.Monad
19+import Control.Monad.Fix
20+import Control.Monad.Identity
21+import Data.Traversable (for, traverse)
22+
23+import qualified Data.Dependent.Map as DMap
24+import Data.Map (Map)
25+import qualified Data.Map as Map
26+import Data.Maybe
27+
28+import Data.Functor.Misc
29+
30+import Data.List
31+import Data.List.Split
32+import Data.Tuple
33+
34+import Data.Monoid
35+import Data.Word
36+
37+import Control.DeepSeq
38+
39+import Prelude hiding (concat, sum)
40+
41+
42+mergeTree :: Num a => (Monoid (f [a]), Functor f) => Int -> [f a] -> f a
43+mergeTree n es | length es <= n = sum' es
44+ | otherwise = mergeTree n subTrees
45+ where
46+ merges = chunksOf n es
47+ subTrees = map sum' merges
48+ sum' = fmap sum . mconcat . fmap (fmap (:[]) )
49+
50+mergeListDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a]
51+mergeListDyn = mconcat . fmap (fmap pure)
52+
53+mergeTreeDyn :: (Num a, Reflex t) => Int -> [Dynamic t a] -> Dynamic t a
54+mergeTreeDyn n dyns | length dyns <= n = sumDyns dyns
55+ | otherwise = mergeTreeDyn n $ fmap sumDyns merges
56+ where
57+ merges = chunksOf n dyns
58+ sumDyns = fmap sum . mergeListDyn
59+
60+
61+
62+-- N events all firing for N frames
63+continuous :: TestPlan t m => Word -> Word -> m [Event t Word]
64+continuous n frames = for [1..n] $ \i -> plan $ (, i) <$> [1..frames]
65+
66+-- Fire N events once every P frames for total N frames (interspersed evenly)
67+occasional :: TestPlan t m => Word -> Word -> Word -> m [Event t Word]
68+occasional n period frames = traverse plan $ zipWith occs [1..] phases
69+ where
70+ phases = take (fromIntegral n) $ concat (repeat [1..period])
71+ occs i phase = (, i) <$> [1, phase+1..frames]
72+
73+
74+
75+-- Event which never fires (but isn't 'never')
76+never' :: TestPlan t m => m (Event t Word)
77+never' = plan []
78+
79+
80+-- Event which fires once on first frame
81+event :: TestPlan t m => m (Event t Word)
82+event = plan [(1, 0)]
83+
84+-- Event which fires constantly over N frames
85+events :: TestPlan t m => Word -> m (Event t Word)
86+events n = plan $ (\i -> (i, i)) <$> [1..n]
87+
88+
89+-- N events all originating from one event
90+fmapFan :: Reflex t => Word -> Event t Word -> [Event t Word]
91+fmapFan n e = (\i -> (+i) <$> e) <$> [1..n]
92+
93+
94+-- Make a fan using the value in the event converting it to a singleton Map
95+-- use a fan of size n (key is the value mod n)
96+fanMerge :: Reflex t => Word -> Event t Word -> Event t Word
97+fanMerge n e = leftmost $ s <$> [0..n - 1] where
98+ s k = select f (Const2 k)
99+ f = fan (toMap <$> e)
100+ toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k)
101+
102+-- Dumb version of the above using simple fmapMaybe to filter
103+fmapFanMerge :: Reflex t => Word -> Event t Word -> Event t Word
104+fmapFanMerge n e = leftmost $ s <$> [0..n - 1] where
105+ s k = flip fmapMaybe e $ \j -> if k == j `mod` n
106+ then Just k
107+ else Nothing
108+
109+
110+
111+-- Create an Event with a Map which is dense to size N
112+denseMap :: TestPlan t m => Word -> m (Event t (Map Word Word))
113+denseMap n = plan [(1, m)] where
114+ m = Map.fromList $ zip [1..n] [1..n]
115+
116+iter :: (a -> a) -> Word -> a -> a
117+iter _ 0 a = a
118+iter f n a = iter f (n - 1) (f a)
119+
120+iterM :: Monad m => (a -> m a) -> Word -> a -> m a
121+iterM _ 0 a = return a
122+iterM f n a = iterM f (n - 1) =<< f a
123+
124+fmapChain :: (Functor f) => Word -> f Word -> f Word
125+fmapChain = iter (fmap (+1))
126+
127+mapDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
128+mapDynChain = iterM (return . fmap (+1))
129+
130+joinDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
131+joinDynChain = iterM (\d -> return $ join $ fmap (const d) d)
132+
133+holdDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
134+holdDynChain = iterM (\d -> sample (current d) >>= flip holdDyn (updated d))
135+
136+buildDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
137+buildDynChain = iterM (\d -> do
138+ let b = fmap (+1) (current d)
139+ e = fmap (*2) (updated d)
140+ buildDynamic (sample b) e)
141+
142+
143+combineDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)
144+combineDynChain = iterM (\d -> return $ zipDynWith (+) d d)
145+
146+pingPong :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> Event t a -> m (Event t a)
147+pingPong e1 e2 = do
148+ rec
149+ d <- foldDyn (const swap) (e1, e2) e
150+ let e = switch (fst <$> current d)
151+ return e
152+
153+switchFactors :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
154+switchFactors 0 e = return e
155+switchFactors i e = do
156+ b <- hold ((+1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)
157+ switchFactors (i - 1) (switch b)
158+
159+
160+switchChain :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
161+switchChain = iterM (\e -> pingPong e ((+1) <$> e))
162+
163+
164+switchChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)
165+switchChain2 = iterM (\e -> pingPong e ((+1) <$> leftmost [e, e]))
166+
167+switchPromptlyChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)
168+switchPromptlyChain = iterM $ \e ->
169+ switchPromptlyDyn <$> holdDyn e (e <$ e)
170+
171+
172+coinChain :: Reflex t => Word -> Event t Word -> Event t Word
173+coinChain = iter $ \e -> coincidence (e <$ e)
174+
175+fanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
176+fanMergeChain width = iter $ fanMerge width
177+
178+fmapFanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word
179+fmapFanMergeChain width = iter $ fmapFanMerge width
180+
181+-- | Data type for a collection (a map) which is updated by providing differences
182+data UpdatedMap t k a = UpdatedMap (Map k a) (Event t (Map k (Maybe a)))
183+
184+-- This will hopefully become a primitive (faster!)
185+switchMergeEvents :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
186+switchMergeEvents mapChanges = switch . fmap mergeMap <$> holdMap mapChanges
187+
188+-- switchMergeMaybe :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))
189+-- switchMergeMaybe (UpdatedMap initial changes) = switchMergeMap initial (fmap (fromMaybe never) <$> changes)
190+
191+switchMergeBehaviors :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Behavior t a) -> m (Behavior t (Map k a))
192+switchMergeBehaviors mapChanges = pull . joinMap <$> holdMap mapChanges
193+ where joinMap m = traverse sample =<< sample m
194+
195+-- | Turn an UpdatedMap into a Dynamic by applying the differences to the initial value
196+holdMapDyn :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Dynamic t (Map k a))
197+holdMapDyn (UpdatedMap initial changes) = foldDyn (flip (Map.foldrWithKey modify)) initial changes
198+
199+ where
200+ modify k Nothing items = Map.delete k items
201+ modify k (Just item) items = Map.insert k item items
202+
203+
204+-- | Hold an UpdatedMap as a behavior by applying differences to the initial value
205+holdMap :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Behavior t (Map k a))
206+holdMap = (current <$>) . holdMapDyn
207+
208+
209+increasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a)
210+increasingMerge xs = do
211+ e <- planList (zipWith Map.singleton [1..] (Just <$> xs) ++ [reset])
212+ return (UpdatedMap Map.empty e)
213+ where
214+ reset = Map.fromList $ zip [1..] (const Nothing <$> xs)
215+
216+decreasingMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
217+decreasingMerge xs = do
218+ e <- planList (zipWith Map.singleton [1..] (const Nothing <$> xs) ++ [reset])
219+ return (UpdatedMap initial e)
220+ where
221+ initial = Map.fromList $ zip [1..] xs
222+ reset = Just <$> initial
223+
224+modifyMerge :: (TestPlan t m) => [a] -> m (UpdatedMap t Int a)
225+modifyMerge xs = do
226+ e <- planList $ zipWith Map.singleton [1..] (Just <$> xs)
227+ return (UpdatedMap initial e)
228+ where
229+ initial = Map.fromList $ zip [1..] xs
230+
231+
232+countMany :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Behavior t Int]
233+countMany = traverse (fmap current . count)
234+
235+countManyDyn :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Dynamic t Int]
236+countManyDyn = traverse count
237+
238+
239+-- Given a function which creates a sub-network (from a single event)
240+-- Create a plan which uses a switch to substitute it
241+switches :: TestPlan t m => Word -> (forall n. (MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> m (Event t a)
242+switches numFrames f = do
243+ es <- events numFrames
244+ switch <$> hold never (makeEvents es)
245+
246+ where
247+ makeEvents es = pushAlways (\n -> f (fmap (+n) es)) es
248+
249+
250+
251+-- Two sets of benchmarks, one which we're interested in testing subscribe time (as well as time to fire frames)
252+-- the other, which we're only interested in time for running frames
253+subscribing :: Word -> Word -> [(String, TestCase)]
254+subscribing n frames =
255+ [ testSub "fmapFanMerge" $ return . mergeList . fmapFan n
256+ , testSub "fanMerge" $ return . fanMerge n
257+ , testSub "fmapFan/mergeTree" $ return . mergeTree 8 . fmapFan n
258+ , testSub "fmapChain" $ return . fmapChain n
259+ , testSub "switchChain" $ switchChain n
260+ , testSub "switchPromptlyChain" $ switchPromptlyChain n
261+ , testSub "switchFactors" $ switchFactors n
262+ , testSub "coincidenceChain" $ return . coinChain n
263+ ]
264+
265+ where
266+ testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)
267+ testSub name test = testE name (switches frames test)
268+
269+-- Set of benchmark to test specifically merging dynamic collections
270+-- a pattern which occurs frequently in reflex-dom collections
271+merging :: Word -> [(String, TestCase)]
272+merging n =
273+ [ testE "static events" $ mergeList <$> sparse
274+ , testE "increasing events" $ switchMergeEvents =<< increasingMerge =<< sparse
275+ , testE "decreasing events" $ switchMergeEvents =<< decreasingMerge =<< sparse
276+ , testE "modify events" $ switchMergeEvents =<< modifyMerge =<< sparse
277+
278+ , testB "static behaviors" $ pull . traverse sample <$> counters
279+ , testB "increasing behaviors" $ switchMergeBehaviors =<< increasingMerge =<< counters
280+ , testB "decreasing behaviors" $ switchMergeBehaviors =<< decreasingMerge =<< counters
281+ , testB "modify behaviors" $ switchMergeBehaviors =<< modifyMerge =<< counters
282+
283+
284+ -- , testE "increasing events/switchMerge" $ switchMergeMaybe =<< increasingMerge =<< sparse
285+ -- , testE "decreasing events/switchMerge" $ switchMergeMaybe =<< decreasingMerge =<< sparse
286+ -- , testE "modify events/switchMerge" $ switchMergeMaybe =<< modifyMerge =<< sparse
287+ ]
288+
289+ where
290+ sparse :: TestPlan t m => m [Event t Word]
291+ sparse = fmap (fmap (+1)) <$> occasional n 8 n
292+
293+ counters :: TestPlan t m => m [Behavior t Int]
294+ counters = countMany =<< sparse
295+
296+
297+
298+fans :: Word -> [(String, TestCase)]
299+fans n =
300+ [ testE "fanMapChain" $ fanMergeChain n 10 <$> e
301+ , testE "fmapFanMapChain" $ fmapFanMergeChain n 10 <$> e
302+
303+ , testE "fanMerge " $ fanMerge n <$> events n
304+
305+ , testE "fmapFanMerge " $ fmapFanMerge n <$> events n
306+ , testE "triggerMerge" $ leftmost <$> for [1..n] (\i -> plan [(i, i)])
307+
308+ ]
309+ where
310+
311+ e :: TestPlan t m => m (Event t Word)
312+ e = events 100
313+
314+
315+
316+
317+dynamics :: Word -> [(String, TestCase)]
318+dynamics n =
319+ [ testE "mapDynChain" $ fmap updated $ mapDynChain n =<< d
320+ , testE "joinDynChain" $ fmap updated $ joinDynChain n =<< d
321+ , testE "holdDynChain" $ fmap updated $ holdDynChain n =<< d
322+ , testE "buildDynChain" $ fmap updated $ buildDynChain n =<< d
323+ , testE "combineDynChain" $ fmap updated $ combineDynChain n =<< d
324+ , testE "dense mergeTree" $ fmap (updated . mergeTreeDyn 8) dense
325+ , testE "sparse mergeTree" $ fmap (updated . mergeTreeDyn 8) sparse
326+ , testE "mergeDyn" $ fmap (updated . fmap sum . mergeListDyn) sparse
327+ ] where
328+
329+ d :: TestPlan t m => m (Dynamic t Word)
330+ d = count =<< events 10
331+
332+ sparse, dense :: TestPlan t m => m [Dynamic t Int]
333+ sparse = countManyDyn =<< occasional n 8 16
334+ dense = countManyDyn =<< continuous n 2
335+
336+
337+firing :: Word -> [(String, TestCase)]
338+firing n =
339+ [ testE "fmapChain" $ fmapChain n <$> e
340+ , testE "switchChain2" $ switchChain2 n =<< e
341+ , testE "switchPromptlyChain" $ switchPromptlyChain n =<< e
342+ , testE "switchFactors" $ switchFactors n =<< e
343+ , testE "coincidenceChain" $ coinChain n <$> e
344+
345+ , testE "dense mergeTree" $ mergeTree 8 <$> dense
346+ , testE "sparse mergeTree" $ mergeTree 8 <$> sparse
347+
348+ -- Triggers test failure in Spider
349+ --, testE "runFrame" $ events n
350+
351+ , testB "sum counters" $ do
352+ counts <- counters
353+ return $ pull $ sum <$> traverse sample counts
354+
355+ , testB "pullChain" $ fmapChain n . current <$> (count =<< events 4)
356+ , testB "pullChain2" $ do
357+ es <- events 4
358+ e' <- plan [(0, ())]
359+
360+ b <- hold (constant 0) $
361+ pushAlways (const $ fmapChain n <$> hold 0 es) e'
362+
363+ return (join b)
364+ , testB "counters/pullTree" $ mergeTree 8 <$> counters
365+
366+ ]
367+ where
368+ e :: TestPlan t m => m (Event t Word)
369+ e = events 10
370+
371+ dense, sparse :: TestPlan t m => m [Event t Word]
372+ dense = continuous n 2
373+ sparse = occasional n 8 16
374+
375+ counters :: TestPlan t m => m [Behavior t Int]
376+ counters = countMany =<< sparse
377+
378+
379+
380+
381+
test/Reflex/Plan/Pure.hsnew file+73
@@ -0,0 +1,73 @@
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+ now = liftPlan now
45+
46+instance MonadSample (Pure Int) PurePlan where
47+ sample = liftPlan . sample
48+
49+
50+instance TestPlan (Pure Int) PurePlan where
51+ plan occs = do
52+ PurePlan . modify $ IntSet.union (IntMap.keysSet m)
53+ return $ mapToPureEvent m
54+ where m = IntMap.fromList (first fromIntegral <$> occs)
55+
56+runPure :: PurePlan a -> (a, IntSet)
57+runPure (PurePlan p) = runStateT p mempty $ 0
58+
59+relevantTimes :: IntSet -> IntSet
60+relevantTimes occs = IntSet.fromList [0..l + 1]
61+ where l = fromMaybe 0 (fst <$> IntSet.maxView occs)
62+
63+testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a
64+testBehavior (b, occs) = IntMap.fromSet (sample b) (relevantTimes occs)
65+
66+testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a)
67+testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relevantTimes occs)
68+
69+
70+
71+
72+
73+
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+267
@@ -0,0 +1,267 @@
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+import qualified Reflex.Profiled as Prof
25+
26+import Control.Arrow (second, (&&&))
27+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
28+import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
29+import Data.Dependent.Sum (DSum (..))
30+import Data.Foldable
31+import Data.Map.Strict (Map)
32+import qualified Data.Map.Strict as Map
33+import qualified Data.Set as Set
34+import Data.Monoid
35+import Data.Traversable
36+import System.Exit
37+import System.Mem
38+
39+mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a
40+mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of
41+ Nothing -> error $ "mapToPureBehavior: no value for time " <> show t
42+ Just (_, v) -> v
43+
44+mapToPureEvent :: Map Int a -> Event PureReflexDomain a
45+mapToPureEvent m = P.Event $ flip Map.lookup m
46+
47+relevantTestingTimes :: (Map Int a, Map Int b) -> [Int]
48+relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of
49+ (Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event
50+ _ -> [] -- Doesn't actually make much sense
51+
52+type PureReflexDomain = P.Pure Int
53+type TimeM = (->) Int
54+
55+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)
56+testPure builder (b, e) =
57+ let (P.Behavior b', P.Event e') = ($ 0) $ builder (mapToPureBehavior b, mapToPureEvent e)
58+ relevantTimes = relevantTestingTimes (b, e)
59+ e'' = Map.mapMaybe id $ Map.fromList $ map (id &&& e') relevantTimes
60+ b'' = Map.fromList $ map (id &&& b') relevantTimes
61+ in (b'', e'')
62+
63+class MapMSignals a a' t t' | a -> t, a' -> t', a t' -> a', a' t -> a where
64+ mapMSignals :: Monad m => (forall b. Behavior t b -> m (Behavior t' b)) -> (forall b. Event t b -> m (Event t' b)) -> a -> m a'
65+
66+instance MapMSignals (Behavior t a) (Behavior t' a) t t' where
67+ mapMSignals fb _ = fb
68+
69+instance MapMSignals (Event t a) (Event t' a) t t' where
70+ mapMSignals _ fe = fe
71+
72+instance (MapMSignals a a' t t', MapMSignals b b' t t') => MapMSignals (a, b) (a', b') t t' where
73+ mapMSignals fb fe (a, b) = liftM2 (,) (mapMSignals fb fe a) (mapMSignals fb fe b)
74+
75+testTimeline
76+ :: (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d))
77+ -> (Map Int a, Map Int b)
78+ -> (forall m t. (MonadReflexHost t m, MonadIO m, MonadRef m, Ref m ~ Ref IO, MonadSample t m) => m (Map Int c, Map Int d))
79+testTimeline builder (bMap, eMap) = do
80+ (re, reTrigger) <- newEventWithTriggerRef
81+ (rb, rbTrigger) <- newEventWithTriggerRef
82+ b <- runHostFrame $ hold (error "testTimeline: No value for input behavior yet") rb
83+ (b', e') <- runHostFrame $ builder (b, re)
84+ e'Handle <- subscribeEvent e' --TODO: This should be unnecessary
85+ let times = relevantTestingTimes (bMap, eMap)
86+ liftIO performGC
87+ outputs <- forM times $ \t -> do
88+ forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger
89+ bOutput <- sample b'
90+ eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do
91+ mret <- readRef reTrigger
92+ let firing = case mret of
93+ Just ret -> [ret :=> Identity val]
94+ Nothing -> []
95+ fireEventsAndRead firing $ sequence =<< readEvent e'Handle
96+ liftIO performGC
97+ return (t, (bOutput, eOutput))
98+ return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)
99+
100+tracePerf :: Show a => a -> b -> b
101+tracePerf = flip const
102+
103+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
104+testAgreement builder inputs = do
105+ let identityResult = testPure builder inputs
106+ tracePerf "---------" $ return ()
107+ spiderResult <- S.runSpiderHost $ testTimeline builder inputs
108+ tracePerf "---------" $ return ()
109+ profiledResult <- S.runSpiderHost $ Prof.runProfiledM $ testTimeline builder inputs
110+ tracePerf "---------" $ return ()
111+ let resultsAgree = identityResult == spiderResult && identityResult == profiledResult
112+ if resultsAgree
113+ then do --putStrLn "Success:"
114+ --print identityResult
115+ return ()
116+ else do putStrLn "Failure:"
117+ putStrLn $ "Pure result: " <> show identityResult
118+ putStrLn $ "Spider result: " <> show spiderResult
119+ putStrLn $ "Profiled result: " <> show profiledResult
120+ return resultsAgree
121+
122+type TestCaseConstraint t m = (Reflex t, MonadSample t m, MonadHold t m, MonadFix m, MonadFix (PushM t))
123+
124+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))
125+
126+testCases :: [(String, TestCase)]
127+testCases =
128+ [ (,) "hold" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
129+ b' <- hold "123" e
130+ return (b', e)
131+ , (,) "count" $ TestCase (Map.singleton 0 (), Map.fromList [(1, ()), (2, ()), (3, ())]) $ \(_, e) -> do
132+ e' <- updated <$> count e
133+ b' <- hold (0 :: Int) e'
134+ return (b', e')
135+ , (,) "headE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
136+ e' <- headE $ leftmost [e, e]
137+ return (b, e')
138+ , (,) "switch-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
139+ let e' = fmap (const e) e
140+ b' <- hold never e'
141+ let e'' = switch b'
142+ return (b, e'')
143+ , (,) "switch-2" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
144+ let e' = flip pushAlways e $ const $ do
145+ let eab = splitRecombineEvent e
146+ switch <$> hold eab never
147+ e'' = coincidence e'
148+ return (b, e'')
149+ , (,) "switch-3" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
150+ let e' = flip pushAlways e $ const $ do
151+ let eab = splitRecombineEvent e
152+ switch <$> hold eab (fmap (const e) e)
153+ e'' = coincidence e'
154+ return (b, e'')
155+ , (,) "switch-4" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
156+ let e' = leftmost [e, e]
157+ e'' <- switch <$> hold e' (fmap (const e) e)
158+ return (b, e'')
159+ , (,) "switchHoldPromptly-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
160+ let e' = fmap (const e) e
161+ e'' <- switchHoldPromptly never e'
162+ return (b, e'')
163+ , (,) "switchHoldPromptly-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
164+ let e' = fmap (const e) e
165+ e'' <- switchHoldPromptly never $ leftmost [e', e']
166+ return (b, e'')
167+ , (,) "switchHoldPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
168+ let e' = leftmost [e, e]
169+ e'' <- switchHoldPromptly never (fmap (const e) e')
170+ return (b, e'')
171+ , (,) "switchHoldPromptly-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
172+ let e' = leftmost [e, e]
173+ e'' <- switchHoldPromptly never (fmap (const e') e)
174+ return (b, e'')
175+ , (,) "switch-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
176+ let e' = leftmost [e, e]
177+ e'' <- switch <$> hold never (fmap (const e') e)
178+ return (b, e'')
179+ , (,) "switchHoldPromptly-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
180+ let e' = flip push e $ \_ -> do
181+ Just <$> headE e
182+ e'' <- switchHoldPromptly never e'
183+ return (b, e'')
184+ , (,) "switchHoldPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
185+ let e' = flip pushAlways e $ \_ -> do
186+ switchHoldPromptly e never
187+ e'' <- switchHoldPromptly never e'
188+ return (b, e'')
189+ , (,) "coincidence-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
190+ let e' = flip pushAlways e $ \_ -> return e
191+ e'' = coincidence e'
192+ return (b, e'')
193+ , (,) "coincidence-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
194+ let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]
195+ e'' = coincidence e'
196+ return (b, e'')
197+ , (,) "coincidence-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
198+ let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e
199+ e'' = coincidence e'
200+ return (b, e'')
201+ , (,) "coincidence-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
202+ let e' = flip pushAlways e $ \_ -> headE e
203+ e'' = coincidence e'
204+ return (b, e'')
205+ , (,) "coincidence-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
206+ let eChild = flip pushAlways e $ const $ do
207+ let eNewValues = leftmost [e, e]
208+ return $ coincidence $ fmap (const eNewValues) eNewValues
209+ e' = coincidence eChild
210+ return (b, e')
211+ , (,) "coincidence-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
212+ let eChild = flip pushAlways e $ const $ do
213+ let e' = coincidence $ fmap (const e) e
214+ return $ leftmost [e', e']
215+ e'' = coincidence eChild
216+ return (b, e'')
217+ , (,) "coincidence-7" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
218+ let e' = leftmost [e, e]
219+ eCoincidences = coincidence $ fmap (const e') e
220+ return (b, eCoincidences)
221+ , (,) "holdWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
222+ eo <- headE e
223+ bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo
224+ let b' = pull $ sample =<< sample bb
225+ return (b', e)
226+ , (,) "foldDynWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
227+ d <- foldDyn (:) [] $
228+ pushAlways (\a -> foldDyn (:) [a] e) e
229+ let b = current (join (fmap distributeListOverDynPure d))
230+ return (b, e)
231+ , (,) "joinDyn" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
232+ bb <- hold "b" e
233+ bd <- hold never . fmap (const e) =<< headE e
234+ eOuter <- pushAlways sample . fmap (const bb) <$> headE e
235+ let eInner = switch bd
236+ e' = leftmost [eOuter, eInner]
237+ return (b, e')
238+ , (,) "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
239+ rec result <- holdUniqDyn d
240+ d <- holdDyn (0 :: Int) e
241+ return (current result, updated result)
242+
243+
244+
245+ {-
246+ , (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do
247+ x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e
248+ let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)
249+ return (b, e')
250+ -}
251+ ]
252+
253+splitRecombineEvent :: Reflex t => Event t a -> Event t String
254+splitRecombineEvent e =
255+ let ea = "a" <$ e
256+ eb = "b" <$ e
257+ in leftmost [ea, eb]
258+
259+
260+main :: IO ()
261+main = do
262+ results <- forM testCases $ \(name, TestCase inputs builder) -> do
263+ putStrLn $ "Test: " <> name
264+ testAgreement builder inputs
265+ exitWith $ if and results
266+ then ExitSuccess
267+ else ExitFailure 1
test/Reflex/Test/Micro.hsnew file+352
@@ -0,0 +1,352 @@
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+ , testE "now-1" $ do
326+ e1 <- events1
327+ switchHoldPromptly never . pushAlways (\a -> fmap (a <$) now) $ e1
328+ , testE "now-2" $ do
329+ e1 <- events1
330+ let e = pushAlways (\a -> if a == "a" then now else return never) e1
331+ x <- accumDyn (<>) never e
332+ return . coincidence $ updated x
333+ ] where
334+
335+ events1, events2, events3 :: TestPlan t m => m (Event t String)
336+ events1 = plan [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")]
337+ events2 = plan [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")]
338+ events3 = liftA2 mappend events1 events2
339+
340+ eithers :: TestPlan t m => m (Event t (Either String String))
341+ eithers = plan [(1, Left "e"), (3, Left "d"), (4, Right "c"), (6, Right "b"), (7, Left "a")]
342+
343+
344+ values = "abcde"
345+ toMap str = Map.fromList $ map (\c -> (c, c)) str
346+
347+ behavior1, behavior2 :: forall t m. TestPlan t m => m (Behavior t String)
348+ behavior1 = hold "1" =<< events1
349+ behavior2 = hold "2" =<< events2
350+
351+ deep e = leftmost [e, e]
352+ 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+235
@@ -0,0 +1,235 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE BangPatterns #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE LambdaCase #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE RecursiveDo #-}
9+{-# LANGUAGE ScopedTypeVariables #-}
10+{-# LANGUAGE TemplateHaskell #-}
11+{-# LANGUAGE TypeApplications #-}
12+{-# LANGUAGE TypeFamilies #-}
13+module Main where
14+
15+import Control.Lens hiding (has)
16+import Control.Monad
17+import Control.Monad.Fix
18+import Control.Monad.IO.Class (MonadIO)
19+import Data.Constraint.Extras
20+import Data.Constraint.Extras.TH
21+import Data.Constraint.Forall
22+import qualified Data.Dependent.Map as DMap
23+import Data.Dependent.Sum
24+import Data.Functor.Misc
25+import Data.List (words)
26+import Data.Map (Map)
27+import qualified Data.Map as M
28+#if !MIN_VERSION_these(4,11,0)
29+import Data.Semigroup ((<>))
30+#endif
31+import Data.Text (Text)
32+import Data.These
33+import Text.Read (readMaybe)
34+
35+#if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))
36+import Data.These.Lens
37+#endif
38+
39+import Reflex
40+import Reflex.Requester.Base
41+import Reflex.Requester.Class
42+import Test.Run
43+
44+data RequestInt a where
45+ RequestInt :: Int -> RequestInt Int
46+
47+main :: IO ()
48+main = do
49+ os1 <- runApp' (unwrapApp testOrdering) $
50+ [ Just ()
51+ ]
52+ print os1
53+ os2 <- runApp' (unwrapApp testSimultaneous) $ map Just $
54+ [ This ()
55+ , That ()
56+ , This ()
57+ , These () ()
58+ ]
59+ print os2
60+ os3 <- runApp' (unwrapApp testMoribundRequest) [Just ()]
61+ print os3
62+ os4 <- runApp' (unwrapApp testMoribundRequestDMap) [Just ()]
63+ print os4
64+ os5 <- runApp' (unwrapApp testLiveRequestDMap) [Just ()]
65+ print os5
66+ os6 <- runApp' (unwrapApp delayedPulse) [Just ()]
67+ print os6
68+ os7 <- runApp' testMatchRequestsWithResponses [ Just $ TestRequest_Increment 1 ]
69+ print os7
70+ os8 <- runApp' testMatchRequestsWithResponses [ Just $ TestRequest_Reverse "yoyo" ]
71+ print os8
72+ let ![[Just [1,2,3,4,5,6,7,8,9,10]]] = os1 -- The order is reversed here: see the documentation for 'runRequesterT'
73+ let ![[Just [9,7,5,3,1]],[Nothing,Nothing],[Just [10,8,6,4,2]],[Just [10,8,6,4,2],Nothing]] = os2
74+ let ![[Nothing, Just [2]]] = os3
75+ let ![[Nothing, Just [2]]] = os4
76+ let ![[Nothing, Just [1, 2]]] = os5
77+ -- let ![[Nothing, Nothing]] = os6 -- TODO re-enable this test after issue #233 has been resolved
78+ let !(Just [(1,"2")]) = M.toList <$> head (head os7)
79+ let !(Just [(1,"oyoy")]) = M.toList <$> head (head os8)
80+
81+ return ()
82+
83+unwrapRequest :: DSum tag RequestInt -> Int
84+unwrapRequest (_ :=> RequestInt i) = i
85+
86+unwrapApp :: ( Reflex t, Monad m )
87+ => (a -> RequesterT t RequestInt Identity m ())
88+ -> a
89+ -> m (Event t [Int])
90+unwrapApp x appIn = do
91+ ((), e) <- runRequesterT (x appIn) never
92+ return $ fmap (map unwrapRequest . requesterDataToList) e
93+
94+testOrdering :: ( Response m ~ Identity
95+ , Request m ~ RequestInt
96+ , Requester t m
97+ , Adjustable t m)
98+ => Event t ()
99+ -> m ()
100+testOrdering pulse = forM_ [10,9..1] $ \i ->
101+ requestingIdentity (RequestInt i <$ pulse)
102+
103+testSimultaneous :: ( Response m ~ Identity
104+ , Request m ~ RequestInt
105+ , Requester t m
106+ , Adjustable t m)
107+ => Event t (These () ())
108+ -> m ()
109+testSimultaneous pulse = do
110+ let tellE = fmapMaybe (^? here) pulse
111+ switchE = fmapMaybe (^? there) pulse
112+ forM_ [1,3..9] $ \i -> runWithReplace (requestingIdentity (RequestInt i <$ tellE)) $ ffor switchE $ \_ ->
113+ requestingIdentity (RequestInt (i+1) <$ tellE)
114+
115+-- | Test that a widget requesting and event which fires at the same time it has been replaced
116+-- doesn't count along with the new widget.
117+testMoribundRequest
118+ :: forall t m
119+ . ( Reflex t
120+ , Adjustable t m
121+ , MonadHold t m
122+ , MonadFix m
123+ , Response m ~ Identity
124+ , Request m ~ RequestInt
125+ , Requester t m
126+ )
127+ => Event t ()
128+ -> m ()
129+testMoribundRequest pulse = do
130+ rec let requestIntOnReplace x = requestingIdentity $ RequestInt x <$ rwrFinished
131+ (_, rwrFinished) <- runWithReplace (requestIntOnReplace 1) $ requestIntOnReplace 2 <$ pulse
132+ return ()
133+
134+-- | The equivalent of 'testMoribundRequest' for 'traverseDMapWithKeyWithAdjust'.
135+testMoribundRequestDMap
136+ :: forall t m
137+ . ( Reflex t
138+ , Adjustable t m
139+ , MonadHold t m
140+ , MonadFix m
141+ , Response m ~ Identity
142+ , Request m ~ RequestInt
143+ , Requester t m
144+ )
145+ => Event t ()
146+ -> m ()
147+testMoribundRequestDMap pulse = do
148+ rec let requestIntOnReplace :: Int -> m ()
149+ requestIntOnReplace x = void $ requestingIdentity $ RequestInt x <$ rwrFinished
150+ (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-
151+ traverseDMapWithKeyWithAdjust
152+ (\(Const2 ()) (Identity v) -> Identity . const v <$> requestIntOnReplace v)
153+ (mapToDMap $ M.singleton () 1)
154+ ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)
155+ return ()
156+
157+-- | Ensures that elements which are _not_ removed can still fire requests
158+-- during the same frame as other elements are updated.
159+testLiveRequestDMap
160+ :: forall t m
161+ . ( Reflex t
162+ , Adjustable t m
163+ , MonadHold t m
164+ , MonadFix m
165+ , Response m ~ Identity
166+ , Request m ~ RequestInt
167+ , Requester t m
168+ )
169+ => Event t ()
170+ -> m ()
171+testLiveRequestDMap pulse = do
172+ rec let requestIntOnReplace :: Int -> m ()
173+ requestIntOnReplace x = void $ requestingIdentity $ RequestInt x <$ rwrFinished
174+ (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-
175+ traverseDMapWithKeyWithAdjust
176+ (\(Const2 k) (Identity ()) -> Identity <$> requestIntOnReplace k)
177+ (mapToDMap $ M.singleton 1 ())
178+ ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)
179+ return ()
180+
181+delayedPulse
182+ :: forall t m
183+ . ( Reflex t
184+ , Adjustable t m
185+ , MonadHold t m
186+ , MonadFix m
187+ , Response m ~ Identity
188+ , Request m ~ RequestInt
189+ , PerformEvent t m
190+ , Requester t m
191+ )
192+ => Event t ()
193+ -> m ()
194+delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do
195+ -- This has the effect of delaying pulse' from pulse
196+ (_, pulse') <- runWithReplace (pure ()) $ pure (RequestInt 1) <$ pulse
197+ requestingIdentity pulse'
198+
199+data TestRequest a where
200+ TestRequest_Reverse :: String -> TestRequest String
201+ TestRequest_Increment :: Int -> TestRequest Int
202+
203+testMatchRequestsWithResponses
204+ :: forall m t req a
205+ . ( MonadFix m
206+ , MonadHold t m
207+ , Reflex t
208+ , PerformEvent t m
209+ , MonadIO (Performable m)
210+ , ForallF Show req
211+ , Has Read req
212+ )
213+ => Event t (req a) -> m (Event t (Map Int String))
214+testMatchRequestsWithResponses pulse = mdo
215+ (_, requests) <- runRequesterT (requesting pulse) responses
216+ let rawResponses = M.map (\v ->
217+ case words v of
218+ ["reverse", str] -> reverse str
219+ ["increment", i] -> show $ succ $ (read i :: Int)
220+ ) <$> rawRequestMap
221+ (rawRequestMap, responses) <- matchResponsesWithRequests reqEncoder requests (head . M.toList <$> rawResponses)
222+ pure rawResponses
223+ where
224+ reqEncoder :: forall a. req a -> (String, String -> Maybe a)
225+ reqEncoder r =
226+ ( whichever @Show @req @a $ show r
227+ , \x -> has @Read r $ readMaybe x
228+ )
229+
230+deriveArgDict ''TestRequest
231+
232+instance Show (TestRequest a) where
233+ show = \case
234+ TestRequest_Reverse str -> "reverse " <> str
235+ TestRequest_Increment i -> "increment " <> show i
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.hsnew file+39
@@ -0,0 +1,39 @@
1+module Main where
2+
3+import Control.Monad
4+import Language.Haskell.HLint (hlint)
5+import System.Directory
6+import System.Exit (exitFailure, exitSuccess)
7+import System.FilePath
8+import System.FilePath.Find
9+
10+main :: IO ()
11+main = do
12+ pwd <- getCurrentDirectory
13+ let runHlint f = hlint $ f:
14+ [ "--ignore=Redundant do"
15+ , "--ignore=Use camelCase"
16+ , "--ignore=Redundant $"
17+ , "--ignore=Use &&"
18+ , "--ignore=Use &&&"
19+ , "--ignore=Use const"
20+ , "--ignore=Use >=>"
21+ , "--ignore=Use ."
22+ , "--ignore=Use unless"
23+ , "--ignore=Reduce duplication"
24+ , "--cpp-define=USE_TEMPLATE_HASKELL"
25+ , "--cpp-define=DEBUG"
26+ , "--ignore=Use tuple-section"
27+ ]
28+ recurseInto = and <$> sequence
29+ [ fileType ==? Directory
30+ , fileName /=? ".git"
31+ ]
32+ matchFile = and <$> sequence
33+ [ extension ==? ".hs"
34+ ]
35+ files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
36+ ideas <- fmap concat $ forM files $ \f -> do
37+ putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
38+ runHlint f
39+ if null ideas then exitSuccess else exitFailure
test/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