on master help sign in
.github/workflows/haskell-ci.yml+41−40
since splitsnapshots
unifiedsplit
@@ -1,6 +1,6 @@
1# This GitHub workflow config has been generated by a script via
1# This GitHub workflow config has been generated by a script via
2#
2#
3−# haskell-ci 'github' '--config=cabal.haskell-ci' 'effectful.cabal'
3+# haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project'
4#
4#
5# To regenerate the script (for example after adjusting tested-with) run
5# To regenerate the script (for example after adjusting tested-with) run
6#
6#
@@ -8,9 +8,9 @@
8#
8#
9# For more information, see https://github.com/haskell-CI/haskell-ci
9# For more information, see https://github.com/haskell-CI/haskell-ci
10#
10#
11−# version: 0.13.20210621
11+# version: 0.13.20211116
12#
12#
13−# REGENDATA ("0.13.20210621",["github","--config=cabal.haskell-ci","effectful.cabal"])
13+# REGENDATA ("0.13.20211116",["github","--config=cabal.haskell-ci","cabal.project"])
14#
14#
15name: Haskell-CI
15name: Haskell-CI
16on:
16on:
@@ -24,26 +24,23 @@ jobs:
24 linux:
24 linux:
25 name: Haskell-CI - Linux - ${{ matrix.compiler }}
25 name: Haskell-CI - Linux - ${{ matrix.compiler }}
26 runs-on: ubuntu-18.04
26 runs-on: ubuntu-18.04
27+ timeout-minutes:
28+ 60
27 container:
29 container:
28 image: buildpack-deps:bionic
30 image: buildpack-deps:bionic
29 continue-on-error: ${{ matrix.allow-failure }}
31 continue-on-error: ${{ matrix.allow-failure }}
30 strategy:
32 strategy:
31 matrix:
33 matrix:
32 include:
34 include:
33− - compiler: ghc-9.2.0.20210422
35+ - compiler: ghc-9.2.1
34 compilerKind: ghc
36 compilerKind: ghc
35− compilerVersion: 9.2.0.20210422
37+ compilerVersion: 9.2.1
36 setup-method: ghcup
38 setup-method: ghcup
37− allow-failure: true
38− - compiler: ghc-9.0.1
39− compilerKind: ghc
40− compilerVersion: 9.0.1
41− setup-method: hvr-ppa
42 allow-failure: false
39 allow-failure: false
43− - compiler: ghc-8.10.4
40+ - compiler: ghc-8.10.7
44 compilerKind: ghc
41 compilerKind: ghc
45− compilerVersion: 8.10.4
42+ compilerVersion: 8.10.7
46− setup-method: hvr-ppa
43+ setup-method: ghcup
47 allow-failure: false
44 allow-failure: false
48 - compiler: ghc-8.8.4
45 - compiler: ghc-8.8.4
49 compilerKind: ghc
46 compilerKind: ghc
@@ -58,14 +55,18 @@ jobs:
58 apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5
55 apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5
59 if [ "${{ matrix.setup-method }}" = ghcup ]; then
56 if [ "${{ matrix.setup-method }}" = ghcup ]; then
60 mkdir -p "$HOME/.ghcup/bin"
57 mkdir -p "$HOME/.ghcup/bin"
61− curl -sL https://downloads.haskell.org/ghcup/0.1.14.1/x86_64-linux-ghcup-0.1.14.1 > "$HOME/.ghcup/bin/ghcup"
58+ curl -sL https://downloads.haskell.org/ghcup/0.1.17.3/x86_64-linux-ghcup-0.1.17.3 > "$HOME/.ghcup/bin/ghcup"
62 chmod a+x "$HOME/.ghcup/bin/ghcup"
59 chmod a+x "$HOME/.ghcup/bin/ghcup"
63 "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER"
60 "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER"
64− "$HOME/.ghcup/bin/ghcup" install cabal 3.4.0.0
61+ "$HOME/.ghcup/bin/ghcup" install cabal 3.6.2.0
65 else
62 else
66 apt-add-repository -y 'ppa:hvr/ghc'
63 apt-add-repository -y 'ppa:hvr/ghc'
67 apt-get update
64 apt-get update
68− apt-get install -y "$HCNAME" cabal-install-3.4
65+ apt-get install -y "$HCNAME"
66+ mkdir -p "$HOME/.ghcup/bin"
67+ curl -sL https://downloads.haskell.org/ghcup/0.1.17.3/x86_64-linux-ghcup-0.1.17.3 > "$HOME/.ghcup/bin/ghcup"
68+ chmod a+x "$HOME/.ghcup/bin/ghcup"
69+ "$HOME/.ghcup/bin/ghcup" install cabal 3.6.2.0
69 fi
70 fi
70 env:
71 env:
71 HCKIND: ${{ matrix.compilerKind }}
72 HCKIND: ${{ matrix.compilerKind }}
@@ -83,20 +84,20 @@ jobs:
83 echo "HC=$HC" >> "$GITHUB_ENV"
84 echo "HC=$HC" >> "$GITHUB_ENV"
84 echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV"
85 echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV"
85 echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV"
86 echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV"
86− echo "CABAL=$HOME/.ghcup/bin/cabal-3.4.0.0 -vnormal+nowrap" >> "$GITHUB_ENV"
87+ echo "CABAL=$HOME/.ghcup/bin/cabal-3.6.2.0 -vnormal+nowrap" >> "$GITHUB_ENV"
87 else
88 else
88 HC=$HCDIR/bin/$HCKIND
89 HC=$HCDIR/bin/$HCKIND
89 echo "HC=$HC" >> "$GITHUB_ENV"
90 echo "HC=$HC" >> "$GITHUB_ENV"
90 echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV"
91 echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV"
91 echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV"
92 echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV"
92− echo "CABAL=/opt/cabal/3.4/bin/cabal -vnormal+nowrap" >> "$GITHUB_ENV"
93+ echo "CABAL=$HOME/.ghcup/bin/cabal-3.6.2.0 -vnormal+nowrap" >> "$GITHUB_ENV"
93 fi
94 fi
94
95
95 HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')
96 HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')
96 echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV"
97 echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV"
97 echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV"
98 echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV"
98 echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV"
99 echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV"
99− if [ $((HCNUMVER >= 90200)) -ne 0 ] ; then echo "HEADHACKAGE=true" >> "$GITHUB_ENV" ; else echo "HEADHACKAGE=false" >> "$GITHUB_ENV" ; fi
100+ echo "HEADHACKAGE=false" >> "$GITHUB_ENV"
100 echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV"
101 echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV"
101 echo "GHCJSARITH=0" >> "$GITHUB_ENV"
102 echo "GHCJSARITH=0" >> "$GITHUB_ENV"
102 env:
103 env:
@@ -125,17 +126,10 @@ jobs:
125 repository hackage.haskell.org
126 repository hackage.haskell.org
126 url: http://hackage.haskell.org/
127 url: http://hackage.haskell.org/
127 EOF
128 EOF
128− if $HEADHACKAGE; then
129 cat >> $CABAL_CONFIG <<EOF
129 cat >> $CABAL_CONFIG <<EOF
130− repository head.hackage.ghc.haskell.org
130+ program-default-options
131− url: https://ghc.gitlab.haskell.org/head.hackage/
131+ ghc-options: $GHCJOBS +RTS -M3G -RTS
132− secure: True
133− root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d
134− 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329
135− f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89
136− key-threshold: 3
137 EOF
132 EOF
138− fi
139 cat $CABAL_CONFIG
133 cat $CABAL_CONFIG
140 - name: versions
134 - name: versions
141 run: |
135 run: |
@@ -148,7 +142,7 @@ jobs:
148 - name: cache (tools)
142 - name: cache (tools)
149 uses: actions/cache@v2
143 uses: actions/cache@v2
150 with:
144 with:
151− key: ${{ runner.os }}-${{ matrix.compiler }}-tools-b692a344
145+ key: ${{ runner.os }}-${{ matrix.compiler }}-tools-16fe7d6d
152 path: ~/.haskell-ci-tools
146 path: ~/.haskell-ci-tools
153 - name: install cabal-plan
147 - name: install cabal-plan
154 run: |
148 run: |
@@ -161,8 +155,8 @@ jobs:
161 cabal-plan --version
155 cabal-plan --version
162 - name: install doctest
156 - name: install doctest
163 run: |
157 run: |
164− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then $CABAL --store-dir=$HOME/.haskell-ci-tools/store v2-install $ARG_COMPILER --ignore-project -j2 doctest --constraint='doctest ^>=0.18' ; fi
158+ $CABAL --store-dir=$HOME/.haskell-ci-tools/store v2-install $ARG_COMPILER --ignore-project -j2 doctest --constraint='doctest ^>=0.20'
165− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then doctest --version ; fi
159+ doctest --version
166 - name: checkout
160 - name: checkout
167 uses: actions/checkout@v2
161 uses: actions/checkout@v2
168 with:
162 with:
@@ -170,7 +164,8 @@ jobs:
170 - name: initial cabal.project for sdist
164 - name: initial cabal.project for sdist
171 run: |
165 run: |
172 touch cabal.project
166 touch cabal.project
173− echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project
167+ echo "packages: $GITHUB_WORKSPACE/source/effectful" >> cabal.project
168+ echo "packages: $GITHUB_WORKSPACE/source/effectful-core" >> cabal.project
174 cat cabal.project
169 cat cabal.project
175 - name: sdist
170 - name: sdist
176 run: |
171 run: |
@@ -184,20 +179,22 @@ jobs:
184 run: |
179 run: |
185 PKGDIR_effectful="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/effectful-[0-9.]*')"
180 PKGDIR_effectful="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/effectful-[0-9.]*')"
186 echo "PKGDIR_effectful=${PKGDIR_effectful}" >> "$GITHUB_ENV"
181 echo "PKGDIR_effectful=${PKGDIR_effectful}" >> "$GITHUB_ENV"
182+ PKGDIR_effectful_core="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/effectful-core-[0-9.]*')"
183+ echo "PKGDIR_effectful_core=${PKGDIR_effectful_core}" >> "$GITHUB_ENV"
187 rm -f cabal.project cabal.project.local
184 rm -f cabal.project cabal.project.local
188 touch cabal.project
185 touch cabal.project
189 touch cabal.project.local
186 touch cabal.project.local
190 echo "packages: ${PKGDIR_effectful}" >> cabal.project
187 echo "packages: ${PKGDIR_effectful}" >> cabal.project
188+ echo "packages: ${PKGDIR_effectful_core}" >> cabal.project
191 echo "package effectful" >> cabal.project
189 echo "package effectful" >> cabal.project
192 echo " ghc-options: -Werror=missing-methods" >> cabal.project
190 echo " ghc-options: -Werror=missing-methods" >> cabal.project
191+ echo "package effectful-core" >> cabal.project
192+ echo " ghc-options: -Werror=missing-methods" >> cabal.project
193 cat >> cabal.project <<EOF
193 cat >> cabal.project <<EOF
194 package effectful
194 package effectful
195 flags: +benchmark-foreign-libraries
195 flags: +benchmark-foreign-libraries
196 EOF
196 EOF
197− if $HEADHACKAGE; then
198− echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1,/g')" >> cabal.project
199− fi
200− $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(effectful)$/; }' >> cabal.project.local
197+ $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(effectful|effectful-core)$/; }' >> cabal.project.local
201 cat cabal.project
198 cat cabal.project
202 cat cabal.project.local
199 cat cabal.project.local
203 - name: dump install plan
200 - name: dump install plan
@@ -225,14 +222,18 @@ jobs:
225 $CABAL v2-test $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --test-show-details=direct
222 $CABAL v2-test $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --test-show-details=direct
226 - name: doctest
223 - name: doctest
227 run: |
224 run: |
228− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then cd ${PKGDIR_effectful} || false ; fi
225+ cd ${PKGDIR_effectful} || false
229− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then doctest -XBangPatterns -XConstraintKinds -XDataKinds -XDeriveFunctor -XFlexibleContexts -XFlexibleInstances -XGADTs -XGeneralizedNewtypeDeriving -XLambdaCase -XMultiParamTypeClasses -XNoStarIsType -XRankNTypes -XRecordWildCards -XRoleAnnotations -XScopedTypeVariables -XStandaloneDeriving -XStrictData -XTupleSections -XTypeApplications -XTypeFamilies -XTypeOperators src ; fi
226+ doctest -XBangPatterns -XConstraintKinds -XDataKinds -XDeriveFunctor -XDeriveGeneric -XFlexibleContexts -XFlexibleInstances -XGADTs -XGeneralizedNewtypeDeriving -XLambdaCase -XMultiParamTypeClasses -XNoStarIsType -XRankNTypes -XRecordWildCards -XRoleAnnotations -XScopedTypeVariables -XStandaloneDeriving -XTupleSections -XTypeApplications -XTypeFamilies -XTypeOperators src
230− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then cd ${PKGDIR_effectful} || false ; fi
227+ cd ${PKGDIR_effectful_core} || false
228+ doctest -XBangPatterns -XConstraintKinds -XDataKinds -XDeriveFunctor -XDeriveGeneric -XFlexibleContexts -XFlexibleInstances -XGADTs -XGeneralizedNewtypeDeriving -XLambdaCase -XMultiParamTypeClasses -XNoStarIsType -XRankNTypes -XRecordWildCards -XRoleAnnotations -XScopedTypeVariables -XStandaloneDeriving -XTupleSections -XTypeApplications -XTypeFamilies -XTypeOperators src
229+ cd ${PKGDIR_effectful_core} || false
231− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then doctest -XBangPatterns -XConstraintKinds -XDataKinds -XDeriveFunctor -XFlexibleContexts -XFlexibleInstances -XGADTs -XGeneralizedNewtypeDeriving -XLambdaCase -XMultiParamTypeClasses -XNoStarIsType -XRankNTypes -XRecordWildCards -XRoleAnnotations -XScopedTypeVariables -XStandaloneDeriving -XStrictData -XTupleSections -XTypeApplications -XTypeFamilies -XTypeOperators utils ; fi
230+ doctest -XBangPatterns -XConstraintKinds -XDataKinds -XDeriveFunctor -XDeriveGeneric -XFlexibleContexts -XFlexibleInstances -XGADTs -XGeneralizedNewtypeDeriving -XLambdaCase -XMultiParamTypeClasses -XNoStarIsType -XRankNTypes -XRecordWildCards -XRoleAnnotations -XScopedTypeVariables -XStandaloneDeriving -XTupleSections -XTypeApplications -XTypeFamilies -XTypeOperators utils
232 - name: cabal check
231 - name: cabal check
233 run: |
232 run: |
234 cd ${PKGDIR_effectful} || false
233 cd ${PKGDIR_effectful} || false
235 ${CABAL} -vnormal check
234 ${CABAL} -vnormal check
235+ cd ${PKGDIR_effectful_core} || false
236+ ${CABAL} -vnormal check
236 - name: haddock
237 - name: haddock
237 run: |
238 run: |
238 $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all
239 $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all
README.md+25−4
@@ -1,7 +1,10 @@
1# effectful
1# effectful
2
2
3[![Build Status](https://github.com/arybczak/effectful/workflows/Haskell-CI/badge.svg?branch=master)](https://github.com/arybczak/effectful/actions?query=branch%3Amaster)
3[![Build Status](https://github.com/arybczak/effectful/workflows/Haskell-CI/badge.svg?branch=master)](https://github.com/arybczak/effectful/actions?query=branch%3Amaster)
4−[![Hackage](https://img.shields.io/hackage/v/effectful.svg)](https://hackage.haskell.org/package/effectful)
4+[![Documentation](https://img.shields.io/static/v1?label=docs&message=effectful-core-0.1&color=informational)](https://rybczak.net/files/effectful/effectful-core-0.1-docs)
5+[![Documentation](https://img.shields.io/static/v1?label=docs&message=effectful-0.1&color=informational)](https://rybczak.net/files/effectful/effectful-0.1-docs)
6+
7+<img src="https://user-images.githubusercontent.com/387658/127747903-f728437f-2ee4-47b8-9f0c-5102fd44c8e4.png" width="128">
5
8
6*Note:* this is a pre-release.
9*Note:* this is a pre-release.
7
10
@@ -17,8 +20,8 @@ Main features:
17
20
182. Easy to use API (no boilerplate code and dealing with arcane types).
212. Easy to use API (no boilerplate code and dealing with arcane types).
19
22
20−3. Correct semantics in presence of runtime exceptions (no more lost or
23+3. Correct semantics in presence of runtime exceptions (no more lost state
21− discarded state).
24+ modifications).
22
25
234. Seamless integration with the existing ecosystem (`exceptions`,
264. Seamless integration with the existing ecosystem (`exceptions`,
24 `monad-control`, `unliftio-core`, `resourcet` etc.).
27 `monad-control`, `unliftio-core`, `resourcet` etc.).
@@ -100,11 +103,25 @@ to "boring" transformer stacks, most of which are a dozen of newtype'd `StateT`
100or `ReaderT` transformers, each with a few associated operations (usually tied
103or `ReaderT` transformers, each with a few associated operations (usually tied
101to a type class), not to replace monad transformers altogether.
104to a type class), not to replace monad transformers altogether.
102
105
106+## Usage
107+
108+The effect system and its effects are split among several libraries:
109+
110+- The `effectful-core` library contains the main machinery of the effect system
111+ itself and a few basic effects.
112+ It aims for a small dependency footprint and provides the building blocks for
113+ more advanced effects.
114+
115+- _TBD_ `effectful-resource`, `effectful-process`, ...
116+
117+- Finally, the `effectful` library which comes with 'batteries included'. It is
118+ build on top of the other libraries and re-exports the functionality of those.
119+
103## Example
120## Example
104
121
105A `Filesystem` effect with two handlers, one that runs in `IO` and another that
122A `Filesystem` effect with two handlers, one that runs in `IO` and another that
106uses an in-memory virtual file system can be found
123uses an in-memory virtual file system can be found
107−[here](https://github.com/arybczak/effectful/blob/master/examples/FileSystem.hs).
124+[here](https://github.com/arybczak/effectful/blob/master/effectful/examples/FileSystem.hs).
108
125
109## Resources
126## Resources
110
127
@@ -122,3 +139,7 @@ Blog posts:
122* [ReaderT design pattern](https://www.fpcomplete.com/blog/2017/06/readert-design-pattern/) by Michael Snoyman.
139* [ReaderT design pattern](https://www.fpcomplete.com/blog/2017/06/readert-design-pattern/) by Michael Snoyman.
123
140
124* [Exceptions Best Practices](https://www.fpcomplete.com/blog/2016/11/exceptions-best-practices-haskell/) by Michael Snoyman.
141* [Exceptions Best Practices](https://www.fpcomplete.com/blog/2016/11/exceptions-best-practices-haskell/) by Michael Snoyman.
142+
143+----------------------------------------
144+
145+<div>Icons made by <a href="https://www.freepik.com" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div>
cabal.haskell-ci+1−3
@@ -1,11 +1,9 @@
1branches: master
1branches: master
2
2
3−doctest: <9.2
3+doctest: <9.3
4tests: True
4tests: True
5benchmarks: True
5benchmarks: True
6
6
7−ghcup-jobs: >=9.2
8−
9raw-project
7raw-project
10 package effectful
8 package effectful
11 flags: +benchmark-foreign-libraries
9 flags: +benchmark-foreign-libraries
cabal.projectnew file+3
@@ -0,0 +1,3 @@
1+packages:
2+ effectful/effectful.cabal
3+ effectful-core/effectful-core.cabal
doctest.sh+32−22
@@ -7,25 +7,35 @@
7# - Compile doctest with the same GHC version the project currently uses.
7# - Compile doctest with the same GHC version the project currently uses.
8#
8#
9
9
10+set -eu
11+
12+run_doctest() {
13+ pushd "${1}"
10−doctest src \
14+ doctest \
15+ "${2}" \
11− -XBangPatterns \
16+ -XBangPatterns \
12− -XConstraintKinds \
17+ -XConstraintKinds \
13− -XDataKinds \
18+ -XDataKinds \
14− -XDeriveFunctor \
19+ -XDeriveFunctor \
20+ -XDeriveGeneric \
15− -XFlexibleContexts \
21+ -XFlexibleContexts \
16− -XFlexibleInstances \
22+ -XFlexibleInstances \
17− -XGADTs \
23+ -XGADTs \
18− -XGeneralizedNewtypeDeriving \
24+ -XGeneralizedNewtypeDeriving \
19− -XLambdaCase \
25+ -XLambdaCase \
20− -XMultiParamTypeClasses \
26+ -XMultiParamTypeClasses \
21− -XNoStarIsType \
27+ -XNoStarIsType \
22− -XRankNTypes \
28+ -XRankNTypes \
23− -XRecordWildCards \
29+ -XRecordWildCards \
24− -XRoleAnnotations \
30+ -XRoleAnnotations \
25− -XScopedTypeVariables \
31+ -XScopedTypeVariables \
26− -XStandaloneDeriving \
32+ -XStandaloneDeriving \
27− -XStrictData \
28− -XTupleSections \
33+ -XTupleSections \
29− -XTypeApplications \
34+ -XTypeApplications \
30− -XTypeFamilies \
35+ -XTypeFamilies \
31− -XTypeOperators
36+ -XTypeOperators
37+ popd
38+}
39+
40+run_doctest effectful-core src
41+run_doctest effectful src
effectful-core/CHANGELOG.mdnew file+2
@@ -0,0 +1,2 @@
1+# effectful-core-0.0.0.0 (2021-06-13)
2+* Initial alpha release.
effectful-core/LICENSEnew file+30
@@ -0,0 +1,30 @@
1+Copyright (c) 2021, Andrzej Rybczak
2+
3+All rights reserved.
4+
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
7+
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
10+
11+ * Redistributions in binary form must reproduce the above
12+ copyright notice, this list of conditions and the following
13+ disclaimer in the documentation and/or other materials provided
14+ with the distribution.
15+
16+ * Neither the name of Andrzej Rybczak nor the names of other
17+ contributors may be used to endorse or promote products derived
18+ from this software without specific prior written permission.
19+
20+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
effectful.cabal → effectful-core/effectful-core.cabalrenamed+22−85
@@ -1,7 +1,7 @@
1cabal-version: 2.4
1cabal-version: 2.4
2build-type: Simple
2build-type: Simple
3−name: effectful
3+name: effectful-core
4−version: 0.0.0.0
4+version: 0.1
5license: BSD-3-Clause
5license: BSD-3-Clause
6license-file: LICENSE
6license-file: LICENSE
7category: Control
7category: Control
@@ -11,21 +11,20 @@ synopsis: An easy to use, performant extensible effects library.
11
11
12description: An easy to use, performant extensible effects library with seamless
12description: An easy to use, performant extensible effects library with seamless
13 integration with the existing Haskell ecosystem.
13 integration with the existing Haskell ecosystem.
14+ .
15+ This library provides core definitions with a minimal dependency
16+ footprint. See the @<https://hackage.haskell.org/package/effectful effectful>@
17+ package for documentation and the "batteries-included" variant.
14
18
15extra-source-files: CHANGELOG.md
19extra-source-files: CHANGELOG.md
16− README.md
17
20
18−tested-with: GHC ==8.8.4 || ==8.10.4 || ==9.0.1 || ==9.2.0.20210422
21+tested-with: GHC ==8.8.4 || ==8.10.7 || ==9.2.1
19
22
20bug-reports: https://github.com/arybczak/effectful/issues
23bug-reports: https://github.com/arybczak/effectful/issues
21source-repository head
24source-repository head
22 type: git
25 type: git
23 location: https://github.com/arybczak/effectful.git
26 location: https://github.com/arybczak/effectful.git
24
27
25−flag benchmark-foreign-libraries
26− description: Include other effect libraries in the benchmarks.
27− default: False
28−
29common language
28common language
30 ghc-options: -Wall -Wcompat
29 ghc-options: -Wall -Wcompat
31
30
@@ -35,6 +34,7 @@ common language
35 ConstraintKinds
34 ConstraintKinds
36 DataKinds
35 DataKinds
37 DeriveFunctor
36 DeriveFunctor
37+ DeriveGeneric
38 FlexibleContexts
38 FlexibleContexts
39 FlexibleInstances
39 FlexibleInstances
40 GADTs
40 GADTs
@@ -47,7 +47,6 @@ common language
47 RoleAnnotations
47 RoleAnnotations
48 ScopedTypeVariables
48 ScopedTypeVariables
49 StandaloneDeriving
49 StandaloneDeriving
50− StrictData
51 TupleSections
50 TupleSections
52 TypeApplications
51 TypeApplications
53 TypeFamilies
52 TypeFamilies
@@ -68,34 +67,32 @@ library
68
67
69 ghc-options: -O2
68 ghc-options: -O2
70
69
71− build-depends: base >= 4.13 && <5
70+ build-depends: effectful-internal-utils
72− , async
71+
72+ build-depends: base >= 4.13 && < 5
73− , containers
73+ , containers >= 0.6
74− , effectful-internal-utils
75− , exceptions
74+ , exceptions >= 0.10.4
76− , monad-control
75+ , monad-control >= 1.0.3
77− , primitive
76+ , primitive >= 0.7.3.0
78− , resourcet
79− , stm
80− , transformers-base
77+ , transformers-base >= 0.4.6
81− , unliftio-core
78+ , unliftio-core >= 0.2.0.1
82− , unliftio
83
79
84 hs-source-dirs: src
80 hs-source-dirs: src
85
81
86 exposed-modules: Effectful
82 exposed-modules: Effectful
87− Effectful.Async
83+ Effectful.Dispatch.Dynamic
84+ Effectful.Dispatch.Static
88 Effectful.Error
85 Effectful.Error
89 Effectful.Error.Dynamic
86 Effectful.Error.Dynamic
90 Effectful.Fail
87 Effectful.Fail
91− Effectful.Handler
92 Effectful.Internal.Effect
88 Effectful.Internal.Effect
93 Effectful.Internal.Env
89 Effectful.Internal.Env
94 Effectful.Internal.Monad
90 Effectful.Internal.Monad
95 Effectful.Internal.Unlift
91 Effectful.Internal.Unlift
96 Effectful.Monad
92 Effectful.Monad
93+ Effectful.Prim
97 Effectful.Reader
94 Effectful.Reader
98− Effectful.Resource
95+ Effectful.Reader.Dynamic
99 Effectful.State.Dynamic
96 Effectful.State.Dynamic
100 Effectful.State.Local
97 Effectful.State.Local
101 Effectful.State.Shared
98 Effectful.State.Shared
@@ -103,64 +100,4 @@ library
103 Effectful.Writer.Local
100 Effectful.Writer.Local
104 Effectful.Writer.Shared
101 Effectful.Writer.Shared
105
102
106− reexported-modules: Effectful.Internal.Utils
103+ reexported-modules: Effectful.Internal.Utils
107−
108−test-suite test
109− import: language
110−
111− ghc-options: -threaded -rtsopts -with-rtsopts=-N4
112−
113− build-depends: base
114− , containers
115− , effectful
116− , exceptions
117− , lifted-base
118− , tasty
119− , tasty-hunit
120− , unliftio
121−
122− hs-source-dirs: tests
123−
124− type: exitcode-stdio-1.0
125− main-is: Main.hs
126−
127− other-modules: AsyncTests
128− ConcurrencyTests
129− ErrorTests
130− StateTests
131− Utils
132−
133−benchmark bench
134− import: language
135−
136− ghc-options: -threaded -rtsopts -with-rtsopts=-T
137−
138− if flag(benchmark-foreign-libraries)
139− build-depends: mtl
140−
141− if impl(ghc < 9)
142− build-depends: freer-simple
143−
144− if impl(ghc < 9.2)
145− build-depends: fused-effects
146−
147− if impl(ghc < 9)
148− build-depends: polysemy
149−
150− build-depends: base
151− , effectful
152− , tasty-bench
153− , unix
154− , unliftio
155− , async
156−
157− hs-source-dirs: bench
158−
159− type: exitcode-stdio-1.0
160− main-is: Main.hs
161−
162− other-modules: Concurrency
163− Countdown
164− FileSizes
165− Unlift
166− Utils
src/Effectful.hs → effectful-core/src/Effectful.hsrenamed+9−8
@@ -8,10 +8,10 @@ module Effectful
8
8
9 -- * Running the 'Eff' monad
9 -- * Running the 'Eff' monad
10
10
11− -- ** Pure operations
11+ -- ** Pure computations
12 , runPureEff
12 , runPureEff
13
13
14− -- ** Operations with side effects
14+ -- ** Computations with side effects
15 , IOE
15 , IOE
16 , runEff
16 , runEff
17
17
@@ -21,6 +21,7 @@ module Effectful
21 , Limit(..)
21 , Limit(..)
22 , unliftStrategy
22 , unliftStrategy
23 , withUnliftStrategy
23 , withUnliftStrategy
24+ , withEffToIO
24
25
25 -- * 'Effect' handlers
26 -- * 'Effect' handlers
26
27
@@ -29,13 +30,9 @@ module Effectful
29
30
30 -- ** Basic handlers
31 -- ** Basic handlers
31 , interpret
32 , interpret
32− , interpretM
33−
34− -- ** Derived handlers
35 , reinterpret
33 , reinterpret
36− , reinterpretM
37
34
38− -- ** Handling local 'Eff' operations
35+ -- ** Handling local 'Eff' computations
39 , LocalEnv
36 , LocalEnv
40
37
41 -- *** Unlifts
38 -- *** Unlifts
@@ -51,7 +48,11 @@ module Effectful
51 -- *** Bidirectional lifts
48 -- *** Bidirectional lifts
52 , localLiftUnlift
49 , localLiftUnlift
53 , localLiftUnliftIO
50 , localLiftUnliftIO
51+
52+ -- * Re-exports
53+ , MonadIO(..)
54+ , MonadUnliftIO(..)
54 ) where
55 ) where
55
56
56−import Effectful.Handler
57+import Effectful.Dispatch.Dynamic
57import Effectful.Monad
58import Effectful.Monad
effectful-core/src/Effectful/Dispatch/Dynamic.hsnew file+246
@@ -0,0 +1,246 @@
1+module Effectful.Dispatch.Dynamic
2+ ( -- * Sending operations to the handler
3+ send
4+
5+ -- * Handling effects
6+ , EffectHandler
7+ , interpret
8+ , reinterpret
9+
10+ -- ** Handling local 'Eff' computations
11+ , LocalEnv
12+
13+ -- *** Unlifts
14+ , localSeqUnlift
15+ , localSeqUnliftIO
16+ , localUnlift
17+ , localUnliftIO
18+
19+ -- *** Lifts
20+ , withLiftMap
21+ , withLiftMapIO
22+
23+ -- *** Bidirectional lifts
24+ , localLiftUnlift
25+ , localLiftUnliftIO
26+
27+ -- *** Utils
28+ , SuffixOf
29+
30+ -- * Re-exports
31+ , HasCallStack
32+ ) where
33+
34+import Control.Monad.IO.Unlift
35+import Data.Kind
36+import GHC.Stack (HasCallStack)
37+
38+import Effectful.Internal.Effect
39+import Effectful.Internal.Env
40+import Effectful.Internal.Monad
41+
42+----------------------------------------
43+-- Handling effects
44+
45+-- | Interpret an effect.
46+interpret
47+ :: EffectHandler e es
48+ -- ^ The effect handler.
49+ -> Eff (e : es) a
50+ -> Eff es a
51+interpret handler m = unsafeEff $ \es -> do
52+ les <- forkEnv es
53+ (`unEff` es) $ runHandler (HandlerA les handler) m
54+
55+-- | Interpret an effect using other effects.
56+reinterpret
57+ :: (Eff handlerEs a -> Eff es b)
58+ -- ^ Introduction of effects encapsulated within the handler.
59+ -> EffectHandler e handlerEs
60+ -- ^ The effect handler.
61+ -> Eff (e : es) a
62+ -> Eff es b
63+reinterpret runHandlerEs handler m = unsafeEff $ \es -> do
64+ les0 <- forkEnv es
65+ (`unEff` les0) . runHandlerEs . unsafeEff $ \les -> do
66+ (`unEff` es) $ runHandler (HandlerA les handler) m
67+
68+----------------------------------------
69+-- Unlifts
70+
71+-- | Create a local unlifting function with the 'SeqUnlift' strategy. For the
72+-- general version see 'localUnlift'.
73+localSeqUnlift
74+ :: (HasCallStack, SuffixOf es handlerEs)
75+ => LocalEnv localEs handlerEs
76+ -- ^ Local environment.
77+ -> ((forall r. Eff localEs r -> Eff es r) -> Eff es a)
78+ -- ^ Continuation with the unlifting function in scope.
79+ -> Eff es a
80+localSeqUnlift (LocalEnv les) k = unsafeEff $ \es -> do
81+ seqUnliftIO les $ \unlift -> do
82+ (`unEff` es) $ k $ unsafeEff_ . unlift
83+
84+-- | Create a local unlifting function with the 'SeqUnlift' strategy. For the
85+-- general version see 'localUnliftIO'.
86+localSeqUnliftIO
87+ :: (HasCallStack, SuffixOf es handlerEs, IOE :> es)
88+ => LocalEnv localEs handlerEs
89+ -- ^ Local environment.
90+ -> ((forall r. Eff localEs r -> IO r) -> IO a)
91+ -- ^ Continuation with the unlifting function in scope.
92+ -> Eff es a
93+localSeqUnliftIO (LocalEnv les) k = liftIO $ seqUnliftIO les k
94+
95+-- | Create a local unlifting function with the given strategy.
96+localUnlift
97+ :: (HasCallStack, SuffixOf es handlerEs)
98+ => LocalEnv localEs handlerEs
99+ -- ^ Local environment.
100+ -> UnliftStrategy
101+ -> ((forall r. Eff localEs r -> Eff es r) -> Eff es a)
102+ -- ^ Continuation with the unlifting function in scope.
103+ -> Eff es a
104+localUnlift (LocalEnv les) strategy k = case strategy of
105+ SeqUnlift -> unsafeEff $ \es -> do
106+ seqUnliftIO les $ \unlift -> do
107+ (`unEff` es) $ k $ unsafeEff_ . unlift
108+ ConcUnlift p l -> unsafeEff $ \es -> do
109+ concUnliftIO les p l $ \unlift -> do
110+ (`unEff` es) $ k $ unsafeEff_ . unlift
111+
112+-- | Create a local unlifting function with the given strategy.
113+localUnliftIO
114+ :: (HasCallStack, SuffixOf es handlerEs, IOE :> es)
115+ => LocalEnv localEs handlerEs
116+ -- ^ Local environment.
117+ -> UnliftStrategy
118+ -> ((forall r. Eff localEs r -> IO r) -> IO a)
119+ -- ^ Continuation with the unlifting function in scope.
120+ -> Eff es a
121+localUnliftIO (LocalEnv les) strategy k = case strategy of
122+ SeqUnlift -> liftIO $ seqUnliftIO les k
123+ ConcUnlift p l -> liftIO $ concUnliftIO les p l k
124+
125+-- | Utility for lifting 'Eff' computations of type
126+--
127+-- @'Eff' es a -> 'Eff' es b@
128+--
129+-- to
130+--
131+-- @'Eff' localEs a -> 'Eff' localEs b@
132+--
133+-- /Note:/ the computation must not run its argument in a separate thread,
134+-- attempting to do so will result in a runtime error.
135+withLiftMap
136+ :: (HasCallStack, SuffixOf es handlerEs)
137+ => LocalEnv localEs handlerEs
138+ -- ^ Local environment.
139+ -> ((forall a b. (Eff es a -> Eff es b) -> Eff localEs a -> Eff localEs b) -> Eff es r)
140+ -- ^ Continuation with the lifting function in scope.
141+ -> Eff es r
142+withLiftMap !_ k = unsafeEff $ \es -> do
143+ -- The LocalEnv parameter is not used, but we need it to constraint the
144+ -- localEs type variable. It's also strict so that callers don't cheat.
145+ (`unEff` es) $ k $ \mapEff m -> unsafeEff $ \localEs -> do
146+ seqUnliftIO localEs $ \unlift -> do
147+ (`unEff` es) . mapEff . unsafeEff_ $ unlift m
148+
149+-- | Utility for lifting 'IO' computations of type
150+--
151+-- @'IO' a -> 'IO' b@
152+--
153+-- to
154+--
155+-- @'Eff' localEs a -> 'Eff' localEs b@
156+--
157+-- /Note:/ the computation must not run its argument in a separate thread,
158+-- attempting to do so will result in a runtime error.
159+--
160+-- Useful e.g. for lifting the unmasking function in
161+-- 'Control.Exception.mask'-like computations:
162+--
163+-- >>> :{
164+-- data Fork :: Effect where
165+-- ForkWithUnmask :: ((forall a. m a -> m a) -> m ()) -> Fork m ThreadId
166+-- :}
167+--
168+-- >>> :{
169+-- runFork :: IOE :> es => Eff (Fork : es) a -> Eff es a
170+-- runFork = interpret $ \env (ForkWithUnmask m) -> withLiftMapIO env $ \liftMap -> do
171+-- localUnliftIO env (ConcUnlift Ephemeral $ Limited 1) $ \unlift -> do
172+-- forkIOWithUnmask $ \unmask -> unlift $ m $ liftMap unmask
173+-- :}
174+withLiftMapIO
175+ :: (HasCallStack, SuffixOf es handlerEs, IOE :> es)
176+ => LocalEnv localEs handlerEs
177+ -- ^ Local environment.
178+ -> ((forall a b. (IO a -> IO b) -> Eff localEs a -> Eff localEs b) -> Eff es r)
179+ -- ^ Continuation with the lifting function in scope.
180+ -> Eff es r
181+withLiftMapIO !_ k = k $ \mapIO m -> unsafeEff $ \es -> do
182+ -- The LocalEnv parameter is not used, but we need it to constraint the
183+ -- localEs type variable. It's also strict so that callers don't cheat.
184+ seqUnliftIO es $ \unlift -> mapIO $ unlift m
185+
186+----------------------------------------
187+-- Bidirectional lifts
188+
189+-- | Create a local lifting and unlifting function with the given strategy.
190+--
191+-- Useful for lifting complicated 'Eff' computations where the monadic action
192+-- shows in both positive (as a result) and negative (as an argument) position.
193+--
194+-- /Note:/ depending on the computation you're lifting 'localUnlift' along with
195+-- 'withLiftMap' might be enough and is more efficient.
196+localLiftUnlift
197+ :: (HasCallStack, SuffixOf es handlerEs)
198+ => LocalEnv localEs handlerEs
199+ -- ^ Local environment.
200+ -> UnliftStrategy
201+ -> ((forall r. Eff es r -> Eff localEs r) -> (forall r. Eff localEs r -> Eff es r) -> Eff es a)
202+ -- ^ Continuation with the lifting and unlifting function in scope.
203+ -> Eff es a
204+localLiftUnlift (LocalEnv les) strategy k = case strategy of
205+ SeqUnlift -> unsafeEff $ \es -> do
206+ seqUnliftIO es $ \unliftEs -> do
207+ seqUnliftIO les $ \unliftLocalEs -> do
208+ (`unEff` es) $ k (unsafeEff_ . unliftEs) (unsafeEff_ . unliftLocalEs)
209+ ConcUnlift p l -> unsafeEff $ \es -> do
210+ concUnliftIO es p l $ \unliftEs -> do
211+ concUnliftIO les p l $ \unliftLocalEs -> do
212+ (`unEff` es) $ k (unsafeEff_ . unliftEs) (unsafeEff_ . unliftLocalEs)
213+
214+-- | Create a local unlifting function with the given strategy along with an
215+-- unrestricted lifting function.
216+--
217+-- Useful for lifting complicated 'IO' computations where the monadic action
218+-- shows in both positive (as a result) and negative (as an argument) position.
219+--
220+-- /Note:/ depending on the computation you're lifting 'localUnliftIO' along
221+-- with 'withLiftMapIO' might be enough and is more efficient.
222+localLiftUnliftIO
223+ :: (HasCallStack, SuffixOf es handlerEs, IOE :> es)
224+ => LocalEnv localEs handlerEs
225+ -- ^ Local environment.
226+ -> UnliftStrategy
227+ -> ((forall r. IO r -> Eff localEs r) -> (forall r. Eff localEs r -> IO r) -> IO a)
228+ -- ^ Continuation with the lifting and unlifting function in scope.
229+ -> Eff es a
230+localLiftUnliftIO (LocalEnv les) strategy k = case strategy of
231+ SeqUnlift -> liftIO $ seqUnliftIO les $ k unsafeEff_
232+ ConcUnlift p l -> liftIO $ concUnliftIO les p l $ k unsafeEff_
233+
234+----------------------------------------
235+-- Utils
236+
237+-- | Require that the second list of effects is a suffix of the first one.
238+--
239+-- In other words, 'SuffixOf' @es@ @baseEs@ means "a suffix of @es@ is
240+-- @baseEs@".
241+type family SuffixOf (es :: [Effect]) (baseEs :: [Effect]) :: Constraint where
242+ SuffixOf baseEs baseEs = ()
243+ SuffixOf (e : es) baseEs = SuffixOf es baseEs
244+
245+-- $setup
246+-- >>> import Control.Concurrent
effectful-core/src/Effectful/Dispatch/Static.hsnew file+82
@@ -0,0 +1,82 @@
1+module Effectful.Dispatch.Static
2+ ( -- * Low level API
3+ DataA(..)
4+
5+ -- ** Extending the environment
6+ , runData
7+ , evalData
8+ , execData
9+
10+ -- ** Data retrieval and update
11+ , getData
12+ , putData
13+ , stateData
14+ , stateDataM
15+ , localData
16+
17+ -- ** Unlifts
18+ , seqUnliftIO
19+ , concUnliftIO
20+
21+ -- ** Utils
22+ , unEff
23+ , unsafeEff
24+ , unsafeEff_
25+ , unsafeLiftMapIO
26+ , unsafeUnliftIO
27+
28+ -- * Primitive API
29+ , Env
30+ , Relinker(..)
31+ , noRelinker
32+
33+ -- ** Operations
34+ , emptyEnv
35+ , cloneEnv
36+ , forkEnv
37+ , sizeEnv
38+ , checkSizeEnv
39+
40+ -- ** Extending and shrinking
41+ , unsafeConsEnv
42+ , unsafeTailEnv
43+
44+ -- ** Data retrieval and update
45+ , getEnv
46+ , putEnv
47+ , stateEnv
48+ , modifyEnv
49+ ) where
50+
51+import Effectful.Internal.Env
52+import Effectful.Internal.Monad
53+
54+-- | Utility for lifting 'IO' computations of type
55+--
56+-- @'IO' a -> 'IO' b@
57+--
58+-- to
59+--
60+-- @'Eff' es a -> 'Eff' es b@
61+--
62+-- This function is __unsafe__ because:
63+--
64+-- - It can be used to introduce arbitrary 'IO' actions into pure 'Eff'
65+-- computations.
66+--
67+-- - The 'IO' computation must not run its argument in a separate thread, but
68+-- it's not checked anywhere.
69+unsafeLiftMapIO :: (IO a -> IO b) -> Eff es a -> Eff es b
70+unsafeLiftMapIO f m = unsafeEff $ \es -> f (unEff m es)
71+
72+-- | Utility for running 'Eff' computations locally in the 'IO' monad.
73+--
74+-- This function is __unsafe__ because:
75+--
76+-- - It can be used to introduce arbitrary 'IO' actions into pure 'Eff'
77+-- computations.
78+--
79+-- - Unlifted 'Eff' computations must not be run in a thread distinct from the
80+-- caller of 'unsafeUnliftIO', but it's not checked anywhere.
81+unsafeUnliftIO :: ((forall r. Eff es r -> IO r) -> IO a) -> Eff es a
82+unsafeUnliftIO k = unsafeEff $ \es -> k (`unEff` es)
effectful-core/src/Effectful/Error.hsnew file+198
@@ -0,0 +1,198 @@
1+-- | Support for handling errors of a particular type, i.e. checked exceptions.
2+--
3+-- The 'Error' effect is __not__ a general mechanism for handling regular
4+-- exceptions, that's what functions from the @exceptions@ library are for (see
5+-- "Control.Monad.Catch" for more information).
6+--
7+-- In particular, regular exceptions of type @e@ are distinct from errors of
8+-- type @e@ and will __not__ be caught by functions from this module:
9+--
10+-- >>> import qualified Control.Monad.Catch as E
11+-- >>> let boom = error "BOOM!"
12+-- >>> runEff . runError @ErrorCall $ boom `catchError` \_ (_::ErrorCall) -> pure "caught"
13+-- *** Exception: BOOM!
14+-- ...
15+--
16+-- If you want to catch regular exceptions, you should use
17+-- 'Control.Monad.Catch.catch' (or a similar function):
18+--
19+-- >>> runEff $ boom `E.catch` \(_::ErrorCall) -> pure "caught"
20+-- "caught"
21+--
22+-- On the other hand, functions for safe finalization and management of
23+-- resources such as 'Control.Monad.Catch.finally' and
24+-- 'Control.Monad.Catch.bracket' work as expected:
25+--
26+-- >>> let msg = liftIO . putStrLn
27+-- >>> :{
28+-- runEff . fmap (either (Left . snd) Right) . runError @String $ do
29+-- E.bracket_ (msg "Beginning.")
30+-- (msg "Cleaning up.")
31+-- (msg "Computing." >> throwError "oops" >> msg "More.")
32+-- :}
33+-- Beginning.
34+-- Computing.
35+-- Cleaning up.
36+-- Left "oops"
37+--
38+-- /Note:/ unlike the 'Control.Monad.Trans.Except.ExceptT' monad transformer
39+-- from the @transformers@ library, the order in which you handle the 'Error'
40+-- effect with regard to other stateful effects does not matter. Consider the
41+-- following:
42+--
43+-- >>> import qualified Control.Monad.State.Strict as T
44+-- >>> import qualified Control.Monad.Except as T
45+--
46+-- >>> let m1 = (T.modify (++ " there!") >> T.throwError "oops") `T.catchError` \_ -> pure ()
47+--
48+-- >>> (`T.runStateT` "Hi") . T.runExceptT $ m1
49+-- (Right (),"Hi there!")
50+--
51+-- >>> T.runExceptT . (`T.runStateT` "Hi") $ m1
52+-- Right ((),"Hi")
53+--
54+-- Here, whether state modifications within the @catchError@ block are lost or
55+-- not depends on the shape of the monad transformer stack, which is surprising
56+-- and can be a source of subtle bugs. On the other hand:
57+--
58+-- >>> import Effectful.State.Local
59+--
60+-- >>> let m2 = (modify (++ " there!") >> throwError "oops") `catchError` \_ (_::String) -> pure ()
61+--
62+-- >>> runEff . runState "Hi" . runError @String $ m2
63+-- (Right (),"Hi there!")
64+--
65+-- >>> runEff . runError @String . runState "Hi" $ m2
66+-- Right ((),"Hi there!")
67+--
68+-- Here, no matter the order of effects, state modifications within the
69+-- @catchError@ block always persist, giving predictable behavior.
70+module Effectful.Error
71+ ( Error
72+ , runError
73+ , throwError
74+ , catchError
75+ , handleError
76+ , tryError
77+
78+ -- * Re-exports
79+ , HasCallStack
80+ , CallStack
81+ , getCallStack
82+ , prettyCallStack
83+ ) where
84+
85+import Control.Exception
86+import Data.Typeable
87+import Data.Unique
88+import GHC.Stack
89+
90+import Effectful.Dispatch.Static
91+import Effectful.Monad
92+
93+-- | Provide the ability to handle errors of type @e@.
94+newtype Error e :: Effect where
95+ Error :: ErrorId -> Error e m r
96+
97+-- | Handle errors of type @e@.
98+runError
99+ :: forall e es a. Typeable e
100+ => Eff (Error e : es) a
101+ -> Eff es (Either (CallStack, e) a)
102+runError m = unsafeEff $ \es0 -> mask $ \release -> do
103+ eid <- newErrorId
104+ size0 <- sizeEnv es0
105+ es <- unsafeConsEnv (DataA (Error @e eid)) noRelinker es0
106+ r <- tryErrorIO release eid es `onException` unsafeTailEnv size0 es
107+ unsafeTailEnv size0 es
108+ pure r
109+ where
110+ tryErrorIO release eid es = try (release $ unEff m es) >>= \case
111+ Right a -> pure $ Right a
112+ Left ex -> tryHandler ex eid (\cs e -> Left (cs, e))
113+ $ throwIO ex
114+
115+-- | Throw an error of type @e@.
116+throwError
117+ :: forall e es a. (HasCallStack, Typeable e, Error e :> es)
118+ => e
119+ -- ^ The error.
120+ -> Eff es a
121+throwError e = unsafeEff $ \es -> do
122+ DataA (Error eid) <- getEnv @(Error e) es
123+ throwIO $ ErrorEx eid callStack e
124+
125+-- | Handle an error of type @e@.
126+catchError
127+ :: forall e es a. (Typeable e, Error e :> es)
128+ => Eff es a
129+ -- ^ The inner computation.
130+ -> (CallStack -> e -> Eff es a)
131+ -- ^ A handler for errors in the inner computation.
132+ -> Eff es a
133+catchError m handler = unsafeEff $ \es -> do
134+ DataA (Error eid) <- getEnv @(Error e) es
135+ size <- sizeEnv es
136+ catchErrorIO eid (unEff m es) $ \cs e -> do
137+ checkSizeEnv size es
138+ unEff (handler cs e) es
139+
140+-- | The same as @'flip' 'catchError'@, which is useful in situations where the
141+-- code for the handler is shorter.
142+handleError
143+ :: forall e es a. (Typeable e, Error e :> es)
144+ => (CallStack -> e -> Eff es a)
145+ -- ^ A handler for errors in the inner computation.
146+ -> Eff es a
147+ -- ^ The inner computation.
148+ -> Eff es a
149+handleError = flip catchError
150+
151+-- | Similar to 'catchError', but returns an 'Either' result which is a 'Right'
152+-- if no error was thrown and a 'Left' otherwise.
153+tryError
154+ :: forall e es a. (Typeable e, Error e :> es)
155+ => Eff es a
156+ -- ^ The inner computation.
157+ -> Eff es (Either (CallStack, e) a)
158+tryError m = (Right <$> m) `catchError` \es e -> pure $ Left (es, e)
159+
160+----------------------------------------
161+-- Helpers
162+
163+newtype ErrorId = ErrorId Unique
164+ deriving Eq
165+
166+-- | A unique is picked so that distinct 'Error' handlers for the same type
167+-- don't catch each other's exceptions.
168+newErrorId :: IO ErrorId
169+newErrorId = ErrorId <$> newUnique
170+
171+tryHandler
172+ :: Typeable e
173+ => SomeException
174+ -> ErrorId
175+ -> (CallStack -> e -> r)
176+ -> IO r
177+ -> IO r
178+tryHandler ex eid0 handler next = case fromException ex of
179+ Just (ErrorEx eid cs e)
180+ | eid0 == eid -> pure $ handler cs e
181+ | otherwise -> next
182+ Nothing -> next
183+
184+data ErrorEx e = ErrorEx !ErrorId CallStack e
185+instance Typeable e => Show (ErrorEx e) where
186+ showsPrec p (ErrorEx _ cs e)
187+ = ("Effectful.Error.ErrorEx (" ++)
188+ . showsPrec p (typeOf e)
189+ . (") " ++)
190+ . showsPrec p cs
191+instance Typeable e => Exception (ErrorEx e)
192+
193+catchErrorIO :: Typeable e => ErrorId -> IO a -> (CallStack -> e -> IO a) -> IO a
194+catchErrorIO eid m handler = do
195+ m `catch` \err@(ErrorEx etag e cs) -> do
196+ if eid == etag
197+ then handler e cs
198+ else throwIO err
src/Effectful/Error/Dynamic.hs → effectful-core/src/Effectful/Error/Dynamic.hsrenamed+8−9
@@ -7,21 +7,20 @@ module Effectful.Error.Dynamic
7 ) where
7 ) where
8
8
9import Data.Typeable
9import Data.Typeable
10−import GHC.Stack
11
10
12−import Effectful.Handler
11+import Effectful.Dispatch.Dynamic
13import Effectful.Monad
12import Effectful.Monad
14import qualified Effectful.Error as E
13import qualified Effectful.Error as E
15
14
16data Error e :: Effect where
15data Error e :: Effect where
17 ThrowError :: e -> Error e m a
16 ThrowError :: e -> Error e m a
18− CatchError :: m a -> (CallStack -> e -> m a) -> Error e m a
17+ CatchError :: m a -> (E.CallStack -> e -> m a) -> Error e m a
19
18
20runError
19runError
21 :: Typeable e
20 :: Typeable e
22 => Eff (Error e : es) a
21 => Eff (Error e : es) a
23− -> Eff es (Either (CallStack, e) a)
22+ -> Eff es (Either (E.CallStack, e) a)
24−runError = reinterpretM E.runError $ \env -> \case
23+runError = reinterpret E.runError $ \env -> \case
25 ThrowError e -> E.throwError e
24 ThrowError e -> E.throwError e
26 CatchError m h -> localSeqUnlift env $ \unlift -> do
25 CatchError m h -> localSeqUnlift env $ \unlift -> do
27 E.catchError (unlift m) (\cs -> unlift . h cs)
26 E.catchError (unlift m) (\cs -> unlift . h cs)
@@ -33,14 +32,14 @@ throwError
33throwError = send . ThrowError
32throwError = send . ThrowError
34
33
35catchError
34catchError
36− :: Error e :> es
35+ :: (HasCallStack, Error e :> es)
37 => Eff es a
36 => Eff es a
38− -> (CallStack -> e -> Eff es a)
37+ -> (E.CallStack -> e -> Eff es a)
39 -> Eff es a
38 -> Eff es a
40catchError m = send . CatchError m
39catchError m = send . CatchError m
41
40
42tryError
41tryError
43− :: Error e :> es
42+ :: (HasCallStack, Error e :> es)
44 => Eff es a
43 => Eff es a
45− -> Eff es (Either (CallStack, e) a)
44+ -> Eff es (Either (E.CallStack, e) a)
46tryError m = (Right <$> m) `catchError` \es e -> pure $ Left (es, e)
45tryError m = (Right <$> m) `catchError` \es e -> pure $ Left (es, e)
effectful-core/src/Effectful/Fail.hsnew file+16
@@ -0,0 +1,16 @@
1+-- | Provider of the 'MonadFail' instance for 'Eff'.
2+module Effectful.Fail
3+ ( Fail(..)
4+ , runFail
5+ ) where
6+
7+import Effectful.Dispatch.Dynamic
8+import Effectful.Error
9+import Effectful.Internal.Monad
10+
11+-- | Run the 'Fail' effect via 'Error'.
12+runFail :: Eff (Fail : es) a -> Eff es (Either String a)
13+runFail = reinterpret eff $ \_ -> \case
14+ Fail msg -> throwError msg
15+ where
16+ eff = fmap (either (Left . snd) Right) . runError
src/Effectful/Internal/Effect.hs → effectful-core/src/Effectful/Internal/Effect.hsrenamed+10−12
@@ -8,7 +8,9 @@
8module Effectful.Internal.Effect
8module Effectful.Internal.Effect
9 ( Effect
9 ( Effect
10 , (:>)(..)
10 , (:>)(..)
11− , IdE(..)
11+
12+ -- * Re-exports
13+ , Type
12 ) where
14 ) where
13
15
14import Data.Kind
16import Data.Kind
@@ -17,20 +19,16 @@ import GHC.TypeLits
17-- | The kind of effects.
19-- | The kind of effects.
18type Effect = (Type -> Type) -> Type -> Type
20type Effect = (Type -> Type) -> Type -> Type
19
21
20−-- | Adapter for statically dispatched effects.
21−newtype IdE (e :: Effect) where
22− IdE :: (forall m r. e m r) -> IdE e
23−
24−-- | A constraint that requires that a particular effect, @e@, is a member of
22+-- | A constraint that requires that a particular effect @e@ is a member of the
25−-- the type-level list @es@. This is used to parameterize an
23+-- type-level list @es@. This is used to parameterize an 'Effectful.Monad.Eff'
26−-- 'Effectful.Monad.Eff' operation over an arbitrary list of effects, so long as
24+-- computation over an arbitrary list of effects, so long as @e@ is /somewhere/
27−-- @e@ is /somewhere/ in the list.
25+-- in the list.
28--
26--
29−-- For example, an operation that only needs access to a cell of mutable state
27+-- For example, a computation that only needs access to a mutable value of type
30−-- containing an 'Integer' would likely use the following type:
28+-- 'Integer' would likely use the following type:
31--
29--
32-- @
30-- @
33−-- 'Effectful.State.State' 'Integer' ':>' es => 'Effectful.Monad.Eff' es ()
31+-- 'Effectful.State.Local.State' 'Integer' ':>' es => 'Effectful.Monad.Eff' es ()
34-- @
32-- @
35class (e :: Effect) :> (es :: [Effect]) where
33class (e :: Effect) :> (es :: [Effect]) where
36 -- | Get the position of @e@ in @es@.
34 -- | Get the position of @e@ in @es@.
src/Effectful/Internal/Env.hs → effectful-core/src/Effectful/Internal/Env.hsrenamed+141−109
@@ -1,37 +1,50 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
1+{-# LANGUAGE MagicHash #-}
2{-# OPTIONS_HADDOCK not-home #-}
2{-# OPTIONS_HADDOCK not-home #-}
3-- | The environment for the 'Effectful.Internal.Monad.Eff' monad.
3-- | The environment for the 'Effectful.Internal.Monad.Eff' monad.
4--
4--
5-- This module is intended for internal use only, and may change without warning
5-- This module is intended for internal use only, and may change without warning
6-- in subsequent releases.
6-- in subsequent releases.
7module Effectful.Internal.Env
7module Effectful.Internal.Env
8+ ( -- * The environment
8− ( Env
9+ Env(..)
10+ , Forks(..)
11+ , EnvRef(..)
12+
13+ -- ** ForkId
14+ , ForkId(..)
15+ , ForkIdGen(..)
16+ , newForkIdGen
17+ , cloneForkIdGen
18+ , newForkId
19+
20+ -- ** Relinker
9 , Relinker(..)
21 , Relinker(..)
10 , noRelinker
22 , noRelinker
11
23
12− -- * Safe operations
24+ -- * Operations
13 , emptyEnv
25 , emptyEnv
14 , cloneEnv
26 , cloneEnv
15 , forkEnv
27 , forkEnv
16 , sizeEnv
28 , sizeEnv
17− , getEnv
18 , checkSizeEnv
29 , checkSizeEnv
19
30
20− -- * Extending and shrinking
31+ -- ** Extending and shrinking
21 , unsafeConsEnv
32 , unsafeConsEnv
22 , unsafeTailEnv
33 , unsafeTailEnv
23
34
24− -- * Data retrieval and update
35+ -- ** Data retrieval and update
25− , unsafePutEnv
36+ , getEnv
26− , unsafeModifyEnv
37+ , putEnv
27− , unsafeStateEnv
38+ , stateEnv
39+ , modifyEnv
28 ) where
40 ) where
29
41
30import Control.Monad
42import Control.Monad
31import Control.Monad.Primitive
43import Control.Monad.Primitive
32import Data.IORef
44import Data.IORef
33import Data.Primitive.SmallArray
45import Data.Primitive.SmallArray
34−import GHC.Exts (Any)
46+import GHC.Exts (Any, SmallMutableArray#)
47+import GHC.Stack (HasCallStack)
35import Unsafe.Coerce
48import Unsafe.Coerce
36import qualified Data.IntMap.Strict as IM
49import qualified Data.IntMap.Strict as IM
37
50
@@ -68,17 +81,17 @@ type role Env nominal
68-- @
81-- @
69--
82--
70-- The point of execution is currently at (*), i.e. the mainline. Moreover,
83-- The point of execution is currently at (*), i.e. the mainline. Moreover,
71−-- currently:
84+-- currently (brackets represent forks):
72--
85--
73-- - Mainline sees @[e00, e01, e05, e07]@.
86-- - Mainline sees @[e00, e01, e05, e07]@.
74--
87--
75−-- - @e01@ is an interpreted effect, its handler sees @[e00, e02, e03]@.
88+-- - @e01@ is an interpreted effect, its handler sees @[e00][e02, e03]@.
76--
89--
77−-- - @e03@ is an interpreted effect, its handler sees @[e00, e02, e04]@.
90+-- - @e03@ is an interpreted effect, its handler sees @[e00][e02][e04]@.
78--
91--
79−-- - @e05@ is an interpreted effect, its handler sees @[e00, e01, e06]@.
92+-- - @e05@ is an interpreted effect, its handler sees @[e00, e01][e06]@.
80--
93--
81−-- - @e07@ is an interpreted effect, its handler sees @[e00, e01, e05, e08,
94+-- - @e07@ is an interpreted effect, its handler sees @[e00, e01, e05][e08,
82-- e09]@.
95-- e09]@.
83--
96--
84-- If an operation from @e01@ is invoked, the environment in the middle of
97-- If an operation from @e01@ is invoked, the environment in the middle of
@@ -101,30 +114,32 @@ type role Env nominal
101-- introduced @e12@), so its local environment was temporarily extended with
114-- introduced @e12@), so its local environment was temporarily extended with
102-- it. Moreover, currently:
115-- it. Moreover, currently:
103--
116--
104−-- - Handler of @e01@ sees @[e00, e02, e03, e10]@.
117+-- - Handler of @e01@ sees @[e00][e02, e03, e10]@.
105--
118--
106−-- - Handler of @e10@ sees @[e00, e02, e03, e11]@.
119+-- - Handler of @e10@ sees @[e00][e02, e03][e11]@.
107--
120--
108−-- - Handler of @e11@ sees @[e00, e02, e03, e12]@.
121+-- - Handler of @e11@ sees @[e00][e02, e03][e12]@.
109--
122--
110data Env (es :: [Effect]) = Env
123data Env (es :: [Effect]) = Env
111− { _forks :: Forks
124+ { _forks :: !Forks
112− , _globalRef :: IORef EnvRef
125+ , _globalRef :: !(IORef EnvRef)
113− , _forkIdGen :: ForkIdGen
126+ , _forkIdGen :: !ForkIdGen
114 }
127 }
115
128
116-- | Local forks of the environment.
129-- | Local forks of the environment.
117−data Forks = Forks ForkId Int (IORef EnvRef) Forks | NoFork
130+data Forks = Forks !ForkId !Int !(IORef EnvRef) Forks | NoFork
118
131
132+-- | Data held in the environment.
119data EnvRef = EnvRef
133data EnvRef = EnvRef
120− { _size :: Int
134+ { _size :: !Int
121− , _data :: SmallMutableArray RealWorld Any
135+ , _data :: !(SmallMutableArray RealWorld Any)
122− , _relinkers :: SmallMutableArray RealWorld Any
136+ , _relinkers :: !(SmallMutableArray RealWorld Any)
123 }
137 }
124
138
125----------------------------------------
139----------------------------------------
126-- ForkId
140-- ForkId
127
141
142+-- | Internal id of the fork.
128newtype ForkId = ForkId { unForkId :: Int }
143newtype ForkId = ForkId { unForkId :: Int }
129
144
130-- | 'ForkId' generation.
145-- | 'ForkId' generation.
@@ -148,12 +163,15 @@ newForkId (ForkIdGen ref) = do
148----------------------------------------
163----------------------------------------
149-- Relinker
164-- Relinker
150
165
166+-- | A function for relinking 'Env' objects stored in the handlers when cloning
167+-- the environment.
151−newtype Relinker i (e :: Effect) where
168+newtype Relinker :: (Effect -> Type) -> Effect -> Type where
152 Relinker
169 Relinker
153− :: ((forall es. Env es -> IO (Env es)) -> handler e -> IO (handler e))
170+ :: ((forall es. Env es -> IO (Env es)) -> adapter e -> IO (adapter e))
154− -> Relinker handler e
171+ -> Relinker adapter e
155
172
173+-- | A dummy 'Relinker' that does nothing.
156−noRelinker :: Relinker handler e
174+noRelinker :: Relinker adapter e
157noRelinker = Relinker $ \_ -> pure
175noRelinker = Relinker $ \_ -> pure
158
176
159----------------------------------------
177----------------------------------------
@@ -171,22 +189,22 @@ cloneEnv (Env NoFork gref0 gen0) = do
171 fs <- cloneSmallMutableArray fs0 0 (sizeofSmallMutableArray fs0)
189 fs <- cloneSmallMutableArray fs0 0 (sizeofSmallMutableArray fs0)
172 gen <- cloneForkIdGen gen0
190 gen <- cloneForkIdGen gen0
173 gref <- newIORef $ EnvRef n es fs
191 gref <- newIORef $ EnvRef n es fs
174− cache <- newIORef IM.empty
192+ store <- newIORef IM.empty
175− relinkData gref gen cache es fs n
193+ relinkData gref gen store es fs n
176 pure $ Env NoFork gref gen
194 pure $ Env NoFork gref gen
177cloneEnv (Env forks@(Forks _ baseIx lref0 _) gref0 gen0) = do
195cloneEnv (Env forks@(Forks _ baseIx lref0 _) gref0 gen0) = do
178 EnvRef _ es0 fs0 <- readIORef gref0
196 EnvRef _ es0 fs0 <- readIORef gref0
179 EnvRef n _ _ <- readIORef lref0
197 EnvRef n _ _ <- readIORef lref0
180 let len = baseIx + n
198 let len = baseIx + n
181− es <- newSmallArray len (error "undefined field")
199+ es <- newSmallArray len undefinedData
182− fs <- newSmallArray len (error "undefined field")
200+ fs <- newSmallArray len undefinedData
183 baseN <- copyForks es fs len forks
201 baseN <- copyForks es fs len forks
184 copySmallMutableArray es 0 es0 0 baseN
202 copySmallMutableArray es 0 es0 0 baseN
185 copySmallMutableArray fs 0 fs0 0 baseN
203 copySmallMutableArray fs 0 fs0 0 baseN
186 gen <- cloneForkIdGen gen0
204 gen <- cloneForkIdGen gen0
187 gref <- newIORef $ EnvRef len es fs
205 gref <- newIORef $ EnvRef len es fs
188− cache <- newIORef IM.empty
206+ store <- newIORef IM.empty
189− relinkData gref gen cache es fs n
207+ relinkData gref gen store es fs n
190 -- The forked environment is flattened and becomes the global one.
208 -- The forked environment is flattened and becomes the global one.
191 pure $ Env NoFork gref gen
209 pure $ Env NoFork gref gen
192{-# NOINLINE cloneEnv #-}
210{-# NOINLINE cloneEnv #-}
@@ -236,18 +254,18 @@ copyForks es fs len = \case
236 copySmallMutableArray fs baseIx fs0 0 n
254 copySmallMutableArray fs baseIx fs0 0 n
237 copyForks es fs baseIx forks
255 copyForks es fs baseIx forks
238
256
239−type EnvRefCache = IORef (IM.IntMap (IORef EnvRef))
257+type EnvRefStore = IORef (IM.IntMap (IORef EnvRef))
240
258
241-- | Relink local environments hiding in the handlers.
259-- | Relink local environments hiding in the handlers.
242relinkData
260relinkData
243 :: IORef EnvRef
261 :: IORef EnvRef
244 -> ForkIdGen
262 -> ForkIdGen
245− -> EnvRefCache
263+ -> EnvRefStore
246 -> SmallMutableArray RealWorld Any
264 -> SmallMutableArray RealWorld Any
247 -> SmallMutableArray RealWorld Any
265 -> SmallMutableArray RealWorld Any
248 -> Int
266 -> Int
249 -> IO ()
267 -> IO ()
250−relinkData gref gen cache es fs = \case
268+relinkData gref gen store es fs = \case
251 0 -> pure ()
269 0 -> pure ()
252 n -> do
270 n -> do
253 let i = n - 1
271 let i = n - 1
@@ -255,41 +273,41 @@ relinkData gref gen cache es fs = \case
255 readSmallArray es i
273 readSmallArray es i
256 >>= f relinkEnv . fromAny
274 >>= f relinkEnv . fromAny
257 >>= writeSmallArray es i . toAny
275 >>= writeSmallArray es i . toAny
258− relinkData gref gen cache es fs i
276+ relinkData gref gen store es fs i
259 where
277 where
260 relinkEnv :: Env es -> IO (Env es)
278 relinkEnv :: Env es -> IO (Env es)
261− relinkEnv (Env forks _ _) = Env <$> relinkForks gref gen cache forks
279+ relinkEnv (Env forks _ _) = Env <$> relinkForks gref gen store forks
262 <*> pure gref
280 <*> pure gref
263 <*> pure gen
281 <*> pure gen
264
282
265−relinkForks :: IORef EnvRef -> ForkIdGen -> EnvRefCache -> Forks -> IO Forks
283+relinkForks :: IORef EnvRef -> ForkIdGen -> EnvRefStore -> Forks -> IO Forks
266−relinkForks gref gen cache = \case
284+relinkForks gref gen store = \case
267 NoFork -> pure NoFork
285 NoFork -> pure NoFork
268 Forks fid baseIx lref0 forks -> do
286 Forks fid baseIx lref0 forks -> do
269 -- A specific IORef EnvRef can be held by more than one local environment
287 -- A specific IORef EnvRef can be held by more than one local environment
270 -- and we need to replace all its occurences with the same, new value
288 -- and we need to replace all its occurences with the same, new value
271 -- containing its clone.
289 -- containing its clone.
272− readIORef cache >>= pure . IM.lookup (unForkId fid) >>= \case
290+ readIORef store >>= pure . IM.lookup (unForkId fid) >>= \case
273 Just lref -> Forks fid baseIx <$> pure lref
291 Just lref -> Forks fid baseIx <$> pure lref
274− <*> relinkForks gref gen cache forks
292+ <*> relinkForks gref gen store forks
275− Nothing -> Forks fid baseIx <$> cloneEnvRef gref gen cache fid lref0
293+ Nothing -> Forks fid baseIx <$> cloneEnvRef gref gen store fid lref0
276− <*> relinkForks gref gen cache forks
294+ <*> relinkForks gref gen store forks
277
295
278−-- | Clone the local 'EnvRef' and put it in a cache.
296+-- | Clone the local 'EnvRef' and put it in a store.
279cloneEnvRef
297cloneEnvRef
280 :: IORef EnvRef
298 :: IORef EnvRef
281 -> ForkIdGen
299 -> ForkIdGen
282− -> EnvRefCache
300+ -> EnvRefStore
283 -> ForkId
301 -> ForkId
284 -> IORef EnvRef
302 -> IORef EnvRef
285 -> IO (IORef EnvRef)
303 -> IO (IORef EnvRef)
286−cloneEnvRef gref gen cache fid lref0 = do
304+cloneEnvRef gref gen store fid lref0 = do
287 EnvRef n es0 fs0 <- readIORef lref0
305 EnvRef n es0 fs0 <- readIORef lref0
288 es <- cloneSmallMutableArray es0 0 (sizeofSmallMutableArray es0)
306 es <- cloneSmallMutableArray es0 0 (sizeofSmallMutableArray es0)
289 fs <- cloneSmallMutableArray fs0 0 (sizeofSmallMutableArray fs0)
307 fs <- cloneSmallMutableArray fs0 0 (sizeofSmallMutableArray fs0)
290 ref <- newIORef $ EnvRef n es fs
308 ref <- newIORef $ EnvRef n es fs
291− modifyIORef' cache $ IM.insert (unForkId fid) ref
309+ modifyIORef' store $ IM.insert (unForkId fid) ref
292− relinkData gref gen cache es fs n
310+ relinkData gref gen store es fs n
293 pure ref
311 pure ref
294
312
295----------------------------------------
313----------------------------------------
@@ -320,12 +338,6 @@ sizeEnv (Env (Forks _ baseIx lref _) _ _) = do
320 pure $ baseIx + n
338 pure $ baseIx + n
321{-# NOINLINE sizeEnv #-}
339{-# NOINLINE sizeEnv #-}
322
340
323−-- | Extract a specific data type from the environment.
324−getEnv :: forall e es handler. e :> es => Env es -> IO (handler e)
325−getEnv env = do
326− (i, es) <- getLocation @e env
327− fromAny <$> readSmallArray es i
328−
329-- | Check that the size of the environment is the same as the expected value.
341-- | Check that the size of the environment is the same as the expected value.
330checkSizeEnv :: Int -> Env es -> IO ()
342checkSizeEnv :: Int -> Env es -> IO ()
331checkSizeEnv k (Env NoFork ref _) = do
343checkSizeEnv k (Env NoFork ref _) = do
@@ -343,7 +355,11 @@ checkSizeEnv k (Env (Forks _ baseIx lref _) _ _) = do
343-- Extending and shrinking
355-- Extending and shrinking
344
356
345-- | Extend the environment with a new data type (in place).
357-- | Extend the environment with a new data type (in place).
358+--
359+-- This function is __highly unsafe__ because it renders the input 'Env'
360+-- unusable until the corresponding 'unsafeTailEnv' call is made, but it's not
361+-- checked anywhere.
346−unsafeConsEnv :: handler e -> Relinker handler e -> Env es -> IO (Env (e : es))
362+unsafeConsEnv :: adapter e -> Relinker adapter e -> Env es -> IO (Env (e : es))
347unsafeConsEnv e f (Env fork gref gen) = case fork of
363unsafeConsEnv e f (Env fork gref gen) = case fork of
348 NoFork -> do
364 NoFork -> do
349 extendEnvRef gref
365 extendEnvRef gref
@@ -364,10 +380,10 @@ unsafeConsEnv e f (Env fork gref gen) = case fork of
364 writeIORef ref $! EnvRef (n + 1) es0 fs0
380 writeIORef ref $! EnvRef (n + 1) es0 fs0
365 EQ -> do
381 EQ -> do
366 let len = doubleCapacity len0
382 let len = doubleCapacity len0
367− es <- newSmallArray len (error "undefined field")
383+ es <- newSmallArray len undefinedData
368 copySmallMutableArray es 0 es0 0 len0
384 copySmallMutableArray es 0 es0 0 len0
369 e `seq` writeSmallArray es n (toAny e)
385 e `seq` writeSmallArray es n (toAny e)
370− fs <- newSmallArray len (error "undefined field")
386+ fs <- newSmallArray len undefinedData
371 copySmallMutableArray fs 0 fs0 0 len0
387 copySmallMutableArray fs 0 fs0 0 len0
372 f `seq` writeSmallArray fs n (toAny f)
388 f `seq` writeSmallArray fs n (toAny f)
373 writeIORef ref $! EnvRef (n + 1) es fs
389 writeIORef ref $! EnvRef (n + 1) es fs
@@ -378,14 +394,13 @@ unsafeConsEnv e f (Env fork gref gen) = case fork of
378
394
379-- | Shrink the environment by one data type (in place). Makes sure the size of
395-- | Shrink the environment by one data type (in place). Makes sure the size of
380-- the environment is as expected.
396-- the environment is as expected.
397+--
398+-- This function is __highly unsafe__ because it renders the input 'Env'
399+-- unusable, but it's not checked anywhere.
381−unsafeTailEnv :: Int -> Env (e : es) -> IO (Env es)
400+unsafeTailEnv :: Int -> Env (e : es) -> IO ()
382−unsafeTailEnv len (Env fork gref gen) = case fork of
401+unsafeTailEnv len (Env fork gref _) = case fork of
383− NoFork -> do
384− shrinkEnvRef len gref
402+ NoFork -> shrinkEnvRef len gref
385− pure $ Env NoFork gref gen
386− Forks _ baseIx lref _ -> do
387− shrinkEnvRef (len - baseIx) lref
403+ Forks _ baseIx lref _ -> shrinkEnvRef (len - baseIx) lref
388− pure $ Env fork gref gen
389 where
404 where
390 shrinkEnvRef :: Int -> IORef EnvRef -> IO ()
405 shrinkEnvRef :: Int -> IORef EnvRef -> IO ()
391 shrinkEnvRef k ref = do
406 shrinkEnvRef k ref = do
@@ -393,62 +408,79 @@ unsafeTailEnv len (Env fork gref gen) = case fork of
393 if k /= n - 1
408 if k /= n - 1
394 then error $ "k (" ++ show k ++ ") /= n - 1 (" ++ show (n - 1) ++ ")"
409 then error $ "k (" ++ show k ++ ") /= n - 1 (" ++ show (n - 1) ++ ")"
395 else do
410 else do
396− writeSmallArray es k (error "undefined field")
411+ writeSmallArray es k undefinedData
397− writeSmallArray fs k (error "undefined field")
412+ writeSmallArray fs k undefinedData
398 writeIORef ref $! EnvRef k es fs
413 writeIORef ref $! EnvRef k es fs
399{-# NOINLINE unsafeTailEnv #-}
414{-# NOINLINE unsafeTailEnv #-}
400
415
401----------------------------------------
416----------------------------------------
402-- Data retrieval and update
417-- Data retrieval and update
403
418
404−-- | Replace the data type in the environment with a new value (in place).
419+-- | Extract a specific data type from the environment.
405−unsafePutEnv
420+getEnv
406− :: forall e es handler. e :> es
421+ :: forall e adapter es. e :> es
407− => handler e
408− -> Env es -> IO ()
422+ => Env es
409−unsafePutEnv e env = do
423+ -> IO (adapter e)
424+getEnv env = do
410− (i, es) <- getLocation @e env
425+ Location i es <- getLocation (reifyIndex @e @es) env
411− e `seq` writeSmallArray es i (toAny e)
426+ fromAny <$> readSmallArray es i
412
427
413−-- | Modify the data type in the environment (in place).
428+-- | Replace the data type in the environment with a new value (in place).
414−unsafeModifyEnv
429+putEnv
415− :: forall e es handler. e :> es
430+ :: forall e adapter es. e :> es
416− => (handler e -> handler e)
417− -> Env es
431+ => Env es
432+ -> adapter e
418 -> IO ()
433 -> IO ()
419−unsafeModifyEnv f env = do
434+putEnv env e = do
420− (i, es) <- getLocation @e env
435+ Location i es <- getLocation (reifyIndex @e @es) env
421− e <- f . fromAny <$> readSmallArray es i
422 e `seq` writeSmallArray es i (toAny e)
436 e `seq` writeSmallArray es i (toAny e)
423
437
424-- | Modify the data type in the environment (in place) and return a value.
438-- | Modify the data type in the environment (in place) and return a value.
425−unsafeStateEnv
439+stateEnv
426− :: forall e es handler a. e :> es
440+ :: forall e adapter es a. e :> es
427− => (handler e -> (a, handler e))
441+ => Env es
428− -> Env es
442+ -> (adapter e -> (a, adapter e))
429 -> IO a
443 -> IO a
430−unsafeStateEnv f env = do
444+stateEnv env f = do
431− (i, es) <- getLocation @e env
445+ Location i es <- getLocation (reifyIndex @e @es) env
432 (a, e) <- f . fromAny <$> readSmallArray es i
446 (a, e) <- f . fromAny <$> readSmallArray es i
433 e `seq` writeSmallArray es i (toAny e)
447 e `seq` writeSmallArray es i (toAny e)
434 pure a
448 pure a
435
449
450+-- | Modify the data type in the environment (in place).
451+modifyEnv
452+ :: forall e adapter es. e :> es
453+ => Env es
454+ -> (adapter e -> adapter e)
455+ -> IO ()
456+modifyEnv env f = do
457+ Location i es <- getLocation (reifyIndex @e @es) env
458+ e <- f . fromAny <$> readSmallArray es i
459+ e `seq` writeSmallArray es i (toAny e)
460+
436----------------------------------------
461----------------------------------------
437-- Internal helpers
462-- Internal helpers
438
463
464+undefinedData :: HasCallStack => a
465+undefinedData = error "undefined data"
466+
439emptyEnvRef :: IO (IORef EnvRef)
467emptyEnvRef :: IO (IORef EnvRef)
440emptyEnvRef = do
468emptyEnvRef = do
441− es <- newSmallArray 0 (error "undefined field")
469+ es <- newSmallArray 0 undefinedData
442− fs <- newSmallArray 0 (error "undefined field")
470+ fs <- newSmallArray 0 undefinedData
443 newIORef $ EnvRef 0 es fs
471 newIORef $ EnvRef 0 es fs
444
472
473+-- | Location with unboxed fields to make GHC generate Core without unnecessary
474+-- reboxing around the local 'go' function from 'getLocation'.
475+data Location = Location !Int !(SmallMutableArray RealWorld Any)
476+
445-- | Determine location of the data type in the environment.
477-- | Determine location of the data type in the environment.
446getLocation
478getLocation
447− :: forall e es. e :> es
479+ :: Int
448− => Env es
480+ -> Env es
449− -> IO (Int, SmallMutableArray RealWorld Any)
481+ -> IO Location
450−getLocation (Env fork ref _) = do
482+getLocation ixE (Env fork ref _) = do
451− EnvRef n es _ <- readIORef ref
483+ EnvRef n es@(SmallMutableArray es#) _ <- readIORef ref
452 -- Optimized for the common access pattern:
484 -- Optimized for the common access pattern:
453 --
485 --
454 -- - Most application code has no access to forks, in which case we look at
486 -- - Most application code has no access to forks, in which case we look at
@@ -457,28 +489,28 @@ getLocation (Env fork ref _) = do
457 -- - Effect handlers will most likely access the newest fork with handler
489 -- - Effect handlers will most likely access the newest fork with handler
458 -- specific effects for reinterpretation.
490 -- specific effects for reinterpretation.
459 case fork of
491 case fork of
460− NoFork -> pure (ix n, es)
492+ NoFork -> pure $ Location (ix n) es
461 Forks _ baseIx lref forks -> do
493 Forks _ baseIx lref forks -> do
462 EnvRef ln les _ <- readIORef lref
494 EnvRef ln les _ <- readIORef lref
463 let i = ix (baseIx + ln)
495 let i = ix (baseIx + ln)
464 if i >= baseIx
496 if i >= baseIx
465− then pure (i - baseIx, les)
497+ then pure $ Location (i - baseIx) les
466− else go es i forks
498+ else go es# i forks
467 where
499 where
468− go :: SmallMutableArray RealWorld Any
500+ go :: SmallMutableArray# RealWorld Any
469 -> Int
501 -> Int
470 -> Forks
502 -> Forks
471− -> IO (Int, SmallMutableArray RealWorld Any)
503+ -> IO Location
472− go es i = \case
504+ go es# i = \case
473− NoFork -> pure (i, es)
505+ NoFork -> pure $ Location i (SmallMutableArray es#)
474 Forks _ baseIx lref forks -> do
506 Forks _ baseIx lref forks -> do
475 EnvRef _ les _ <- readIORef lref
507 EnvRef _ les _ <- readIORef lref
476 if i >= baseIx
508 if i >= baseIx
477− then pure (i - baseIx, les)
509+ then pure $ Location (i - baseIx) les
478− else go es i forks
510+ else go es# i forks
479
511
480 ix :: Int -> Int
512 ix :: Int -> Int
481− ix n = n - reifyIndex @e @es - 1
513+ ix n = n - ixE - 1
482
514
483toAny :: a -> Any
515toAny :: a -> Any
484toAny = unsafeCoerce
516toAny = unsafeCoerce
effectful-core/src/Effectful/Internal/Monad.hsnew file+415
@@ -0,0 +1,415 @@
1+{-# LANGUAGE UndecidableInstances #-}
2+{-# OPTIONS_GHC -Wno-noncanonical-monad-instances #-}
3+{-# OPTIONS_HADDOCK not-home #-}
4+-- | The 'Eff' monad.
5+--
6+-- This module is intended for internal use only, and may change without warning
7+-- in subsequent releases.
8+module Effectful.Internal.Monad
9+ ( -- * The 'Eff' monad
10+ Eff
11+ , runPureEff
12+
13+ -- ** Access to the internal representation
14+ , unEff
15+ , unsafeEff
16+ , unsafeEff_
17+
18+ -- * Fail
19+ , Fail(..)
20+
21+ -- * IO
22+ , IOE
23+ , runEff
24+
25+ -- * Prim
26+ , Prim
27+ , runPrim
28+
29+ -- * Unlift strategies
30+ , UnliftStrategy(..)
31+ , Persistence(..)
32+ , Limit(..)
33+ , unliftStrategy
34+ , withUnliftStrategy
35+ , withEffToIO
36+
37+ -- ** Low-level unlifts
38+ , seqUnliftIO
39+ , concUnliftIO
40+
41+ -- * Effects
42+
43+ -- ** Dynamic dispatch
44+ , EffectHandler
45+ , LocalEnv(..)
46+ , HandlerA(..)
47+ , runHandler
48+ , send
49+
50+ -- ** Static dispatch
51+ , DataA(..)
52+ , runData
53+ , evalData
54+ , execData
55+ , getData
56+ , putData
57+ , stateData
58+ , stateDataM
59+ , localData
60+ ) where
61+
62+import Control.Applicative (liftA2)
63+import Control.Monad.Base
64+import Control.Monad.Fix
65+import Control.Monad.IO.Class
66+import Control.Monad.IO.Unlift
67+import Control.Monad.Primitive
68+import Control.Monad.Trans.Control
69+import GHC.Exts (oneShot)
70+import GHC.IO (IO(..))
71+import GHC.Stack (HasCallStack)
72+import System.IO.Unsafe (unsafeDupablePerformIO)
73+import qualified Control.Exception as E
74+import qualified Control.Monad.Catch as C
75+
76+import Effectful.Internal.Effect
77+import Effectful.Internal.Env
78+import Effectful.Internal.Unlift
79+
80+type role Eff nominal representational
81+
82+-- | The 'Eff' monad provides the implementation of a computation that performs
83+-- an arbitrary set of effects. In @'Eff' es a@, @es@ is a type-level list that
84+-- contains all the effects that the computation may perform. For example, a
85+-- computation that produces an 'Integer' by consuming a 'String' from the
86+-- global environment and acting upon a single mutable value of type 'Bool'
87+-- would have the following type:
88+--
89+-- @
90+-- 'Eff' '['Effectful.Reader.Reader' 'String', 'Effectful.State.Local.State' 'Bool'] 'Integer'
91+-- @
92+--
93+-- Normally, a concrete list of effects is not used to parameterize 'Eff'.
94+-- Instead, the '(:>)' type class is used to express constraints on the list of
95+-- effects without coupling a computation to a concrete list of effects. For
96+-- example, the above example would be expressed with the following type:
97+--
98+-- @
99+-- ('Effectful.Reader.Reader' 'String' ':>' es, 'Effectful.State.Local.State' 'Bool' ':>' es) => 'Eff' es 'Integer'
100+-- @
101+--
102+-- This abstraction allows the computation to be used in functions that may
103+-- perform other effects, and it also allows the effects to be handled in any
104+-- order.
105+newtype Eff (es :: [Effect]) a = Eff (Env es -> IO a)
106+ deriving (Monoid, Semigroup)
107+
108+-- | Run a pure 'Eff' computation.
109+--
110+-- For running computations with side effects see 'runEff'.
111+runPureEff :: Eff '[] a -> a
112+runPureEff (Eff m) =
113+ -- unsafeDupablePerformIO is safe here since IOE was not on the stack, so no
114+ -- IO with side effects was performed (unless someone sneakily introduced side
115+ -- effects with unsafeEff, but then all bets are off).
116+ --
117+ -- Moreover, internals don't allocate any resources that require explicit
118+ -- cleanup actions to run.
119+ unsafeDupablePerformIO $ m =<< emptyEnv
120+
121+----------------------------------------
122+-- Access to the internal representation
123+
124+-- | Peel off the constructor of 'Eff'.
125+unEff :: Eff es a -> Env es -> IO a
126+unEff (Eff m) = m
127+
128+-- | Access the underlying 'IO' monad along with the environment.
129+--
130+-- This function is __unsafe__ because it can be used to introduce arbitrary
131+-- 'IO' actions into pure 'Eff' computations.
132+unsafeEff :: (Env es -> IO a) -> Eff es a
133+unsafeEff m = Eff (oneShot m)
134+
135+-- | Access the underlying 'IO' monad.
136+--
137+-- This function is __unsafe__ because it can be used to introduce arbitrary
138+-- 'IO' actions into pure 'Eff' computations.
139+unsafeEff_ :: IO a -> Eff es a
140+unsafeEff_ m = unsafeEff $ \_ -> m
141+
142+----------------------------------------
143+-- Unlifting IO
144+
145+-- | Get the current 'UnliftStrategy'.
146+unliftStrategy :: IOE :> es => Eff es UnliftStrategy
147+unliftStrategy = do
148+ DataA (IOE unlift) <- getData
149+ pure unlift
150+
151+-- | Locally override the 'UnliftStrategy' with the given value.
152+withUnliftStrategy :: IOE :> es => UnliftStrategy -> Eff es a -> Eff es a
153+withUnliftStrategy unlift = localData $ \_ -> DataA (IOE unlift)
154+
155+-- | Create an unlifting function with the current 'UnliftStrategy'.
156+--
157+-- This function is equivalent to 'withRunInIO', but has a 'HasCallStack'
158+-- constraint for accurate stack traces in case an insufficiently powerful
159+-- 'UnliftStrategy' is used and the unlifting function fails.
160+--
161+-- /Note:/ the strategy is reset to 'SeqUnlift' inside the continuation.
162+withEffToIO
163+ :: (HasCallStack, IOE :> es)
164+ => ((forall r. Eff es r -> IO r) -> IO a)
165+ -- ^ Continuation with the unlifting function in scope.
166+ -> Eff es a
167+withEffToIO f = unliftStrategy >>= \case
168+ SeqUnlift -> unsafeEff $ \es -> seqUnliftIO es f
169+ ConcUnlift p b -> withUnliftStrategy SeqUnlift $ do
170+ unsafeEff $ \es -> concUnliftIO es p b f
171+
172+-- | Create an unlifting function with the 'SeqUnlift' strategy.
173+seqUnliftIO
174+ :: HasCallStack
175+ => Env es
176+ -- ^ The environment.
177+ -> ((forall r. Eff es r -> IO r) -> IO a)
178+ -- ^ Continuation with the unlifting function in scope.
179+ -> IO a
180+seqUnliftIO es k = seqUnlift k es unEff
181+
182+-- | Create an unlifting function with the 'ConcUnlift' strategy.
183+concUnliftIO
184+ :: HasCallStack
185+ => Env es
186+ -- ^ The environment.
187+ -> Persistence
188+ -> Limit
189+ -> ((forall r. Eff es r -> IO r) -> IO a)
190+ -- ^ Continuation with the unlifting function in scope.
191+ -> IO a
192+concUnliftIO es persistence limit k = concUnlift persistence limit k es unEff
193+
194+----------------------------------------
195+-- Base
196+
197+instance Functor (Eff es) where
198+ fmap f (Eff m) = unsafeEff $ \es -> f <$> m es
199+ a <$ Eff fb = unsafeEff $ \es -> a <$ fb es
200+
201+instance Applicative (Eff es) where
202+ pure = unsafeEff_ . pure
203+ Eff mf <*> Eff mx = unsafeEff $ \es -> mf es <*> mx es
204+ Eff ma *> Eff mb = unsafeEff $ \es -> ma es *> mb es
205+ Eff ma <* Eff mb = unsafeEff $ \es -> ma es <* mb es
206+ liftA2 f (Eff ma) (Eff mb) = unsafeEff $ \es -> liftA2 f (ma es) (mb es)
207+
208+instance Monad (Eff es) where
209+ return = unsafeEff_ . pure
210+ Eff m >>= k = unsafeEff $ \es -> m es >>= \a -> unEff (k a) es
211+ -- https://gitlab.haskell.org/ghc/ghc/-/issues/20008
212+ Eff ma >> Eff mb = unsafeEff $ \es -> ma es >> mb es
213+
214+instance MonadFix (Eff es) where
215+ mfix f = unsafeEff $ \es -> mfix $ \a -> unEff (f a) es
216+
217+----------------------------------------
218+-- Exception
219+
220+instance C.MonadThrow (Eff es) where
221+ throwM = unsafeEff_ . E.throwIO
222+
223+instance C.MonadCatch (Eff es) where
224+ catch m handler = unsafeEff $ \es -> do
225+ size <- sizeEnv es
226+ unEff m es `E.catch` \e -> do
227+ checkSizeEnv size es
228+ unEff (handler e) es
229+
230+instance C.MonadMask (Eff es) where
231+ mask k = unsafeEff $ \es -> E.mask $ \restore ->
232+ unEff (k $ \m -> unsafeEff $ restore . unEff m) es
233+
234+ uninterruptibleMask k = unsafeEff $ \es -> E.uninterruptibleMask $ \restore ->
235+ unEff (k $ \m -> unsafeEff $ restore . unEff m) es
236+
237+ generalBracket acquire release use = unsafeEff $ \es -> E.mask $ \restore -> do
238+ size <- sizeEnv es
239+ resource <- unEff acquire es
240+ b <- restore (unEff (use resource) es) `E.catch` \e -> do
241+ checkSizeEnv size es
242+ _ <- unEff (release resource $ C.ExitCaseException e) es
243+ E.throwIO e
244+ checkSizeEnv size es
245+ c <- unEff (release resource $ C.ExitCaseSuccess b) es
246+ pure (b, c)
247+
248+----------------------------------------
249+-- Fail
250+
251+-- | Provide the ability to use the 'MonadFail' instance of 'Eff'.
252+data Fail :: Effect where
253+ Fail :: String -> Fail m a
254+
255+instance Fail :> es => MonadFail (Eff es) where
256+ fail = send . Fail
257+
258+----------------------------------------
259+-- IO
260+
261+-- | Run arbitrary 'IO' computations via 'MonadIO' or 'MonadUnliftIO'.
262+newtype IOE :: Effect where
263+ IOE :: UnliftStrategy -> IOE m r
264+
265+-- | Run an 'Eff' computation with side effects.
266+--
267+-- For running pure computations see 'runPureEff'.
268+runEff :: Eff '[IOE] a -> IO a
269+runEff m = unEff (evalData (DataA (IOE SeqUnlift)) m) =<< emptyEnv
270+
271+instance IOE :> es => MonadIO (Eff es) where
272+ liftIO = unsafeEff_
273+
274+-- | Use 'withEffToIO' if you want accurate stack traces on errors.
275+instance IOE :> es => MonadUnliftIO (Eff es) where
276+ withRunInIO = withEffToIO
277+
278+-- | Instance included for compatibility with existing code, usage of 'liftIO'
279+-- is preferrable.
280+instance IOE :> es => MonadBase IO (Eff es) where
281+ liftBase = unsafeEff_
282+
283+-- | Instance included for compatibility with existing code, usage of
284+-- 'withRunInIO' is preferrable.
285+instance IOE :> es => MonadBaseControl IO (Eff es) where
286+ type StM (Eff es) a = a
287+ liftBaseWith = withEffToIO
288+ restoreM = pure
289+
290+----------------------------------------
291+-- Primitive
292+
293+-- | Provide the ability to perform primitive state-transformer actions.
294+data Prim :: Effect where
295+ Prim :: Prim m r
296+
297+-- | Run an 'Eff' computation with primitive state-transformer actions.
298+runPrim :: IOE :> es => Eff (Prim : es) a -> Eff es a
299+runPrim = evalData (DataA Prim)
300+
301+instance Prim :> es => PrimMonad (Eff es) where
302+ type PrimState (Eff es) = RealWorld
303+ primitive = unsafeEff_ . IO
304+
305+----------------------------------------
306+-- Dynamic dispatch
307+
308+type role LocalEnv nominal nominal
309+
310+-- | Opaque representation of the 'Eff' environment at the point of calling the
311+-- 'send' function, i.e. right before the control is passed to the effect
312+-- handler.
313+--
314+-- The second type variable represents effects of a handler and is needed for
315+-- technical reasons to guarantee soundness.
316+newtype LocalEnv (localEs :: [Effect]) (handlerEs :: [Effect]) = LocalEnv (Env localEs)
317+
318+-- | Type signature of the effect handler.
319+type EffectHandler e es
320+ = forall a localEs. HasCallStack
321+ => LocalEnv localEs es
322+ -- ^ Capture of the local environment for handling local 'Eff' computations
323+ -- when @e@ is a higher order effect.
324+ -> e (Eff localEs) a
325+ -- ^ The effect performed in the local environment.
326+ -> Eff es a
327+
328+-- | An adapter for dynamically dispatched effects.
329+--
330+-- Represents the effect handler bundled with its environment.
331+data HandlerA :: Effect -> Type where
332+ HandlerA :: !(Env es) -> !(EffectHandler e es) -> HandlerA e
333+
334+-- | Run a dynamically dispatched effect with the given handler.
335+runHandler :: HandlerA e -> Eff (e : es) a -> Eff es a
336+runHandler e m = unsafeEff $ \es0 -> do
337+ size0 <- sizeEnv es0
338+ E.bracket (unsafeConsEnv e relinker es0)
339+ (unsafeTailEnv size0)
340+ (\es -> unEff m es)
341+ where
342+ relinker :: Relinker HandlerA e
343+ relinker = Relinker $ \relink (HandlerA handlerEs handle) -> do
344+ newHandlerEs <- relink handlerEs
345+ pure $ HandlerA newHandlerEs handle
346+
347+-- | Send an operation of the given effect to its handler for execution.
348+send :: (HasCallStack, e :> es) => e (Eff es) a -> Eff es a
349+send op = unsafeEff $ \es -> do
350+ HandlerA handlerEs handle <- getEnv es
351+ unEff (handle (LocalEnv es) op) handlerEs
352+
353+----------------------------------------
354+-- Static dispatch
355+
356+-- | An adapter for statically dispatched effects.
357+--
358+-- Represents an arbitrary data type with the appropriate number of phantom type
359+-- parameters.
360+newtype DataA :: Effect -> Type where
361+ DataA :: (forall m r. e m r) -> DataA e
362+
363+-- | Run a statically dispatched effect with the given initial state and return
364+-- the final value along with the final state.
365+runData :: DataA e -> Eff (e : es) a -> Eff es (a, DataA e)
366+runData e0 m = unsafeEff $ \es0 -> do
367+ size0 <- sizeEnv es0
368+ E.bracket (unsafeConsEnv e0 noRelinker es0)
369+ (unsafeTailEnv size0)
370+ (\es -> (,) <$> unEff m es <*> getEnv es)
371+
372+-- | Run a statically dispatched effect with the given initial state and return
373+-- the final value, discarding the final state.
374+evalData :: DataA e -> Eff (e : es) a -> Eff es a
375+evalData e m = unsafeEff $ \es0 -> do
376+ size0 <- sizeEnv es0
377+ E.bracket (unsafeConsEnv e noRelinker es0)
378+ (unsafeTailEnv size0)
379+ (\es -> unEff m es)
380+
381+-- | Run a statically dispatched effect with the given initial state and return
382+-- the final state, discarding the final value.
383+execData :: DataA e -> Eff (e : es) a -> Eff es (DataA e)
384+execData e0 m = unsafeEff $ \es0 -> do
385+ size0 <- sizeEnv es0
386+ E.bracket (unsafeConsEnv e0 noRelinker es0)
387+ (unsafeTailEnv size0)
388+ (\es -> unEff m es *> getEnv es)
389+
390+-- | Fetch the current state of the effect.
391+getData :: e :> es => Eff es (DataA e)
392+getData = unsafeEff $ \es -> getEnv es
393+
394+-- | Set the current state of the effect to the given value.
395+putData :: e :> es => DataA e -> Eff es ()
396+putData e = unsafeEff $ \es -> putEnv es e
397+
398+-- | Apply the function to the current state of the effect and return a value.
399+stateData :: e :> es => (DataA e -> (a, DataA e)) -> Eff es a
400+stateData f = unsafeEff $ \es -> stateEnv es f
401+
402+-- | Apply the monadic function to the current state of the effect and return a
403+-- value.
404+stateDataM :: e :> es => (DataA e -> Eff es (a, DataA e)) -> Eff es a
405+stateDataM f = unsafeEff $ \es -> E.mask $ \release -> do
406+ (a, e) <- (\e -> release $ unEff (f e) es) =<< getEnv es
407+ putEnv es e
408+ pure a
409+
410+-- | Execute a computation with a temporarily modified state of the effect.
411+localData :: e :> es => (DataA e -> DataA e) -> Eff es a -> Eff es a
412+localData f m = unsafeEff $ \es -> do
413+ E.bracket (stateEnv es $ \e -> (e, f e))
414+ (\e -> putEnv es e)
415+ (\_ -> unEff m es)
src/Effectful/Internal/Unlift.hs → effectful-core/src/Effectful/Internal/Unlift.hsrenamed+128−20
@@ -1,20 +1,30 @@
1{-# LANGUAGE MagicHash #-}
1{-# LANGUAGE MagicHash #-}
2{-# LANGUAGE UnboxedTuples #-}
2{-# LANGUAGE UnboxedTuples #-}
3{-# OPTIONS_HADDOCK not-home #-}
3{-# OPTIONS_HADDOCK not-home #-}
4−-- | Implementation of concurrent unlifts.
4+-- | Implementation of sequential and concurrent unlifts.
5--
5--
6-- This module is intended for internal use only, and may change without warning
6-- This module is intended for internal use only, and may change without warning
7-- in subsequent releases.
7-- in subsequent releases.
8module Effectful.Internal.Unlift
8module Effectful.Internal.Unlift
9− ( unsafeEphemeralConcUnliftIO
9+ ( -- * Unlifting strategies
10− , unsafePersistentConcUnliftIO
10+ UnliftStrategy(..)
11+ , Persistence(..)
12+ , Limit(..)
13+
14+ -- * Unlifting functions
15+ , seqUnlift
16+ , concUnlift
17+ , ephemeralConcUnlift
18+ , persistentConcUnlift
11 ) where
19 ) where
12
20
13import Control.Concurrent
21import Control.Concurrent
14import Control.Monad
22import Control.Monad
15import GHC.Conc.Sync (ThreadId(..))
23import GHC.Conc.Sync (ThreadId(..))
16import GHC.Exts (mkWeak#, mkWeakNoFinalizer#)
24import GHC.Exts (mkWeak#, mkWeakNoFinalizer#)
25+import GHC.Generics (Generic)
17import GHC.IO (IO(..))
26import GHC.IO (IO(..))
27+import GHC.Stack (HasCallStack)
18import GHC.Weak (Weak(..))
28import GHC.Weak (Weak(..))
19import System.Mem.Weak (deRefWeak)
29import System.Mem.Weak (deRefWeak)
20import qualified Data.IntMap.Strict as IM
30import qualified Data.IntMap.Strict as IM
@@ -22,17 +32,113 @@ import qualified Data.IntMap.Strict as IM
22import Effectful.Internal.Env
32import Effectful.Internal.Env
23import Effectful.Internal.Utils
33import Effectful.Internal.Utils
24
34
35+----------------------------------------
36+-- Unlift strategies
37+
38+-- | The strategy to use when unlifting 'Eff' computations via 'withRunInIO',
39+-- 'Effectful.Monad.withEffToIO' or the 'Effectful.Dispatch.Dynamic.localUnlift'
40+-- family.
41+data UnliftStrategy
42+ = SeqUnlift
43+ -- ^ The fastest strategy and a default setting for 'IOE'. An attempt to call
44+ -- the unlifting function in threads distinct from its creator will result in
45+ -- a runtime error.
46+ | ConcUnlift !Persistence !Limit
47+ -- ^ A strategy that makes it possible for the unlifting function to be called
48+ -- in threads distinct from its creator. See 'Persistence' and 'Limit'
49+ -- settings for more information.
50+ deriving (Eq, Generic, Ord, Show)
51+
52+-- | Persistence setting for the 'ConcUnlift' strategy.
53+--
54+-- Different functions require different persistence strategies. Examples:
55+--
56+-- - Lifting 'pooledMapConcurrentlyN' from the @unliftio@ library requires the
57+-- 'Ephemeral' strategy as we don't want jobs to share environment changes
58+-- made by previous jobs run in the same worker thread.
59+--
60+-- - Lifting 'Control.Concurrent.forkIOWithUnmask' requires the 'Persistent'
61+-- strategy, otherwise the unmasking function would start with a fresh
62+-- environment each time it's called.
63+data Persistence
64+ = Ephemeral
65+ -- ^ Don't persist the environment between calls to the unlifting function in
66+ -- threads distinct from its creator.
67+ | Persistent
68+ -- ^ Persist the environment between calls to the unlifting function within a
69+ -- particular thread.
70+ deriving (Eq, Generic, Ord, Show)
71+
72+-- | Limit setting for the 'ConcUnlift' strategy.
73+data Limit
74+ = Limited !Int
75+ -- ^ Behavior dependent on the 'Persistence' setting.
76+ --
77+ -- For 'Ephemeral', it limits the amount of uses of the unlifting function in
78+ -- threads distinct from its creator to @N@. The unlifting function will
79+ -- create @N@ copies of the environment when called @N@ times and @K+1@ copies
80+ -- when called @K < N@ times.
81+ --
82+ -- For 'Persistent', it limits the amount of threads, distinct from the
83+ -- creator of the unlifting function, it can be called in to @N@. The amount
84+ -- of calls to the unlifting function within a particular threads is
85+ -- unlimited. The unlifting function will create @N@ copies of the environment
86+ -- when called in @N@ threads and @K+1@ copies when called in @K < N@ threads.
87+ | Unlimited
88+ -- ^ Unlimited use of the unlifting function.
89+ deriving (Eq, Generic, Ord, Show)
90+
91+----------------------------------------
92+-- Unlift functions
93+
94+-- | Sequential unlift.
95+seqUnlift
96+ :: HasCallStack
97+ => ((forall r. m r -> IO r) -> IO a)
98+ -> Env es
99+ -> (forall r. m r -> Env es -> IO r)
100+ -> IO a
101+seqUnlift k es unEff = do
102+ tid0 <- myThreadId
103+ k $ \m -> do
104+ tid <- myThreadId
105+ if tid `eqThreadId` tid0
106+ then unEff m es
107+ else error
108+ $ "If you want to use the unlifting function to run Eff computations "
109+ ++ "in multiple threads, have a look at UnliftStrategy (ConcUnlift)."
110+
111+-- | Concurrent unlift for various strategies and limits.
112+concUnlift
113+ :: HasCallStack
114+ => Persistence
115+ -> Limit
116+ -> ((forall r. m r -> IO r) -> IO a)
117+ -> Env es
118+ -> (forall r. m r -> Env es -> IO r)
119+ -> IO a
120+concUnlift Ephemeral (Limited uses) k =
121+ ephemeralConcUnlift uses k
122+concUnlift Ephemeral Unlimited k =
123+ ephemeralConcUnlift maxBound k
124+concUnlift Persistent (Limited threads) k =
125+ persistentConcUnlift False threads k
126+concUnlift Persistent Unlimited k =
127+ persistentConcUnlift True maxBound k
128+
25-- | Concurrent unlift that doesn't preserve the environment between calls to
129-- | Concurrent unlift that doesn't preserve the environment between calls to
26-- the unlifting function in threads other than its creator.
130-- the unlifting function in threads other than its creator.
27−unsafeEphemeralConcUnliftIO
131+ephemeralConcUnlift
132+ :: HasCallStack
28− :: Int
133+ => Int
134+ -- ^ Number of permitted uses of the unlift function.
29 -> ((forall r. m r -> IO r) -> IO a)
135 -> ((forall r. m r -> IO r) -> IO a)
30 -> Env es
136 -> Env es
31 -> (forall r. m r -> Env es -> IO r)
137 -> (forall r. m r -> Env es -> IO r)
32 -> IO a
138 -> IO a
33−unsafeEphemeralConcUnliftIO uses k es0 unEff = do
139+ephemeralConcUnlift uses k es0 unEff = do
34− when (uses < 0) $ do
140+ unless (uses > 0) $ do
35− error $ "ephemeralConcUnliftIO: invalid number of uses: " ++ show uses
141+ error $ "Invalid number of uses: " ++ show uses
36 tid0 <- myThreadId
142 tid0 <- myThreadId
37 -- Create a copy of the environment as a template for the other threads to
143 -- Create a copy of the environment as a template for the other threads to
38 -- use. This can't be done from inside the callback as the environment might
144 -- use. This can't be done from inside the callback as the environment might
@@ -56,16 +162,18 @@ unsafeEphemeralConcUnliftIO uses k es0 unEff = do
56
162
57-- | Concurrent unlift that preserves the environment between calls to the
163-- | Concurrent unlift that preserves the environment between calls to the
58-- unlifting function within a particular thread.
164-- unlifting function within a particular thread.
59−unsafePersistentConcUnliftIO
165+persistentConcUnlift
166+ :: HasCallStack
60− :: Bool
167+ => Bool
61 -> Int
168 -> Int
169+ -- ^ Number of threads that are allowed to use the unlift function.
62 -> ((forall r. m r -> IO r) -> IO a)
170 -> ((forall r. m r -> IO r) -> IO a)
63 -> Env es
171 -> Env es
64 -> (forall r. m r -> Env es -> IO r)
172 -> (forall r. m r -> Env es -> IO r)
65 -> IO a
173 -> IO a
66−unsafePersistentConcUnliftIO cleanUp threads k es0 unEff = do
174+persistentConcUnlift cleanUp threads k es0 unEff = do
67− when (threads < 0) $ do
175+ unless (threads > 0) $ do
68− error $ "persistentConcUnliftIO: invalid number of threads: " ++ show threads
176+ error $ "Invalid number of threads: " ++ show threads
69 tid0 <- myThreadId
177 tid0 <- myThreadId
70 -- Create a copy of the environment as a template for the other threads to
178 -- Create a copy of the environment as a template for the other threads to
71 -- use. This can't be done from inside the callback as the environment might
179 -- use. This can't be done from inside the callback as the environment might
@@ -84,9 +192,9 @@ unsafePersistentConcUnliftIO cleanUp threads k es0 unEff = do
84 Just es -> pure (te, es)
192 Just es -> pure (te, es)
85 Nothing -> case teCapacity te of
193 Nothing -> case teCapacity te of
86 0 -> error
194 0 -> error
87− $ "Number of other threads (" ++ show threads ++ ") permitted to "
195+ $ "Number of other threads (" ++ show threads ++ ") permitted to "
88− ++ "use the unlifting function was exceeded. Please increase the "
196+ ++ "use the unlifting function was exceeded. Please increase the "
89− ++ "limit or use the unlimited variant."
197+ ++ "limit or use the unlimited variant."
90 1 -> do
198 1 -> do
91 wkTidEs <- mkWeakThreadIdEnv tid esTemplate wkTid i mvEntries cleanUp
199 wkTidEs <- mkWeakThreadIdEnv tid esTemplate wkTid i mvEntries cleanUp
92 let newEntries = ThreadEntries
200 let newEntries = ThreadEntries
@@ -117,17 +225,17 @@ nextEntryId :: EntryId -> EntryId
117nextEntryId (EntryId i) = EntryId (i + 1)
225nextEntryId (EntryId i) = EntryId (i + 1)
118
226
119data ThreadEntries es = ThreadEntries
227data ThreadEntries es = ThreadEntries
120− { teCapacity :: Int
228+ { teCapacity :: !Int
121− , teEntries :: IM.IntMap (ThreadEntry es)
229+ , teEntries :: !(IM.IntMap (ThreadEntry es))
122 }
230 }
123
231
124-- | In GHC < 9 weak thread ids are 32bit long, while ThreadIdS are 64bit long,
232-- | In GHC < 9 weak thread ids are 32bit long, while ThreadIdS are 64bit long,
125-- so there is potential for collisions. This is solved by keeping, for a
233-- so there is potential for collisions. This is solved by keeping, for a
126-- particular weak thread id, a list of ThreadIdS with unique EntryIdS.
234-- particular weak thread id, a list of ThreadIdS with unique EntryIdS.
127−data ThreadEntry es = ThreadEntry EntryId (ThreadData es)
235+data ThreadEntry es = ThreadEntry !EntryId !(ThreadData es)
128
236
129data ThreadData es
237data ThreadData es
130− = ThreadData EntryId (Weak (ThreadId, Env es)) (ThreadData es)
238+ = ThreadData !EntryId !(Weak (ThreadId, Env es)) (ThreadData es)
131 | NoThreadData
239 | NoThreadData
132
240
133----------------------------------------
241----------------------------------------
src/Effectful/Monad.hs → effectful-core/src/Effectful/Monad.hsrenamed+8−4
@@ -11,17 +11,21 @@ module Effectful.Monad
11 , IOE
11 , IOE
12 , runEff
12 , runEff
13
13
14− -- * Primitive actions
15− , Prim
16− , runPrim
17−
18 -- ** Unlift strategies
14 -- ** Unlift strategies
19 , UnliftStrategy(..)
15 , UnliftStrategy(..)
20 , Persistence(..)
16 , Persistence(..)
21 , Limit(..)
17 , Limit(..)
22 , unliftStrategy
18 , unliftStrategy
23 , withUnliftStrategy
19 , withUnliftStrategy
20+ , withEffToIO
21+
22+ -- * Re-exports
23+ , MonadIO(..)
24+ , MonadUnliftIO(..)
24 ) where
25 ) where
25
26
27+import Control.Monad.IO.Class
28+import Control.Monad.IO.Unlift
29+
26import Effectful.Internal.Effect
30import Effectful.Internal.Effect
27import Effectful.Internal.Monad
31import Effectful.Internal.Monad
effectful-core/src/Effectful/Prim.hsnew file+7
@@ -0,0 +1,7 @@
1+-- | Provider of the 'MonadPrim' instance for 'Eff'.
2+module Effectful.Prim
3+ ( Prim
4+ , runPrim
5+ ) where
6+
7+import Effectful.Internal.Monad
effectful-core/src/Effectful/Reader.hsnew file+49
@@ -0,0 +1,49 @@
1+-- | Support for access to a read only value of a particular type.
2+module Effectful.Reader
3+ ( Reader
4+ , runReader
5+ , ask
6+ , asks
7+ , local
8+ ) where
9+
10+import Effectful.Dispatch.Static
11+import Effectful.Monad
12+
13+-- | Provide access to a strict (WHNF), thread local, read only value of type
14+-- @r@.
15+newtype Reader r :: Effect where
16+ Reader :: r -> Reader r m a
17+
18+-- | Run a 'Reader' effect with the given initial environment.
19+runReader
20+ :: r -- ^ An initial environment.
21+ -> Eff (Reader r : es) a
22+ -> Eff es a
23+runReader r = evalData (DataA (Reader r))
24+
25+-- | Fetch the value of the environment.
26+ask :: Reader r :> es => Eff es r
27+ask = do
28+ DataA (Reader r) <- getData
29+ pure r
30+
31+-- | Retrieve a function of the current environment.
32+--
33+-- @'asks' f ≡ f '<$>' 'ask'@
34+asks
35+ :: Reader r :> es
36+ => (r -> a) -- ^ The function to apply to the environment.
37+ -> Eff es a
38+asks f = f <$> ask
39+
40+-- | Execute a computation in a modified environment.
41+--
42+-- @'runReader' r ('local' f m) ≡ 'runReader' (f r) m@
43+--
44+local
45+ :: Reader r :> es
46+ => (r -> r) -- ^ The function to modify the environment.
47+ -> Eff es a
48+ -> Eff es a
49+local f = localData $ \(DataA (Reader r)) -> DataA (Reader (f r))
effectful-core/src/Effectful/Reader/Dynamic.hsnew file+32
@@ -0,0 +1,32 @@
1+module Effectful.Reader.Dynamic
2+ ( Reader(..)
3+ , runReader
4+ , ask
5+ , asks
6+ , local
7+ ) where
8+
9+import Effectful.Dispatch.Dynamic
10+import Effectful.Monad
11+import qualified Effectful.Reader as R
12+
13+data Reader r :: Effect where
14+ Ask :: Reader r m r
15+ Local :: (r -> r) -> m a -> Reader r m a
16+
17+runReader :: r -> Eff (Reader r : es) a -> Eff es a
18+runReader r = reinterpret (R.runReader r) $ \env -> \case
19+ Ask -> R.ask
20+ Local f m -> localSeqUnlift env $ \unlift -> R.local f (unlift m)
21+
22+----------------------------------------
23+-- Operations
24+
25+ask :: (HasCallStack, Reader r :> es) => Eff es r
26+ask = send Ask
27+
28+asks :: (HasCallStack, Reader r :> es) => (r -> a) -> Eff es a
29+asks f = f <$> ask
30+
31+local :: (HasCallStack, Reader r :> es ) => (r -> r) -> Eff es a -> Eff es a
32+local f = send . Local f
src/Effectful/State/Dynamic.hs → effectful-core/src/Effectful/State/Dynamic.hsrenamed+38−29
@@ -1,13 +1,4 @@
1-- | The 'State' effect with dynamic dispatch.
1-- | The 'State' effect with dynamic dispatch.
2−--
3−-- It's not clear in which situation it's beneficial to use this instead of
4−-- "Effectful.State.Local" or "Effectful.State.Shared" as you either:
5−--
6−-- - Share state between threads and need the shared version.
7−--
8−-- - Don't share state between threads (or want it to be thread local) and are
9−-- free to use the faster, local version.
10−--
11module Effectful.State.Dynamic
2module Effectful.State.Dynamic
12 ( State(..)
3 ( State(..)
13
4
@@ -31,17 +22,15 @@ module Effectful.State.Dynamic
31 , modifyM
22 , modifyM
32 ) where
23 ) where
33
24
34−import Effectful.Handler
25+import Effectful.Dispatch.Dynamic
35import Effectful.Monad
26import Effectful.Monad
36import qualified Effectful.State.Local as L
27import qualified Effectful.State.Local as L
37import qualified Effectful.State.Shared as S
28import qualified Effectful.State.Shared as S
38
29
39−-- | Provide access to a mutable state of type @s@.
30+-- | Provide access to a mutable value of type @s@.
40−--
41−-- Whether the state is local and shareable depends on the interpretation.
42data State s :: Effect where
31data State s :: Effect where
43 Get :: State s m s
32 Get :: State s m s
44− Put :: ~s -> State s m ()
33+ Put :: s -> State s m ()
45 State :: (s -> (a, s)) -> State s m a
34 State :: (s -> (a, s)) -> State s m a
46 StateM :: (s -> m (a, s)) -> State s m a
35 StateM :: (s -> m (a, s)) -> State s m a
47
36
@@ -49,17 +38,17 @@ data State s :: Effect where
49-- Local
38-- Local
50
39
51runLocalState :: s -> Eff (State s : es) a -> Eff es (a, s)
40runLocalState :: s -> Eff (State s : es) a -> Eff es (a, s)
52−runLocalState s0 = reinterpretM (L.runState s0) localState
41+runLocalState s0 = reinterpret (L.runState s0) localState
53
42
54evalLocalState :: s -> Eff (State s : es) a -> Eff es a
43evalLocalState :: s -> Eff (State s : es) a -> Eff es a
55−evalLocalState s0 = reinterpretM (L.evalState s0) localState
44+evalLocalState s0 = reinterpret (L.evalState s0) localState
56
45
57execLocalState :: s -> Eff (State s : es) a -> Eff es s
46execLocalState :: s -> Eff (State s : es) a -> Eff es s
58−execLocalState s0 = reinterpretM (L.execState s0) localState
47+execLocalState s0 = reinterpret (L.execState s0) localState
59
48
60localState
49localState
61 :: L.State s :> es
50 :: L.State s :> es
62− => LocalEnv localEs
51+ => LocalEnv localEs es
63 -> State s (Eff localEs) a
52 -> State s (Eff localEs) a
64 -> Eff es a
53 -> Eff es a
65localState env = \case
54localState env = \case
@@ -72,17 +61,17 @@ localState env = \case
72-- Shared
61-- Shared
73
62
74runSharedState :: s -> Eff (State s : es) a -> Eff es (a, s)
63runSharedState :: s -> Eff (State s : es) a -> Eff es (a, s)
75−runSharedState s0 = reinterpretM (S.runState s0) sharedState
64+runSharedState s0 = reinterpret (S.runState s0) sharedState
76
65
77evalSharedState :: s -> Eff (State s : es) a -> Eff es a
66evalSharedState :: s -> Eff (State s : es) a -> Eff es a
78−evalSharedState s0 = reinterpretM (S.evalState s0) sharedState
67+evalSharedState s0 = reinterpret (S.evalState s0) sharedState
79
68
80execSharedState :: s -> Eff (State s : es) a -> Eff es s
69execSharedState :: s -> Eff (State s : es) a -> Eff es s
81−execSharedState s0 = reinterpretM (S.execState s0) sharedState
70+execSharedState s0 = reinterpret (S.execState s0) sharedState
82
71
83sharedState
72sharedState
84 :: S.State s :> es
73 :: S.State s :> es
85− => LocalEnv localEs
74+ => LocalEnv localEs es
86 -> State s (Eff localEs) a
75 -> State s (Eff localEs) a
87 -> Eff es a
76 -> Eff es a
88sharedState env = \case
77sharedState env = \case
@@ -94,23 +83,43 @@ sharedState env = \case
94----------------------------------------
83----------------------------------------
95-- Operations
84-- Operations
96
85
86+get
87+ :: (HasCallStack, State s :> es)
97−get :: State s :> es => Eff es s
88+ => Eff es s
98get = send Get
89get = send Get
99
90
91+gets
92+ :: (HasCallStack, State s :> es)
93+ => (s -> a)
100−gets :: State s :> es => (s -> a) -> Eff es a
94+ -> Eff es a
101gets f = f <$> get
95gets f = f <$> get
102
96
97+put
98+ :: (HasCallStack, State s :> es)
99+ => s
103−put :: State s :> es => s -> Eff es ()
100+ -> Eff es ()
104put = send . Put
101put = send . Put
105
102
103+state
104+ :: (HasCallStack, State s :> es)
105+ => (s -> (a, s))
106−state :: (State s :> es) => (s -> (a, s)) -> Eff es a
106+ -> Eff es a
107state = send . State
107state = send . State
108
108
109−modify :: State s :> es => (s -> s) -> Eff es ()
109+modify
110+ :: (HasCallStack, State s :> es)
111+ => (s -> s)
112+ -> Eff es ()
110modify f = state (\s -> ((), f s))
113modify f = state (\s -> ((), f s))
111
114
115+stateM
116+ :: (HasCallStack, State s :> es)
112−stateM :: State s :> es => (s -> Eff es (a, s)) -> Eff es a
117+ => (s -> Eff es (a, s))
118+ -> Eff es a
113stateM = send . StateM
119stateM = send . StateM
114
120
115−modifyM :: State s :> es => (s -> Eff es s) -> Eff es ()
121+modifyM
122+ :: (HasCallStack, State s :> es)
123+ => (s -> Eff es s)
124+ -> Eff es ()
116modifyM f = stateM (\s -> ((), ) <$> f s)
125modifyM f = stateM (\s -> ((), ) <$> f s)
effectful-core/src/Effectful/State/Local.hsnew file+131
@@ -0,0 +1,131 @@
1+-- | Support for access to a mutable value of a particular type, which is:
2+--
3+-- - thread local (if you want the value to be shared between threads, have a
4+-- look at "Effectful.State.Shared"),
5+--
6+-- - very fast.
7+--
8+-- /Note:/ unlike the 'Control.Monad.Trans.State.StateT' monad transformer from
9+-- the @transformers@ library, the 'State' effect doesn't lose state
10+-- modifications when an exception is received:
11+--
12+-- >>> import qualified Control.Monad.Trans.State.Strict as S
13+--
14+-- >>> :{
15+-- (`S.execStateT` "Hi") . handle (\(_::ErrorCall) -> pure ()) $ do
16+-- S.modify (++ " there!")
17+-- error "oops"
18+-- :}
19+-- "Hi"
20+--
21+-- >>> :{
22+-- runEff . execState "Hi" . handle (\(_::ErrorCall) -> pure ()) $ do
23+-- modify (++ " there!")
24+-- error "oops"
25+-- :}
26+-- "Hi there!"
27+module Effectful.State.Local
28+ ( State
29+ , runState
30+ , evalState
31+ , execState
32+ , get
33+ , gets
34+ , put
35+ , state
36+ , modify
37+ , stateM
38+ , modifyM
39+ ) where
40+
41+import Effectful.Dispatch.Static
42+import Effectful.Monad
43+
44+-- | Provide access to a strict (WHNF), thread local, mutable value of type @s@.
45+newtype State s :: Effect where
46+ State :: s -> State s m r
47+
48+-- | Run a 'State' effect with the given initial state and return the final
49+-- value along with the final state.
50+runState
51+ :: s -- ^ An initial state.
52+ -> Eff (State s : es) a
53+ -> Eff es (a, s)
54+runState s0 m = do
55+ (a, DataA (State s)) <- runData (DataA (State s0)) m
56+ pure (a, s)
57+
58+-- | Run a 'State' effect with the given initial state and return the final
59+-- value, discarding the final state.
60+evalState
61+ :: s -- ^ An initial state.
62+ -> Eff (State s : es) a
63+ -> Eff es a -- ^ A return value.
64+evalState s = evalData (DataA (State s))
65+
66+-- | Run a 'State' effect with the given initial state and return the final
67+-- state, discarding the final value.
68+execState
69+ :: s -- ^ An initial state.
70+ -> Eff (State s : es) a
71+ -> Eff es s
72+execState s0 m = do
73+ DataA (State s) <- execData (DataA (State s0)) m
74+ pure s
75+
76+-- | Fetch the current value of the state.
77+get :: State s :> es => Eff es s
78+get = do
79+ DataA (State s) <- getData
80+ pure s
81+
82+-- | Get a function of the current state.
83+--
84+-- @'gets' f ≡ f '<$>' 'get'@
85+gets
86+ :: State s :> es
87+ => (s -> a) -- ^ The function to apply to the state.
88+ -> Eff es a
89+gets f = f <$> get
90+
91+-- | Set the current state to the given value.
92+put :: State s :> es => s -> Eff es ()
93+put s = putData (DataA (State s))
94+
95+-- | Apply the function to the current state and return a value.
96+state
97+ :: State s :> es
98+ => (s -> (a, s)) -- ^ The function to modify the state.
99+ -> Eff es a
100+state f = stateData $ \(DataA (State s0)) -> let (a, s) = f s0 in (a, DataA (State s))
101+
102+-- | Apply the function to the current state.
103+--
104+-- @'modify' f ≡ 'state' (\\s -> ((), f s))@
105+modify
106+ :: State s :> es
107+ => (s -> s) -- ^ The function to modify the state.
108+ -> Eff es ()
109+modify f = state $ \s -> ((), f s)
110+
111+-- | Apply the monadic function to the current state and return a value.
112+stateM
113+ :: State s :> es
114+ => (s -> Eff es (a, s)) -- ^ The function to modify the state.
115+ -> Eff es a
116+stateM f = stateDataM $ \(DataA (State s0)) -> do
117+ (a, s) <- f s0
118+ pure (a, DataA (State s))
119+
120+-- | Apply the monadic function to the current state.
121+--
122+-- @'modifyM' f ≡ 'stateM' (\\s -> ((), ) '<$>' f s)@
123+modifyM
124+ :: State s :> es
125+ => (s -> Eff es s) -- ^ The monadic function to modify the state.
126+ -> Eff es ()
127+modifyM f = stateM (\s -> ((), ) <$> f s)
128+
129+-- $setup
130+-- >>> import Control.Exception (ErrorCall)
131+-- >>> import Control.Monad.Catch
effectful-core/src/Effectful/State/Shared.hsnew file+127
@@ -0,0 +1,127 @@
1+-- | Support for access to a mutable value of a particular type, which is:
2+--
3+-- - shared between multiple threads (if you want each thead to manage its own
4+-- version of the value, see "Effectful.State.Local").
5+--
6+-- - slightly slower than "Effectful.State.Local".
7+--
8+-- /Note:/ unlike the 'Control.Monad.Trans.State.StateT' monad transformer from
9+-- the @transformers@ library, the 'State' effect doesn't lose state
10+-- modifications when an exception is received:
11+--
12+-- >>> import qualified Control.Monad.Trans.State.Strict as S
13+--
14+-- >>> :{
15+-- (`S.execStateT` "Hi") . handle (\(_::ErrorCall) -> pure ()) $ do
16+-- S.modify (++ " there!")
17+-- error "oops"
18+-- :}
19+-- "Hi"
20+--
21+-- >>> :{
22+-- runEff . execState "Hi" . handle (\(_::ErrorCall) -> pure ()) $ do
23+-- modify (++ " there!")
24+-- error "oops"
25+-- :}
26+-- "Hi there!"
27+module Effectful.State.Shared
28+ ( State
29+ , runState
30+ , evalState
31+ , execState
32+ , get
33+ , gets
34+ , put
35+ , state
36+ , modify
37+ , stateM
38+ , modifyM
39+ ) where
40+
41+import Control.Concurrent.MVar
42+
43+import Effectful.Dispatch.Static
44+import Effectful.Monad
45+
46+-- | Provide access to a strict (WHNF), shared, mutable value of type @s@.
47+newtype State s :: Effect where
48+ State :: MVar s -> State s m r
49+
50+-- | Run a 'State' effect with the given initial state and return the final
51+-- value along with the final state.
52+runState :: s -> Eff (State s : es) a -> Eff es (a, s)
53+runState s m = do
54+ v <- unsafeEff_ $ newMVar s
55+ a <- evalData (DataA (State v)) m
56+ (a, ) <$> unsafeEff_ (readMVar v)
57+
58+-- | Run a 'State' effect with the given initial state and return the final
59+-- value, discarding the final state.
60+evalState :: s -> Eff (State s : es) a -> Eff es a
61+evalState s m = do
62+ v <- unsafeEff_ $ newMVar s
63+ evalData (DataA (State v)) m
64+
65+-- | Run a 'State' effect with the given initial state and return the final
66+-- state, discarding the final value.
67+execState :: s -> Eff (State s : es) a -> Eff es s
68+execState s m = do
69+ v <- unsafeEff_ $ newMVar s
70+ _ <- evalData (DataA (State v)) m
71+ unsafeEff_ $ readMVar v
72+
73+-- | Fetch the current value of the state.
74+get :: State s :> es => Eff es s
75+get = unsafeEff $ \es -> do
76+ DataA (State v) <- getEnv es
77+ readMVar v
78+
79+-- | Get a function of the current state.
80+--
81+-- @'gets' f ≡ f '<$>' 'get'@
82+gets :: State s :> es => (s -> a) -> Eff es a
83+gets f = f <$> get
84+
85+-- | Set the current state to the given value.
86+put :: State s :> es => s -> Eff es ()
87+put s = unsafeEff $ \es -> do
88+ DataA (State v) <- getEnv es
89+ modifyMVar_ v $ \_ -> s `seq` pure s
90+
91+-- | Apply the function to the current state and return a value.
92+--
93+-- /Note:/ this function gets an exclusive access to the state for its duration.
94+state :: State s :> es => (s -> (a, s)) -> Eff es a
95+state f = unsafeEff $ \es -> do
96+ DataA (State v) <- getEnv es
97+ modifyMVar v $ \s0 -> let (a, s) = f s0 in s `seq` pure (s, a)
98+
99+-- | Apply the function to the current state.
100+--
101+-- @'modify' f ≡ 'state' (\\s -> ((), f s))@
102+--
103+-- /Note:/ this function gets an exclusive access to the state for its duration.
104+modify :: State s :> es => (s -> s) -> Eff es ()
105+modify f = state (\s -> ((), f s))
106+
107+-- | Apply the monadic function to the current state and return a value.
108+--
109+-- /Note:/ this function gets an exclusive access to the state for its duration.
110+stateM :: State s :> es => (s -> Eff es (a, s)) -> Eff es a
111+stateM f = unsafeEff $ \es -> do
112+ DataA (State v) <- getEnv es
113+ modifyMVar v $ \s0 -> do
114+ (a, s) <- unEff (f s0) es
115+ s `seq` pure (s, a)
116+
117+-- | Apply the monadic function to the current state.
118+--
119+-- @'modifyM' f ≡ 'stateM' (\\s -> ((), ) '<$>' f s)@
120+--
121+-- /Note:/ this function gets an exclusive access to the state for its duration.
122+modifyM :: State s :> es => (s -> Eff es s) -> Eff es ()
123+modifyM f = stateM (\s -> ((), ) <$> f s)
124+
125+-- $setup
126+-- >>> import Control.Exception (ErrorCall)
127+-- >>> import Control.Monad.Catch
src/Effectful/Writer/Dynamic.hs → effectful-core/src/Effectful/Writer/Dynamic.hsrenamed+21−11
@@ -15,27 +15,27 @@ module Effectful.Writer.Dynamic
15 , listens
15 , listens
16 ) where
16 ) where
17
17
18−import Effectful.Handler
18+import Effectful.Dispatch.Dynamic
19import Effectful.Monad
19import Effectful.Monad
20import qualified Effectful.Writer.Local as L
20import qualified Effectful.Writer.Local as L
21import qualified Effectful.Writer.Shared as S
21import qualified Effectful.Writer.Shared as S
22
22
23data Writer w :: Effect where
23data Writer w :: Effect where
24− Tell :: ~w -> Writer w m ()
24+ Tell :: w -> Writer w m ()
25 Listen :: m a -> Writer w m (a, w)
25 Listen :: m a -> Writer w m (a, w)
26
26
27----------------------------------------
27----------------------------------------
28-- Local
28-- Local
29
29
30runLocalWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
30runLocalWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
31−runLocalWriter = reinterpretM L.runWriter localWriter
31+runLocalWriter = reinterpret L.runWriter localWriter
32
32
33execLocalWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
33execLocalWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
34−execLocalWriter = reinterpretM L.execWriter localWriter
34+execLocalWriter = reinterpret L.execWriter localWriter
35
35
36localWriter
36localWriter
37 :: (L.Writer w :> es, Monoid w)
37 :: (L.Writer w :> es, Monoid w)
38− => LocalEnv localEs
38+ => LocalEnv localEs es
39 -> Writer w (Eff localEs) a
39 -> Writer w (Eff localEs) a
40 -> Eff es a
40 -> Eff es a
41localWriter env = \case
41localWriter env = \case
@@ -46,14 +46,14 @@ localWriter env = \case
46-- Shared
46-- Shared
47
47
48runSharedWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
48runSharedWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
49−runSharedWriter = reinterpretM S.runWriter sharedWriter
49+runSharedWriter = reinterpret S.runWriter sharedWriter
50
50
51execSharedWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
51execSharedWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
52−execSharedWriter = reinterpretM S.execWriter sharedWriter
52+execSharedWriter = reinterpret S.execWriter sharedWriter
53
53
54sharedWriter
54sharedWriter
55 :: (S.Writer w :> es, Monoid w)
55 :: (S.Writer w :> es, Monoid w)
56− => LocalEnv localEs
56+ => LocalEnv localEs es
57 -> Writer w (Eff localEs) a
57 -> Writer w (Eff localEs) a
58 -> Eff es a
58 -> Eff es a
59sharedWriter env = \case
59sharedWriter env = \case
@@ -63,13 +63,23 @@ sharedWriter env = \case
63----------------------------------------
63----------------------------------------
64-- Operations
64-- Operations
65
65
66−tell :: (Writer w :> es, Monoid w) => w -> Eff es ()
66+tell
67+ :: (HasCallStack, Writer w :> es)
68+ => w
69+ -> Eff es ()
67tell = send . Tell
70tell = send . Tell
68
71
69−listen :: (Writer w :> es, Monoid w) => Eff es a -> Eff es (a, w)
72+listen
73+ :: (HasCallStack, Writer w :> es)
74+ => Eff es a
75+ -> Eff es (a, w)
70listen = send . Listen
76listen = send . Listen
71
77
72−listens :: (Writer w :> es, Monoid w) => (w -> b) -> Eff es a -> Eff es (a, b)
78+listens
79+ :: (HasCallStack, Writer w :> es)
80+ => (w -> b)
81+ -> Eff es a
82+ -> Eff es (a, b)
73listens f m = do
83listens f m = do
74 (a, w) <- listen m
84 (a, w) <- listen m
75 pure (a, f w)
85 pure (a, f w)
effectful-core/src/Effectful/Writer/Local.hsnew file+94
@@ -0,0 +1,94 @@
1+-- | Support for access to a write only value of a particular type, which is:
2+--
3+-- - thread local (if you want the value to be shared between threads, have a
4+-- look at "Effectful.Writer.Shared"),
5+--
6+-- - very fast.
7+--
8+-- /Warning:/ 'Writer'\'s state will be accumulated via __left-associated__ uses
9+-- of '<>', which makes it unsuitable for use with types for which such pattern
10+-- is inefficient. __This applies, in particular, to the standard list type__,
11+-- which makes the 'Writer' effect pretty niche.
12+--
13+-- /Note:/ while the 'Control.Monad.Trans.Writer.Strict.Writer' from the
14+-- @transformers@ package includes additional operations
15+-- 'Control.Monad.Trans.Writer.Strict.pass' and
16+-- 'Control.Monad.Trans.Writer.Strict.censor', they don't cooperate with runtime
17+-- exceptions very well, so they're deliberately omitted here.
18+module Effectful.Writer.Local
19+ ( Writer
20+ , runWriter
21+ , execWriter
22+ , tell
23+ , listen
24+ , listens
25+ ) where
26+
27+import Control.Exception (onException, mask)
28+
29+import Effectful.Dispatch.Static
30+import Effectful.Monad
31+
32+-- | Provide access to a strict (WHNF), thread local, write only value of type
33+-- @w@.
34+newtype Writer w :: Effect where
35+ Writer :: w -> Writer w m r
36+
37+-- | Run a 'Writer' effect and return the final value along with the final
38+-- output.
39+runWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
40+runWriter m = do
41+ (a, DataA (Writer w)) <- runData (DataA (Writer mempty)) m
42+ pure (a, w)
43+
44+-- | Run a 'Writer' effect and return the final output, discarding the final
45+-- value.
46+execWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
47+execWriter m = do
48+ DataA (Writer w) <- execData (DataA (Writer mempty)) m
49+ pure w
50+
51+-- | Append the given output to the overall output of the 'Writer'.
52+tell :: (Writer w :> es, Monoid w) => w -> Eff es ()
53+tell w = stateData $ \(DataA (Writer w0)) -> ((), DataA (Writer (w0 <> w)))
54+
55+-- | Execute an action and append its output to the overall output of the
56+-- 'Writer'.
57+--
58+-- /Note:/ if an exception is received while the action is executed, the partial
59+-- output of the action will still be appended to the overall output of the
60+-- 'Writer':
61+--
62+-- >>> :{
63+-- runEff . execWriter @String $ do
64+-- tell "Hi"
65+-- handle (\(_::ErrorCall) -> pure ((), "")) $ do
66+-- tell " there"
67+-- listen $ do
68+-- tell "!"
69+-- error "oops"
70+-- :}
71+-- "Hi there!"
72+listen :: (Writer w :> es, Monoid w) => Eff es a -> Eff es (a, w)
73+listen m = unsafeEff $ \es -> mask $ \restore -> do
74+ w0 <- stateEnv es $ \(DataA (Writer w)) -> (w, DataA (Writer mempty))
75+ a <- restore (unEff m es) `onException` merge es w0
76+ (a, ) <$> merge es w0
77+ where
78+ merge es w0 =
79+ -- If an exception is thrown, restore w0 and keep parts of w1.
80+ stateEnv es $ \(DataA (Writer w1)) -> (w1, DataA (Writer (w0 <> w1)))
81+
82+-- | Execute an action and append its output to the overall output of the
83+-- 'Writer', then return the final value along with a function of the recorded
84+-- output.
85+--
86+-- @'listens' f m ≡ 'Data.Bifunctor.second' f '<$>' 'listen' m@
87+listens :: (Writer w :> es, Monoid w) => (w -> b) -> Eff es a -> Eff es (a, b)
88+listens f m = do
89+ (a, w) <- listen m
90+ pure (a, f w)
91+
92+-- $setup
93+-- >>> import Control.Exception (ErrorCall)
94+-- >>> import Control.Monad.Catch
effectful-core/src/Effectful/Writer/Shared.hsnew file+108
@@ -0,0 +1,108 @@
1+-- | Support for access to a write only value of a particular type, which is:
2+--
3+-- - shared between multiple threads (if you want each thead to manage its own
4+-- version of the value, see "Effectful.Writer.Local").
5+--
6+-- - slightly slower than "Effectful.Writer.Local".
7+--
8+-- /Warning:/ 'Writer'\'s state will be accumulated via __left-associated__ uses
9+-- of '<>', which makes it unsuitable for use with types for which such pattern
10+-- is inefficient. __This applies, in particular, to the standard list type__,
11+-- which makes the 'Writer' effect pretty niche.
12+--
13+-- /Note:/ while the 'Control.Monad.Trans.Writer.Strict.Writer' from the
14+-- @transformers@ package includes additional operations
15+-- 'Control.Monad.Trans.Writer.Strict.pass' and
16+-- 'Control.Monad.Trans.Writer.Strict.censor', they don't cooperate with runtime
17+-- exceptions very well, so they're deliberately omitted here.
18+module Effectful.Writer.Shared
19+ ( Writer
20+ , runWriter
21+ , execWriter
22+ , tell
23+ , listen
24+ , listens
25+ ) where
26+
27+import Control.Concurrent.MVar
28+import Control.Exception (onException, uninterruptibleMask)
29+
30+import Effectful.Dispatch.Static
31+import Effectful.Monad
32+
33+-- | Provide access to a strict (WHNF), shared, write only value of type @w@.
34+newtype Writer w :: Effect where
35+ Writer :: MVar w -> Writer w m r
36+
37+-- | Run a 'Writer' effect and return the final value along with the final
38+-- output.
39+runWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
40+runWriter m = do
41+ v <- unsafeEff_ $ newMVar mempty
42+ a <- evalData (DataA (Writer v)) m
43+ (a, ) <$> unsafeEff_ (readMVar v)
44+
45+-- | Run a 'Writer' effect and return the final output, discarding the final
46+-- value.
47+execWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
48+execWriter m = do
49+ v <- unsafeEff_ $ newMVar mempty
50+ _ <- evalData (DataA (Writer v)) m
51+ unsafeEff_ $ readMVar v
52+
53+-- | Append the given output to the overall output of the 'Writer'.
54+tell :: (Writer w :> es, Monoid w) => w -> Eff es ()
55+tell w1 = unsafeEff $ \es -> do
56+ DataA (Writer v) <- getEnv es
57+ modifyMVar_ v $ \w0 -> let w = w0 <> w1 in w `seq` pure w
58+
59+-- | Execute an action and append its output to the overall output of the
60+-- 'Writer'.
61+--
62+-- /Note:/ if an exception is received while the action is executed, the partial
63+-- output of the action will still be appended to the overall output of the
64+-- 'Writer':
65+--
66+-- >>> :{
67+-- runEff . execWriter @String $ do
68+-- tell "Hi"
69+-- handle (\(_::ErrorCall) -> pure ((), "")) $ do
70+-- tell " there"
71+-- listen $ do
72+-- tell "!"
73+-- error "oops"
74+-- :}
75+-- "Hi there!"
76+listen :: (Writer w :> es, Monoid w) => Eff es a -> Eff es (a, w)
77+listen m = unsafeEff $ \es -> do
78+ -- The mask is uninterruptible because modifyMVar_ v0 in the merge function
79+ -- might block and if an async exception is received while waiting, w1 will be
80+ -- lost.
81+ uninterruptibleMask $ \restore -> do
82+ v1 <- newMVar mempty
83+ -- Replace thread local MVar with a fresh one for isolated listening.
84+ v0 <- stateEnv es $ \(DataA (Writer v)) -> (v, DataA (Writer v1))
85+ a <- restore (unEff m es) `onException` merge es v0 v1
86+ (a, ) <$> merge es v0 v1
87+ where
88+ -- Merge results accumulated in the local MVar with the mainline. If an
89+ -- exception was received while listening, merge results recorded so far.
90+ merge es v0 v1 = do
91+ putEnv es $ DataA (Writer v0)
92+ w1 <- readMVar v1
93+ modifyMVar_ v0 $ \w0 -> let w = w0 <> w1 in w `seq` pure w
94+ pure w1
95+
96+-- | Execute an action and append its output to the overall output of the
97+-- 'Writer', then return the final value along with a function of the recorded
98+-- output.
99+--
100+-- @'listens' f m ≡ 'Data.Bifunctor.second' f '<$>' 'listen' m@
101+listens :: (Writer w :> es, Monoid w) => (w -> b) -> Eff es a -> Eff es (a, b)
102+listens f m = do
103+ (a, w) <- listen m
104+ pure (a, f w)
105+
106+-- $setup
107+-- >>> import Control.Exception (ErrorCall)
108+-- >>> import Control.Monad.Catch
utils/Effectful/Internal/Utils.hs → effectful-core/utils/Effectful/Internal/Utils.hsrenamed

The content is the same.

utils/utils.c → effectful-core/utils/utils.crenamed

The content is the same.

effectful/CHANGELOG.mdnew file+2
@@ -0,0 +1,2 @@
1+# effectful-0.0.0.0 (2021-06-13)
2+* Initial alpha release.
effectful/LICENSEnew file+30
@@ -0,0 +1,30 @@
1+Copyright (c) 2021, Andrzej Rybczak
2+
3+All rights reserved.
4+
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
7+
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
10+
11+ * Redistributions in binary form must reproduce the above
12+ copyright notice, this list of conditions and the following
13+ disclaimer in the documentation and/or other materials provided
14+ with the distribution.
15+
16+ * Neither the name of Andrzej Rybczak nor the names of other
17+ contributors may be used to endorse or promote products derived
18+ from this software without specific prior written permission.
19+
20+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
bench/Concurrency.hs → effectful/bench/Concurrency.hsrenamed+11−13
@@ -2,8 +2,7 @@
2module Concurrency (concurrencyBenchmark) where
2module Concurrency (concurrencyBenchmark) where
3
3
4#ifdef VERSION_criterion
4#ifdef VERSION_criterion
5−import Criterion
5+import Criterion hiding (env)
6−import Criterion.Main
7#endif
6#endif
8
7
9#ifdef VERSION_tasty_bench
8#ifdef VERSION_tasty_bench
@@ -12,8 +11,7 @@ import Test.Tasty.Bench hiding (env)
12
11
13import Control.Concurrent.Async
12import Control.Concurrent.Async
14import Control.Monad
13import Control.Monad
15−import Control.Monad.IO.Class
16−import qualified Effectful.Async as A
14+import qualified Effectful.Concurrent.Async as A
17
15
18import Effectful
16import Effectful
19import Utils
17import Utils
@@ -27,7 +25,7 @@ concurrencyBenchmark = bgroup "concurrency"
27shallowBench :: Int -> Benchmark
25shallowBench :: Int -> Benchmark
28shallowBench n = bgroup ("unmask " ++ show n ++ "x")
26shallowBench n = bgroup ("unmask " ++ show n ++ "x")
29 [ bench "async (IO)" $ nfAppIO (asyncBenchIO n) op
27 [ bench "async (IO)" $ nfAppIO (asyncBenchIO n) op
30− , bench "async (Eff)" $ nfAppIO (runShallow . A.runAsyncE . asyncBench n) op
28+ , bench "async (Eff)" $ nfAppIO (runShallow . A.runConcurrent . asyncBench n) op
31 , bench "Fork (localUnliftIO/withLiftMapIO)" $
29 , bench "Fork (localUnliftIO/withLiftMapIO)" $
32 nfAppIO (runShallow . runFork1 . forkBench n) op
30 nfAppIO (runShallow . runFork1 . forkBench n) op
33 , bench "Fork (localUnlift/withLiftMap)" $
31 , bench "Fork (localUnlift/withLiftMap)" $
@@ -40,7 +38,7 @@ shallowBench n = bgroup ("unmask " ++ show n ++ "x")
40
38
41deepBench :: Int -> Benchmark
39deepBench :: Int -> Benchmark
42deepBench n = bgroup ("unmask " ++ show n ++ "x")
40deepBench n = bgroup ("unmask " ++ show n ++ "x")
43− [ bench "async (Eff)" $ nfAppIO (runDeep . A.runAsyncE . asyncBench n) op
41+ [ bench "async (Eff)" $ nfAppIO (runDeep . A.runConcurrent . asyncBench n) op
44 , bench "Fork (localUnliftIO/withLiftMapIO)" $
42 , bench "Fork (localUnliftIO/withLiftMapIO)" $
45 nfAppIO (runDeep . runFork1 . forkBench n) op
43 nfAppIO (runDeep . runFork1 . forkBench n) op
46 , bench "Fork (localUnlift/withLiftMap)" $
44 , bench "Fork (localUnlift/withLiftMap)" $
@@ -61,28 +59,28 @@ data Fork :: Effect where
61
59
62-- | Uses 'localUnliftIO' and 'withLiftMapIO'.
60-- | Uses 'localUnliftIO' and 'withLiftMapIO'.
63runFork1 :: IOE :> es => Eff (Fork : es) a -> Eff es a
61runFork1 :: IOE :> es => Eff (Fork : es) a -> Eff es a
64−runFork1 = interpretM $ \env -> \case
62+runFork1 = interpret $ \env -> \case
65− ForkWithUnmask m -> withLiftMapIO $ \liftMap -> do
63+ ForkWithUnmask m -> withLiftMapIO env $ \liftMap -> do
66 localUnliftIO env (ConcUnlift Ephemeral $ Limited 1) $ \unlift -> do
64 localUnliftIO env (ConcUnlift Ephemeral $ Limited 1) $ \unlift -> do
67 asyncWithUnmask $ \unmask -> unlift $ m $ liftMap unmask
65 asyncWithUnmask $ \unmask -> unlift $ m $ liftMap unmask
68
66
69-- | Uses 'localUnlift' and 'withLiftMap'.
67-- | Uses 'localUnlift' and 'withLiftMap'.
70runFork2 :: IOE :> es => Eff (Fork : es) a -> Eff es a
68runFork2 :: IOE :> es => Eff (Fork : es) a -> Eff es a
71−runFork2 = reinterpretM A.runAsyncE $ \env -> \case
69+runFork2 = reinterpret A.runConcurrent $ \env -> \case
72− ForkWithUnmask m -> withLiftMap $ \liftMap -> do
70+ ForkWithUnmask m -> withLiftMap env $ \liftMap -> do
73 localUnlift env (ConcUnlift Ephemeral $ Limited 1) $ \unlift -> do
71 localUnlift env (ConcUnlift Ephemeral $ Limited 1) $ \unlift -> do
74 A.asyncWithUnmask $ \unmask -> unlift $ m $ liftMap unmask
72 A.asyncWithUnmask $ \unmask -> unlift $ m $ liftMap unmask
75
73
76-- | Uses 'localLiftUnliftIO'.
74-- | Uses 'localLiftUnliftIO'.
77runFork3 :: IOE :> es => Eff (Fork : es) a -> Eff es a
75runFork3 :: IOE :> es => Eff (Fork : es) a -> Eff es a
78−runFork3 = interpretM $ \env -> \case
76+runFork3 = interpret $ \env -> \case
79 ForkWithUnmask m -> do
77 ForkWithUnmask m -> do
80 localLiftUnliftIO env (ConcUnlift Persistent $ Limited 1) $ \lift unlift -> do
78 localLiftUnliftIO env (ConcUnlift Persistent $ Limited 1) $ \lift unlift -> do
81 asyncWithUnmask $ \unmask -> unlift $ m $ lift . unmask . unlift
79 asyncWithUnmask $ \unmask -> unlift $ m $ lift . unmask . unlift
82
80
83-- | Uses 'localLiftUnlift'.
81-- | Uses 'localLiftUnlift'.
84runFork4 :: IOE :> es => Eff (Fork : es) a -> Eff es a
82runFork4 :: IOE :> es => Eff (Fork : es) a -> Eff es a
85−runFork4 = reinterpretM A.runAsyncE $ \env -> \case
83+runFork4 = reinterpret A.runConcurrent $ \env -> \case
86 ForkWithUnmask m -> do
84 ForkWithUnmask m -> do
87 localLiftUnlift env (ConcUnlift Persistent $ Limited 1) $ \lift unlift -> do
85 localLiftUnlift env (ConcUnlift Persistent $ Limited 1) $ \lift unlift -> do
88 A.asyncWithUnmask $ \unmask -> unlift $ m $ lift . unmask . unlift
86 A.asyncWithUnmask $ \unmask -> unlift $ m $ lift . unmask . unlift
@@ -96,7 +94,7 @@ asyncBenchIO n f = do
96 wait a
94 wait a
97{-# NOINLINE asyncBenchIO #-}
95{-# NOINLINE asyncBenchIO #-}
98
96
99−asyncBench :: A.AsyncE :> es => Int -> Eff es Int -> Eff es Int
97+asyncBench :: A.Concurrent :> es => Int -> Eff es Int -> Eff es Int
100asyncBench n f = do
98asyncBench n f = do
101 a <- A.asyncWithUnmask $ \unmask -> do
99 a <- A.asyncWithUnmask $ \unmask -> do
102 sum <$> replicateM n (unmask f)
100 sum <$> replicateM n (unmask f)
bench/Countdown.hs → effectful/bench/Countdown.hsrenamed

The content is the same.

bench/FileSizes.hs → effectful/bench/FileSizes.hsrenamed+2−2
@@ -81,7 +81,7 @@ effectful_tryFileSize :: Effectful_File E.:> es => FilePath -> E.Eff es (Maybe I
81effectful_tryFileSize = E.send . Effectful_tryFileSize
81effectful_tryFileSize = E.send . Effectful_tryFileSize
82
82
83effectful_runFile :: E.IOE E.:> es => E.Eff (Effectful_File : es) a -> E.Eff es a
83effectful_runFile :: E.IOE E.:> es => E.Eff (Effectful_File : es) a -> E.Eff es a
84−effectful_runFile = E.interpret \case
84+effectful_runFile = E.interpret \_ -> \case
85 Effectful_tryFileSize path -> liftIO $ tryGetFileSize path
85 Effectful_tryFileSize path -> liftIO $ tryGetFileSize path
86
86
87data Effectful_Logging :: E.Effect where
87data Effectful_Logging :: E.Effect where
@@ -93,7 +93,7 @@ effectful_logMsg = E.send . Effectful_logMsg
93effectful_runLogging
93effectful_runLogging
94 :: E.Eff (Effectful_Logging : es) a
94 :: E.Eff (Effectful_Logging : es) a
95 -> E.Eff es (a, [String])
95 -> E.Eff es (a, [String])
96−effectful_runLogging = E.reinterpret (E.runState []) \case
96+effectful_runLogging = E.reinterpret (E.runState []) \_ -> \case
97 Effectful_logMsg msg -> E.modify (msg :)
97 Effectful_logMsg msg -> E.modify (msg :)
98
98
99----------
99----------
bench/Main.hs → effectful/bench/Main.hsrenamed+3−3
@@ -97,11 +97,11 @@ filesize n = bgroup (show n)
97#ifdef VERSION_eff
97#ifdef VERSION_eff
98 , bench "eff" $ nfAppIO eff_calculateFileSizesDeep (take n files)
98 , bench "eff" $ nfAppIO eff_calculateFileSizesDeep (take n files)
99#endif
99#endif
100−#ifdef VERSION_polysemy
101− , bench "polysemy" $ nfAppIO poly_calculateFileSizesDeep (take n files)
102−#endif
103#ifdef VERSION_mtl
100#ifdef VERSION_mtl
104 , bench "mtl" $ nfAppIO mtl_calculateFileSizesDeep (take n files)
101 , bench "mtl" $ nfAppIO mtl_calculateFileSizesDeep (take n files)
102+#endif
103+#ifdef VERSION_polysemy
104+ , bench "polysemy" $ nfAppIO poly_calculateFileSizesDeep (take n files)
105#endif
105#endif
106 ]
106 ]
107 ]
107 ]
bench/Unlift.hs → effectful/bench/Unlift.hsrenamed+14−15
@@ -3,19 +3,18 @@ module Unlift (unliftBenchmark) where
3
3
4#ifdef VERSION_criterion
4#ifdef VERSION_criterion
5import Criterion
5import Criterion
6−import Criterion.Main
7#endif
6#endif
8
7
9#ifdef VERSION_tasty_bench
8#ifdef VERSION_tasty_bench
10import Test.Tasty.Bench
9import Test.Tasty.Bench
11#endif
10#endif
12
11
13−import UnliftIO
12+import qualified UnliftIO as U
14
13
15import Effectful
14import Effectful
16import Effectful.State.Dynamic
15import Effectful.State.Dynamic
17import Utils
16import Utils
18−import qualified Effectful.Async as A
17+import qualified Effectful.Concurrent.Async as A
19
18
20unliftBenchmark :: Benchmark
19unliftBenchmark :: Benchmark
21unliftBenchmark = bgroup "unlifting"
20unliftBenchmark = bgroup "unlifting"
@@ -30,7 +29,7 @@ unliftBenchmark = bgroup "unlifting"
30 , bench "seq" $ nfAppIO runShallow benchDummy
29 , bench "seq" $ nfAppIO runShallow benchDummy
31 , shallowConc "conc" 1 benchDummyE benchDummy
30 , shallowConc "conc" 1 benchDummyE benchDummy
32 ]
31 ]
33− , shallowConc "async" 1 benchAsyncE benchAsync
32+ , shallowConc "async" 1 benchAsyncEff benchAsync
34 , shallowConc "concurrently" 2 benchConcurrentlyE benchConcurrently
33 , shallowConc "concurrently" 2 benchConcurrentlyE benchConcurrently
35 ]
34 ]
36 , bgroup "deep"
35 , bgroup "deep"
@@ -39,7 +38,7 @@ unliftBenchmark = bgroup "unlifting"
39 , bench "seq" $ nfAppIO runDeep benchDummy
38 , bench "seq" $ nfAppIO runDeep benchDummy
40 , deepConc "conc" 1 benchDummyE benchDummy
39 , deepConc "conc" 1 benchDummyE benchDummy
41 ]
40 ]
42− , deepConc "async" 1 benchAsyncE benchAsync
41+ , deepConc "async" 1 benchAsyncEff benchAsync
43 , deepConc "concurrently" 2 benchConcurrentlyE benchConcurrently
42 , deepConc "concurrently" 2 benchConcurrentlyE benchConcurrently
44 ]
43 ]
45 ]
44 ]
@@ -49,11 +48,11 @@ unliftBenchmark = bgroup "unlifting"
49shallowConc
48shallowConc
50 :: String
49 :: String
51 -> Int
50 -> Int
52− -> Eff '[A.AsyncE, IOE] ()
51+ -> Eff '[A.Concurrent, IOE] ()
53 -> Eff '[IOE] ()
52 -> Eff '[IOE] ()
54 -> Benchmark
53 -> Benchmark
55shallowConc name n r f = bgroup name
54shallowConc name n r f = bgroup name
56− [ bench "AsyncE" $ nfAppIO (runShallow . A.runAsyncE) r
55+ [ bench "Async" $ nfAppIO (runShallow . A.runConcurrent) r
57 , bench "ephemeral/limited" $ nfAppIO
56 , bench "ephemeral/limited" $ nfAppIO
58 (runShallow . withUnliftStrategy (ConcUnlift Ephemeral $ Limited n)) f
57 (runShallow . withUnliftStrategy (ConcUnlift Ephemeral $ Limited n)) f
59 , bench "ephemeral/unlimited" $ nfAppIO
58 , bench "ephemeral/unlimited" $ nfAppIO
@@ -67,7 +66,7 @@ shallowConc name n r f = bgroup name
67deepConc
66deepConc
68 :: String
67 :: String
69 -> Int
68 -> Int
70− -> Eff '[ A.AsyncE
69+ -> Eff '[ A.Concurrent
71 , State (), State (), State (), State (), State ()
70 , State (), State (), State (), State (), State ()
72 , State (), State (), State (), State (), State ()
71 , State (), State (), State (), State (), State ()
73 , IOE] ()
72 , IOE] ()
@@ -76,7 +75,7 @@ deepConc
76 , IOE] ()
75 , IOE] ()
77 -> Benchmark
76 -> Benchmark
78deepConc name n r f = bgroup name
77deepConc name n r f = bgroup name
79− [ bench "AsyncE" $ nfAppIO (runDeep . A.runAsyncE) r
78+ [ bench "Async" $ nfAppIO (runDeep . A.runConcurrent) r
80 , bench "ephemeral/limited" $ nfAppIO
79 , bench "ephemeral/limited" $ nfAppIO
81 (runDeep . withUnliftStrategy (ConcUnlift Ephemeral $ Limited n)) f
80 (runDeep . withUnliftStrategy (ConcUnlift Ephemeral $ Limited n)) f
82 , bench "ephemeral/unlimited" $ nfAppIO
81 , bench "ephemeral/unlimited" $ nfAppIO
@@ -93,19 +92,19 @@ benchDummy :: MonadUnliftIO m => m ()
93benchDummy = withRunInIO $ \runIO -> runIO $ pure ()
92benchDummy = withRunInIO $ \runIO -> runIO $ pure ()
94
93
95benchAsync :: MonadUnliftIO m => m ()
94benchAsync :: MonadUnliftIO m => m ()
96−benchAsync = withAsync (pure ()) wait
95+benchAsync = U.withAsync (pure ()) U.wait
97
96
98benchConcurrently :: MonadUnliftIO m => m ()
97benchConcurrently :: MonadUnliftIO m => m ()
99−benchConcurrently = concurrently_ (pure ()) (pure ())
98+benchConcurrently = U.concurrently_ (pure ()) (pure ())
100
99
101benchDummyE :: Eff es ()
100benchDummyE :: Eff es ()
102benchDummyE = pure ()
101benchDummyE = pure ()
103{-# NOINLINE benchDummyE #-}
102{-# NOINLINE benchDummyE #-}
104
103
105−benchAsyncE :: A.AsyncE :> es => Eff es ()
104+benchAsyncEff :: A.Concurrent :> es => Eff es ()
106−benchAsyncE = A.withAsync (pure ()) A.wait
105+benchAsyncEff = A.withAsync (pure ()) A.wait
107−{-# NOINLINE benchAsyncE #-}
106+{-# NOINLINE benchAsyncEff #-}
108
107
109−benchConcurrentlyE :: A.AsyncE :> es => Eff es ()
108+benchConcurrentlyE :: A.Concurrent :> es => Eff es ()
110benchConcurrentlyE = A.concurrently_ (pure ()) (pure ())
109benchConcurrentlyE = A.concurrently_ (pure ()) (pure ())
111{-# NOINLINE benchConcurrentlyE #-}
110{-# NOINLINE benchConcurrentlyE #-}
bench/Utils.hs → effectful/bench/Utils.hsrenamed

The content is the same.

effectful/effectful.cabalnew file+176
@@ -0,0 +1,176 @@
1+cabal-version: 2.4
2+build-type: Simple
3+name: effectful
4+version: 0.1
5+license: BSD-3-Clause
6+license-file: LICENSE
7+category: Control
8+maintainer: andrzej@rybczak.net
9+author: Andrzej Rybczak
10+synopsis: An easy to use, performant extensible effects library.
11+
12+description: An easy to use, performant extensible effects library with seamless
13+ integration with the existing Haskell ecosystem. See the main
14+ module "Effectful" for the documentation.
15+ .
16+ This is the "batteries-included" variant with many dependencies;
17+ See the @<https://hackage.haskell.org/package/effectful-core
18+ effectful-core>@ package and other @effectful-*@ packages if you
19+ need a more limited dependency footprint.
20+
21+extra-source-files: CHANGELOG.md
22+
23+tested-with: GHC ==8.8.4 || ==8.10.7 || ==9.2.1
24+
25+bug-reports: https://github.com/arybczak/effectful/issues
26+source-repository head
27+ type: git
28+ location: https://github.com/arybczak/effectful.git
29+
30+flag benchmark-foreign-libraries
31+ description: Include other effect libraries in the benchmarks.
32+ default: False
33+
34+common language
35+ ghc-options: -Wall -Wcompat
36+
37+ default-language: Haskell2010
38+
39+ default-extensions: BangPatterns
40+ ConstraintKinds
41+ DataKinds
42+ DeriveFunctor
43+ DeriveGeneric
44+ FlexibleContexts
45+ FlexibleInstances
46+ GADTs
47+ GeneralizedNewtypeDeriving
48+ LambdaCase
49+ MultiParamTypeClasses
50+ NoStarIsType
51+ RankNTypes
52+ RecordWildCards
53+ RoleAnnotations
54+ ScopedTypeVariables
55+ StandaloneDeriving
56+ TupleSections
57+ TypeApplications
58+ TypeFamilies
59+ TypeOperators
60+
61+library
62+ import: language
63+
64+ build-depends: base >= 4.13 && < 5
65+ , async >= 2.2.2
66+ , directory >= 1.3.2
67+ , effectful-core >= 0.1 && < 0.1.1
68+ , process >= 1.6.9
69+ , resourcet >= 1.2.4.3
70+ , time >= 1.9.2
71+ , stm >= 2.5.0.0
72+ , unliftio >= 0.2.20
73+
74+ hs-source-dirs: src
75+
76+ exposed-modules: Effectful.Concurrent
77+ Effectful.Concurrent.Async
78+ Effectful.Concurrent.Chan
79+ Effectful.Concurrent.MVar
80+ Effectful.Concurrent.STM
81+ Effectful.Concurrent.QSem
82+ Effectful.Concurrent.QSemN
83+ Effectful.Environment
84+ Effectful.FileSystem
85+ Effectful.FileSystem.IO
86+ Effectful.Process
87+ Effectful.Resource
88+ Effectful.Temporary
89+ Effectful.Timeout
90+
91+ other-modules: Effectful.Concurrent.Effect
92+ Effectful.FileSystem.Effect
93+
94+ reexported-modules: Effectful
95+ , Effectful.Dispatch.Dynamic
96+ , Effectful.Dispatch.Static
97+ , Effectful.Error
98+ , Effectful.Error.Dynamic
99+ , Effectful.Fail
100+ , Effectful.Monad
101+ , Effectful.Prim
102+ , Effectful.Reader
103+ , Effectful.Reader.Dynamic
104+ , Effectful.State.Dynamic
105+ , Effectful.State.Local
106+ , Effectful.State.Shared
107+ , Effectful.Writer.Dynamic
108+ , Effectful.Writer.Local
109+ , Effectful.Writer.Shared
110+
111+test-suite test
112+ import: language
113+
114+ ghc-options: -threaded -rtsopts -with-rtsopts=-N4
115+
116+ build-depends: base
117+ , containers
118+ , effectful
119+ , effectful-core
120+ , exceptions
121+ , lifted-base
122+ , tasty
123+ , tasty-hunit
124+ , unliftio
125+
126+ hs-source-dirs: tests examples
127+
128+ type: exitcode-stdio-1.0
129+ main-is: Main.hs
130+
131+ other-modules: AsyncTests
132+ ConcurrencyTests
133+ EnvironmentTests
134+ ErrorTests
135+ StateTests
136+ TimeoutTests
137+ UnliftTests
138+ Utils
139+ -- These are examples; We do not actually run them but list
140+ -- them here in order to check if they compile.
141+ FileSystem
142+
143+benchmark bench
144+ import: language
145+
146+ ghc-options: -threaded -rtsopts -with-rtsopts=-T
147+
148+ if flag(benchmark-foreign-libraries)
149+ build-depends: mtl
150+
151+ if impl(ghc < 9)
152+ build-depends: freer-simple
153+
154+ if impl(ghc < 9.2)
155+ build-depends: fused-effects
156+
157+ if impl(ghc < 9.3)
158+ build-depends: polysemy
159+
160+ build-depends: base
161+ , async
162+ , effectful
163+ , tasty-bench
164+ , unix
165+ , unliftio
166+
167+ hs-source-dirs: bench
168+
169+ type: exitcode-stdio-1.0
170+ main-is: Main.hs
171+
172+ other-modules: Concurrency
173+ Countdown
174+ FileSizes
175+ Unlift
176+ Utils
examples/FileSystem.hs → effectful/examples/FileSystem.hsrenamed+5−6
@@ -9,14 +9,13 @@ module FileSystem
9
9
10import Control.Exception (IOException)
10import Control.Exception (IOException)
11import Control.Monad.Catch
11import Control.Monad.Catch
12−import Control.Monad.IO.Class
13import Prelude hiding (readFile, writeFile)
12import Prelude hiding (readFile, writeFile)
14import qualified Data.Map.Strict as M
13import qualified Data.Map.Strict as M
15import qualified System.IO as IO
14import qualified System.IO as IO
16
15
17import Effectful
16import Effectful
18import Effectful.Error
17import Effectful.Error
19−import Effectful.State
18+import Effectful.State.Local
20
19
21-- | An effect for reading and writing files.
20-- | An effect for reading and writing files.
22data FileSystem :: Effect where
21data FileSystem :: Effect where
@@ -30,11 +29,11 @@ newtype FsError = FsError String
30-- Operations
29-- Operations
31
30
32-- | Read contents of a file.
31-- | Read contents of a file.
33−readFile :: FileSystem :> es => FilePath -> Eff es String
32+readFile :: (HasCallStack, FileSystem :> es) => FilePath -> Eff es String
34readFile = send . ReadFile
33readFile = send . ReadFile
35
34
36-- | Write contents to a file.
35-- | Write contents to a file.
37−writeFile :: FileSystem :> es => FilePath -> String -> Eff es ()
36+writeFile :: (HasCallStack, FileSystem :> es) => FilePath -> String -> Eff es ()
38writeFile path = send . WriteFile path
37writeFile path = send . WriteFile path
39
38
40----------------------------------------
39----------------------------------------
@@ -44,7 +43,7 @@ runFileSystemIO
44 :: (IOE :> es, Error FsError :> es)
43 :: (IOE :> es, Error FsError :> es)
45 => Eff (FileSystem : es) a
44 => Eff (FileSystem : es) a
46 -> Eff es a
45 -> Eff es a
47−runFileSystemIO = interpret $ \case
46+runFileSystemIO = interpret $ \_ -> \case
48 ReadFile path -> adapt $ IO.readFile path
47 ReadFile path -> adapt $ IO.readFile path
49 WriteFile path contents -> adapt $ IO.writeFile path contents
48 WriteFile path contents -> adapt $ IO.writeFile path contents
50 where
49 where
@@ -55,7 +54,7 @@ runFileSystemPure
55 => M.Map FilePath String
54 => M.Map FilePath String
56 -> Eff (FileSystem : es) a
55 -> Eff (FileSystem : es) a
57 -> Eff es a
56 -> Eff es a
58−runFileSystemPure fs0 = reinterpret (evalState fs0) $ \case
57+runFileSystemPure fs0 = reinterpret (evalState fs0) $ \_ -> \case
59 ReadFile path -> gets (M.lookup path) >>= \case
58 ReadFile path -> gets (M.lookup path) >>= \case
60 Just contents -> pure contents
59 Just contents -> pure contents
61 Nothing -> throwError . FsError $ "File not found: " ++ show path
60 Nothing -> throwError . FsError $ "File not found: " ++ show path
effectful/src/Effectful/Concurrent.hsnew file+218
@@ -0,0 +1,218 @@
1+-- | Lifted version of "Control.Concurrent".
2+--
3+-- For functions that spawn threads, the order of preference for their usage is
4+-- recommended as follows:
5+--
6+-- 1) High level functions from "Effectful.Concurrent.Async" such as
7+-- 'Effectful.Concurrent.Async.withAsync',
8+-- 'Effectful.Concurrent.Async.concurrently' or
9+-- 'Effectful.Concurrent.Async.mapConcurrently'.
10+--
11+-- 2) Low level functions from "Effectful.Concurrent.Async" such as
12+-- 'Effectful.Concurrent.Async.async'.
13+--
14+-- 3) Low level functions from "Effectful.Concurrent" such as 'forkIO'.
15+module Effectful.Concurrent
16+ ( Concurrent
17+ , runConcurrent
18+
19+ -- * Basic concurrency operations
20+ , myThreadId
21+ , forkIO
22+ , forkFinally
23+ , forkIOWithUnmask
24+ , killThread
25+ , throwTo
26+
27+ -- ** Threads with affinity
28+ , forkOn
29+ , forkOnWithUnmask
30+ , getNumCapabilities
31+ , setNumCapabilities
32+ , getNumProcessors
33+ , threadCapability
34+
35+ -- * Scheduling
36+ , yield
37+
38+ -- ** Waiting
39+ , threadDelay
40+ , threadWaitRead
41+ , threadWaitWrite
42+ , threadWaitReadSTM
43+ , threadWaitWriteSTM
44+
45+ -- * Bound threads
46+ , forkOS
47+ , forkOSWithUnmask
48+ , isCurrentThreadBound
49+ , runInBoundThread
50+ , runInUnboundThread
51+
52+ -- * Weak references to ThreadIds
53+ , mkWeakThreadId
54+
55+ -- * Re-exports
56+ , C.rtsSupportsBoundThreads
57+ ) where
58+
59+import Control.Exception (Exception, SomeException)
60+import Data.Bifunctor (second)
61+import System.Mem.Weak (Weak)
62+import System.Posix.Types (Fd)
63+import UnliftIO.STM (STM)
64+import qualified Control.Concurrent as C
65+import qualified GHC.Conc as GHC
66+
67+import Effectful.Concurrent.Effect
68+import Effectful.Dispatch.Static
69+import Effectful.Monad
70+
71+----------------------------------------
72+-- Basic concurrency operations
73+
74+-- | Lifted 'C.myThreadId'.
75+myThreadId :: Concurrent :> es => Eff es C.ThreadId
76+myThreadId = unsafeEff_ C.myThreadId
77+
78+-- | Lifted 'C.forkIO'.
79+forkIO :: Concurrent :> es => Eff es () -> Eff es C.ThreadId
80+forkIO k = unsafeEff $ \es -> do
81+ esF <- cloneEnv es
82+ C.forkIO $ unEff k esF
83+
84+-- | Lifted 'C.forkFinally'.
85+forkFinally
86+ :: Concurrent :> es
87+ => Eff es a
88+ -> (Either SomeException a -> Eff es ())
89+ -> Eff es C.ThreadId
90+forkFinally k cleanup = unsafeEff $ \es -> do
91+ esF <- cloneEnv es
92+ C.forkFinally (unEff k esF) ((`unEff` esF) . cleanup)
93+
94+-- | Lifted 'C.forkIOWithUnmask'.
95+forkIOWithUnmask
96+ :: Concurrent :> es
97+ => ((forall a es'. IOE :> es' => Eff es' a -> Eff es' a)
98+ -> Eff es ())
99+ -> Eff es C.ThreadId
100+forkIOWithUnmask f = unsafeEff $ \es -> do
101+ esF <- cloneEnv es
102+ C.forkIOWithUnmask (\restore -> unEff (f (unsafeLiftMapIO restore)) esF)
103+
104+-- | Lifted 'C.killThread'.
105+killThread :: Concurrent :> es => C.ThreadId -> Eff es ()
106+killThread = unsafeEff_ . C.killThread
107+
108+-- | Lifted 'C.throwTo'.
109+throwTo :: (Concurrent :> es, Exception e) => C.ThreadId -> e -> Eff es ()
110+throwTo tid = unsafeEff_ . C.throwTo tid
111+
112+----------------------------------------
113+-- Threads with affinity
114+
115+-- | Lifted 'C.forkOn'.
116+forkOn :: Concurrent :> es => Int -> Eff es () -> Eff es C.ThreadId
117+forkOn n k = unsafeEff $ \es -> do
118+ esF <- cloneEnv es
119+ C.forkOn n (unEff k esF)
120+
121+-- | Lifted 'C.forkOnWithUnmask'.
122+forkOnWithUnmask
123+ :: Concurrent :> es
124+ => Int
125+ -> ((forall a es'. IOE :> es' => Eff es' a -> Eff es' a) -> Eff es ())
126+ -> Eff es C.ThreadId
127+forkOnWithUnmask n f = unsafeEff $ \es -> do
128+ esF <- cloneEnv es
129+ C.forkOnWithUnmask n (\restore -> unEff (f (unsafeLiftMapIO restore)) esF)
130+
131+-- | Lifted 'C.getNumCapabilities'.
132+getNumCapabilities :: Concurrent :> es => Eff es Int
133+getNumCapabilities = unsafeEff_ C.getNumCapabilities
134+
135+-- | Lifted 'C.setNumCapabilities'.
136+setNumCapabilities :: Concurrent :> es => Int -> Eff es ()
137+setNumCapabilities = unsafeEff_ . C.setNumCapabilities
138+
139+-- | Lifted 'GHC.getNumProcessors'.
140+getNumProcessors :: Concurrent :> es => Eff es Int
141+getNumProcessors = unsafeEff_ GHC.getNumProcessors
142+
143+-- | Lifted 'C.threadCapability'.
144+threadCapability :: Concurrent :> es => C.ThreadId -> Eff es (Int, Bool)
145+threadCapability = unsafeEff_ . C.threadCapability
146+
147+----------------------------------------
148+-- Scheduling
149+
150+-- | Lifted 'C.yield'.
151+yield :: Concurrent :> es => Eff es ()
152+yield = unsafeEff_ C.yield
153+
154+----------------------------------------
155+-- Waiting
156+
157+-- | Lifted 'C.threadDelay'.
158+threadDelay :: Concurrent :> es => Int -> Eff es ()
159+threadDelay = unsafeEff_ . C.threadDelay
160+
161+-- | Lifted 'C.threadWaitRead'.
162+threadWaitRead :: Concurrent :> es => Fd -> Eff es ()
163+threadWaitRead = unsafeEff_ . C.threadWaitRead
164+
165+-- | Lifted 'C.threadWaitWrite'.
166+threadWaitWrite :: Concurrent :> es => Fd -> Eff es ()
167+threadWaitWrite = unsafeEff_ . C.threadWaitWrite
168+
169+-- | Lifted 'C.threadWaitReadSTM'.
170+threadWaitReadSTM :: Concurrent :> es => Fd -> Eff es (STM (), Eff es ())
171+threadWaitReadSTM fd = unsafeEff_ $ do
172+ second unsafeEff_ <$> C.threadWaitReadSTM fd
173+
174+-- | Lifted 'C.threadWaitWriteSTM'.
175+threadWaitWriteSTM :: Concurrent :> es => Fd -> Eff es (STM (), Eff es ())
176+threadWaitWriteSTM fd = unsafeEff_ $ do
177+ second unsafeEff_ <$> C.threadWaitWriteSTM fd
178+
179+----------------------------------------
180+-- Bound threads
181+
182+-- | Lifted 'C.forkOS'.
183+forkOS :: Concurrent :> es => Eff es () -> Eff es C.ThreadId
184+forkOS k = unsafeEff $ \es -> do
185+ esF <- cloneEnv es
186+ C.forkOS $ unEff k esF
187+
188+-- | Lifted 'E.forkOSWithUnmask'.
189+forkOSWithUnmask
190+ :: Concurrent :> es
191+ => ((forall a es'. IOE :> es' => Eff es' a -> Eff es' a) -> Eff es ())
192+ -> Eff es C.ThreadId
193+forkOSWithUnmask f = unsafeEff $ \es -> do
194+ esF <- cloneEnv es
195+ C.forkOSWithUnmask (\restore -> unEff (f (unsafeLiftMapIO restore)) esF)
196+
197+-- | Lifted 'C.isCurrentThreadBound'.
198+isCurrentThreadBound :: Concurrent :> es => Eff es Bool
199+isCurrentThreadBound = unsafeEff_ C.isCurrentThreadBound
200+
201+-- | Lifted 'C.runInBoundThread'.
202+runInBoundThread :: Concurrent :> es => Eff es a -> Eff es a
203+runInBoundThread k = unsafeEff $ \es -> do
204+ esF <- cloneEnv es
205+ C.runInBoundThread $ unEff k esF
206+
207+-- | Lifted 'C.runInUnboundThread'.
208+runInUnboundThread :: Concurrent :> es => Eff es a -> Eff es a
209+runInUnboundThread k = unsafeEff $ \es -> do
210+ esF <- cloneEnv es
211+ C.runInUnboundThread $ unEff k esF
212+
213+----------------------------------------
214+-- Weak references to ThreadIds
215+
216+-- | Lifted 'C.mkWeakThreadId'.
217+mkWeakThreadId :: Concurrent :> es => C.ThreadId -> Eff es (Weak C.ThreadId)
218+mkWeakThreadId = unsafeEff_ . C.mkWeakThreadId
src/Effectful/Async.hs → effectful/src/Effectful/Concurrent/Async.hsrenamed+73−87
@@ -1,8 +1,8 @@
1{-# LANGUAGE UndecidableInstances #-}
1{-# LANGUAGE UndecidableInstances #-}
2+-- | Lifted version of "Control.Concurrent.Async".
2−module Effectful.Async
3+module Effectful.Concurrent.Async
3− ( -- * Async effect
4+ ( Concurrent
4− AsyncE
5+ , runConcurrent
5− , runAsyncE
6
6
7 -- * Asynchronous actions
7 -- * Asynchronous actions
8 , Async
8 , Async
@@ -76,49 +76,37 @@ import Control.Concurrent (threadDelay)
76import Control.Concurrent.Async (Async)
76import Control.Concurrent.Async (Async)
77import Control.Exception (Exception, SomeException)
77import Control.Exception (Exception, SomeException)
78import Control.Monad (forever)
78import Control.Monad (forever)
79+import Data.Kind (Type)
79import qualified Control.Concurrent.Async as A
80import qualified Control.Concurrent.Async as A
80import qualified UnliftIO.Async as U
81import qualified UnliftIO.Async as U
81import qualified UnliftIO.Internals.Async as I
82import qualified UnliftIO.Internals.Async as I
82
83
83−import Effectful.Internal.Effect
84+import Effectful.Concurrent.Effect
84−import Effectful.Internal.Env
85+import Effectful.Dispatch.Static
85−import Effectful.Internal.Monad
86+import Effectful.Monad
86−
87−-- | Run 'Eff' operations asynchronously via the @async@ library.
88−--
89−-- /Note:/ thread local state changes in 'Eff' operations run asynchronously
90−-- will not affect the parent thread.
91−data AsyncE :: Effect where
92− AsyncE :: AsyncE m r
93−
94−runAsyncE :: IOE :> es => Eff (AsyncE : es) a -> Eff es a
95−runAsyncE = evalEffect (IdE AsyncE)
96−
97−----------------------------------------
98−-- Operations
99
87
100-- | Lifted 'A.async'.
88-- | Lifted 'A.async'.
101−async :: AsyncE :> es => Eff es a -> Eff es (Async a)
89+async :: Concurrent :> es => Eff es a -> Eff es (Async a)
102async = liftAsync A.async
90async = liftAsync A.async
103
91
104-- | Lifted 'A.asyncBound'.
92-- | Lifted 'A.asyncBound'.
105−asyncBound :: AsyncE :> es => Eff es a -> Eff es (Async a)
93+asyncBound :: Concurrent :> es => Eff es a -> Eff es (Async a)
106asyncBound = liftAsync A.asyncBound
94asyncBound = liftAsync A.asyncBound
107
95
108-- | Lifted 'A.asyncOn'.
96-- | Lifted 'A.asyncOn'.
109−asyncOn :: AsyncE :> es => Int -> Eff es a -> Eff es (Async a)
97+asyncOn :: Concurrent :> es => Int -> Eff es a -> Eff es (Async a)
110asyncOn cpu = liftAsync (A.asyncOn cpu)
98asyncOn cpu = liftAsync (A.asyncOn cpu)
111
99
112-- | Lifted 'A.asyncWithUnmask'.
100-- | Lifted 'A.asyncWithUnmask'.
113asyncWithUnmask
101asyncWithUnmask
114− :: AsyncE :> es
102+ :: Concurrent :> es
115 => ((forall b. Eff es b -> Eff es b) -> Eff es a)
103 => ((forall b. Eff es b -> Eff es b) -> Eff es a)
116 -> Eff es (Async a)
104 -> Eff es (Async a)
117asyncWithUnmask = liftAsyncWithUnmask A.asyncWithUnmask
105asyncWithUnmask = liftAsyncWithUnmask A.asyncWithUnmask
118
106
119-- | Lifted 'A.asyncOnWithUnmask'.
107-- | Lifted 'A.asyncOnWithUnmask'.
120asyncOnWithUnmask
108asyncOnWithUnmask
121− :: AsyncE :> es
109+ :: Concurrent :> es
122 => Int
110 => Int
123 -> ((forall b. Eff es b -> Eff es b) -> Eff es a)
111 -> ((forall b. Eff es b -> Eff es b) -> Eff es a)
124 -> Eff es (Async a)
112 -> Eff es (Async a)
@@ -126,7 +114,7 @@ asyncOnWithUnmask cpu = liftAsyncWithUnmask (A.asyncOnWithUnmask cpu)
126
114
127-- | Lifted 'A.withAsync'.
115-- | Lifted 'A.withAsync'.
128withAsync
116withAsync
129− :: AsyncE :> es
117+ :: Concurrent :> es
130 => Eff es a
118 => Eff es a
131 -> (Async a -> Eff es b)
119 -> (Async a -> Eff es b)
132 -> Eff es b
120 -> Eff es b
@@ -134,7 +122,7 @@ withAsync = liftWithAsync A.withAsync
134
122
135-- | Lifted 'A.withAsyncBound'.
123-- | Lifted 'A.withAsyncBound'.
136withAsyncBound
124withAsyncBound
137− :: AsyncE :> es
125+ :: Concurrent :> es
138 => Eff es a
126 => Eff es a
139 -> (Async a -> Eff es b)
127 -> (Async a -> Eff es b)
140 -> Eff es b
128 -> Eff es b
@@ -142,7 +130,7 @@ withAsyncBound = liftWithAsync A.withAsyncBound
142
130
143-- | Lifted 'A.withAsyncOn'.
131-- | Lifted 'A.withAsyncOn'.
144withAsyncOn
132withAsyncOn
145− :: AsyncE :> es
133+ :: Concurrent :> es
146 => Int
134 => Int
147 -> Eff es a
135 -> Eff es a
148 -> (Async a -> Eff es b)
136 -> (Async a -> Eff es b)
@@ -151,7 +139,7 @@ withAsyncOn cpu = liftWithAsync (A.withAsyncOn cpu)
151
139
152-- | Lifted 'A.withAsyncWithUnmask'.
140-- | Lifted 'A.withAsyncWithUnmask'.
153withAsyncWithUnmask
141withAsyncWithUnmask
154− :: AsyncE :> es
142+ :: Concurrent :> es
155 => ((forall c. Eff es c -> Eff es c) -> Eff es a)
143 => ((forall c. Eff es c -> Eff es c) -> Eff es a)
156 -> (Async a -> Eff es b)
144 -> (Async a -> Eff es b)
157 -> Eff es b
145 -> Eff es b
@@ -159,7 +147,7 @@ withAsyncWithUnmask = liftWithAsyncWithUnmask A.withAsyncWithUnmask
159
147
160-- | Lifted 'A.withAsyncOnWithUnmask'.
148-- | Lifted 'A.withAsyncOnWithUnmask'.
161withAsyncOnWithUnmask
149withAsyncOnWithUnmask
162− :: AsyncE :> es
150+ :: Concurrent :> es
163 => Int
151 => Int
164 -> ((forall c. Eff es c -> Eff es c) -> Eff es a)
152 -> ((forall c. Eff es c -> Eff es c) -> Eff es a)
165 -> (Async a -> Eff es b)
153 -> (Async a -> Eff es b)
@@ -167,60 +155,60 @@ withAsyncOnWithUnmask
167withAsyncOnWithUnmask cpu = liftWithAsyncWithUnmask (A.withAsyncOnWithUnmask cpu)
155withAsyncOnWithUnmask cpu = liftWithAsyncWithUnmask (A.withAsyncOnWithUnmask cpu)
168
156
169-- | Lifted 'A.wait'.
157-- | Lifted 'A.wait'.
170−wait :: AsyncE :> es => Async a -> Eff es a
158+wait :: Concurrent :> es => Async a -> Eff es a
171wait = unsafeEff_ . A.wait
159wait = unsafeEff_ . A.wait
172
160
173-- | Lifted 'A.poll'.
161-- | Lifted 'A.poll'.
174poll
162poll
175− :: AsyncE :> es
163+ :: Concurrent :> es
176 => Async a
164 => Async a
177 -> Eff es (Maybe (Either SomeException a))
165 -> Eff es (Maybe (Either SomeException a))
178poll = unsafeEff_ . A.poll
166poll = unsafeEff_ . A.poll
179
167
180-- | Lifted 'A.cancel'.
168-- | Lifted 'A.cancel'.
181−cancel :: AsyncE :> es => Async a -> Eff es ()
169+cancel :: Concurrent :> es => Async a -> Eff es ()
182cancel = unsafeEff_ . A.cancel
170cancel = unsafeEff_ . A.cancel
183
171
184-- | Lifted 'A.cancelWith'.
172-- | Lifted 'A.cancelWith'.
185−cancelWith :: (Exception e, AsyncE :> es) => Async a -> e -> Eff es ()
173+cancelWith :: (Exception e, Concurrent :> es) => Async a -> e -> Eff es ()
186cancelWith a = unsafeEff_ . A.cancelWith a
174cancelWith a = unsafeEff_ . A.cancelWith a
187
175
188-- | Lifted 'A.uninterruptibleCancel'.
176-- | Lifted 'A.uninterruptibleCancel'.
189−uninterruptibleCancel :: AsyncE :> es => Async a -> Eff es ()
177+uninterruptibleCancel :: Concurrent :> es => Async a -> Eff es ()
190uninterruptibleCancel = unsafeEff_ . A.uninterruptibleCancel
178uninterruptibleCancel = unsafeEff_ . A.uninterruptibleCancel
191
179
192-- | Lifted 'A.waitCatch'.
180-- | Lifted 'A.waitCatch'.
193waitCatch
181waitCatch
194− :: AsyncE :> es
182+ :: Concurrent :> es
195 => Async a
183 => Async a
196 -> Eff es (Either SomeException a)
184 -> Eff es (Either SomeException a)
197waitCatch = unsafeEff_ . A.waitCatch
185waitCatch = unsafeEff_ . A.waitCatch
198
186
199-- | Lifted 'A.waitAny'.
187-- | Lifted 'A.waitAny'.
200−waitAny :: AsyncE :> es => [Async a] -> Eff es (Async a, a)
188+waitAny :: Concurrent :> es => [Async a] -> Eff es (Async a, a)
201waitAny = unsafeEff_ . A.waitAny
189waitAny = unsafeEff_ . A.waitAny
202
190
203-- | Lifted 'A.waitAnyCatch'.
191-- | Lifted 'A.waitAnyCatch'.
204waitAnyCatch
192waitAnyCatch
205− :: AsyncE :> es
193+ :: Concurrent :> es
206 => [Async a]
194 => [Async a]
207 -> Eff es (Async a, Either SomeException a)
195 -> Eff es (Async a, Either SomeException a)
208waitAnyCatch = unsafeEff_ . A.waitAnyCatch
196waitAnyCatch = unsafeEff_ . A.waitAnyCatch
209
197
210-- | Lifted 'A.waitAnyCancel'.
198-- | Lifted 'A.waitAnyCancel'.
211−waitAnyCancel :: AsyncE :> es => [Async a] -> Eff es (Async a, a)
199+waitAnyCancel :: Concurrent :> es => [Async a] -> Eff es (Async a, a)
212waitAnyCancel = unsafeEff_ . A.waitAnyCancel
200waitAnyCancel = unsafeEff_ . A.waitAnyCancel
213
201
214-- | Lifted 'A.waitAnyCatchCancel'.
202-- | Lifted 'A.waitAnyCatchCancel'.
215waitAnyCatchCancel
203waitAnyCatchCancel
216− :: AsyncE :> es
204+ :: Concurrent :> es
217 => [Async a]
205 => [Async a]
218 -> Eff es (Async a, Either SomeException a)
206 -> Eff es (Async a, Either SomeException a)
219waitAnyCatchCancel = unsafeEff_ . A.waitAnyCatchCancel
207waitAnyCatchCancel = unsafeEff_ . A.waitAnyCatchCancel
220
208
221-- | Lifted 'A.waitEither'.
209-- | Lifted 'A.waitEither'.
222waitEither
210waitEither
223− :: AsyncE :> es
211+ :: Concurrent :> es
224 => Async a
212 => Async a
225 -> Async b
213 -> Async b
226 -> Eff es (Either a b)
214 -> Eff es (Either a b)
@@ -228,7 +216,7 @@ waitEither a b = unsafeEff_ $ A.waitEither a b
228
216
229-- | Lifted 'A.waitEitherCatch'.
217-- | Lifted 'A.waitEitherCatch'.
230waitEitherCatch
218waitEitherCatch
231− :: AsyncE :> es
219+ :: Concurrent :> es
232 => Async a
220 => Async a
233 -> Async b
221 -> Async b
234 -> Eff es (Either (Either SomeException a) (Either SomeException b))
222 -> Eff es (Either (Either SomeException a) (Either SomeException b))
@@ -236,7 +224,7 @@ waitEitherCatch a b = unsafeEff_ $ A.waitEitherCatch a b
236
224
237-- | Lifted 'A.waitEitherCancel'.
225-- | Lifted 'A.waitEitherCancel'.
238waitEitherCancel
226waitEitherCancel
239− :: AsyncE :> es
227+ :: Concurrent :> es
240 => Async a
228 => Async a
241 -> Async b
229 -> Async b
242 -> Eff es (Either a b)
230 -> Eff es (Either a b)
@@ -244,53 +232,53 @@ waitEitherCancel a b = unsafeEff_ $ A.waitEitherCancel a b
244
232
245-- | Lifted 'A.waitEitherCatchCancel'.
233-- | Lifted 'A.waitEitherCatchCancel'.
246waitEitherCatchCancel
234waitEitherCatchCancel
247− :: AsyncE :> es
235+ :: Concurrent :> es
248 => Async a
236 => Async a
249 -> Async b
237 -> Async b
250 -> Eff es (Either (Either SomeException a) (Either SomeException b))
238 -> Eff es (Either (Either SomeException a) (Either SomeException b))
251waitEitherCatchCancel a b = unsafeEff_ $ A.waitEitherCatch a b
239waitEitherCatchCancel a b = unsafeEff_ $ A.waitEitherCatch a b
252
240
253-- | Lifted 'A.waitEither_'.
241-- | Lifted 'A.waitEither_'.
254−waitEither_ :: AsyncE :> es => Async a -> Async b -> Eff es ()
242+waitEither_ :: Concurrent :> es => Async a -> Async b -> Eff es ()
255waitEither_ a b = unsafeEff_ $ A.waitEither_ a b
243waitEither_ a b = unsafeEff_ $ A.waitEither_ a b
256
244
257-- | Lifted 'A.waitBoth'.
245-- | Lifted 'A.waitBoth'.
258−waitBoth :: AsyncE :> es => Async a -> Async b -> Eff es (a, b)
246+waitBoth :: Concurrent :> es => Async a -> Async b -> Eff es (a, b)
259waitBoth a b = unsafeEff_ $ A.waitBoth a b
247waitBoth a b = unsafeEff_ $ A.waitBoth a b
260
248
261-- | Lifted 'A.link'.
249-- | Lifted 'A.link'.
262−link :: AsyncE :> es => Async a -> Eff es ()
250+link :: Concurrent :> es => Async a -> Eff es ()
263link = unsafeEff_ . A.link
251link = unsafeEff_ . A.link
264
252
265-- | Lifted 'A.linkOnly'.
253-- | Lifted 'A.linkOnly'.
266−linkOnly :: AsyncE :> es => (SomeException -> Bool) -> Async a -> Eff es ()
254+linkOnly :: Concurrent :> es => (SomeException -> Bool) -> Async a -> Eff es ()
267linkOnly f = unsafeEff_ . A.linkOnly f
255linkOnly f = unsafeEff_ . A.linkOnly f
268
256
269-- | Lifted 'A.link2'.
257-- | Lifted 'A.link2'.
270−link2 :: AsyncE :> es => Async a -> Async b -> Eff es ()
258+link2 :: Concurrent :> es => Async a -> Async b -> Eff es ()
271link2 a b = unsafeEff_ $ A.link2 a b
259link2 a b = unsafeEff_ $ A.link2 a b
272
260
273-- | Lifted 'A.link2Only'.
261-- | Lifted 'A.link2Only'.
274−link2Only :: AsyncE :> es => (SomeException -> Bool) -> Async a -> Async b -> Eff es ()
262+link2Only :: Concurrent :> es => (SomeException -> Bool) -> Async a -> Async b -> Eff es ()
275link2Only f a b = unsafeEff_ $ A.link2Only f a b
263link2Only f a b = unsafeEff_ $ A.link2Only f a b
276
264
277-- | Lifted 'A.race'.
265-- | Lifted 'A.race'.
278−race :: AsyncE :> es => Eff es a -> Eff es b -> Eff es (Either a b)
266+race :: Concurrent :> es => Eff es a -> Eff es b -> Eff es (Either a b)
279race ma mb = unsafeEff $ \es -> do
267race ma mb = unsafeEff $ \es -> do
280 A.race (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
268 A.race (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
281
269
282-- | Lifted 'A.race_'.
270-- | Lifted 'A.race_'.
283−race_ :: AsyncE :> es => Eff es a -> Eff es b -> Eff es ()
271+race_ :: Concurrent :> es => Eff es a -> Eff es b -> Eff es ()
284race_ ma mb = unsafeEff $ \es -> do
272race_ ma mb = unsafeEff $ \es -> do
285 A.race_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
273 A.race_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
286
274
287-- | Lifted 'A.concurrently'.
275-- | Lifted 'A.concurrently'.
288−concurrently :: AsyncE :> es => Eff es a -> Eff es b -> Eff es (a, b)
276+concurrently :: Concurrent :> es => Eff es a -> Eff es b -> Eff es (a, b)
289concurrently ma mb = unsafeEff $ \es -> do
277concurrently ma mb = unsafeEff $ \es -> do
290 A.concurrently (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
278 A.concurrently (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
291
279
292-- | Lifted 'A.concurrently_'.
280-- | Lifted 'A.concurrently_'.
293−concurrently_ :: AsyncE :> es => Eff es a -> Eff es b -> Eff es ()
281+concurrently_ :: Concurrent :> es => Eff es a -> Eff es b -> Eff es ()
294concurrently_ ma mb = unsafeEff $ \es -> do
282concurrently_ ma mb = unsafeEff $ \es -> do
295 A.concurrently_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
283 A.concurrently_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es)
296
284
@@ -300,7 +288,7 @@ concurrently_ ma mb = unsafeEff $ \es -> do
300
288
301-- | Lifted 'A.mapConcurrently'.
289-- | Lifted 'A.mapConcurrently'.
302mapConcurrently
290mapConcurrently
303− :: (Traversable f, AsyncE :> es)
291+ :: (Traversable f, Concurrent :> es)
304 => (a -> Eff es b)
292 => (a -> Eff es b)
305 -> f a
293 -> f a
306 -> Eff es (f b)
294 -> Eff es (f b)
@@ -309,7 +297,7 @@ mapConcurrently f t = unsafeEff $ \es -> do
309
297
310-- | Lifted 'A.mapConcurrently_'.
298-- | Lifted 'A.mapConcurrently_'.
311mapConcurrently_
299mapConcurrently_
312− :: (Foldable f, AsyncE :> es)
300+ :: (Foldable f, Concurrent :> es)
313 => (a -> Eff es b)
301 => (a -> Eff es b)
314 -> f a
302 -> f a
315 -> Eff es ()
303 -> Eff es ()
@@ -318,7 +306,7 @@ mapConcurrently_ f t = unsafeEff $ \es -> do
318
306
319-- | Lifted 'A.forConcurrently'.
307-- | Lifted 'A.forConcurrently'.
320forConcurrently
308forConcurrently
321− :: (Traversable f, AsyncE :> es)
309+ :: (Traversable f, Concurrent :> es)
322 => f a
310 => f a
323 -> (a -> Eff es b)
311 -> (a -> Eff es b)
324 -> Eff es (f b)
312 -> Eff es (f b)
@@ -327,7 +315,7 @@ forConcurrently t f = unsafeEff $ \es -> do
327
315
328-- | Lifted 'A.forConcurrently_'.
316-- | Lifted 'A.forConcurrently_'.
329forConcurrently_
317forConcurrently_
330− :: (Foldable f, AsyncE :> es)
318+ :: (Foldable f, Concurrent :> es)
331 => f a
319 => f a
332 -> (a -> Eff es b)
320 -> (a -> Eff es b)
333 -> Eff es ()
321 -> Eff es ()
@@ -335,12 +323,12 @@ forConcurrently_ t f = unsafeEff $ \es -> do
335 U.forConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es)
323 U.forConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es)
336
324
337-- | Lifted 'A.replicateConcurrently'.
325-- | Lifted 'A.replicateConcurrently'.
338−replicateConcurrently :: AsyncE :> es => Int -> Eff es a -> Eff es [a]
326+replicateConcurrently :: Concurrent :> es => Int -> Eff es a -> Eff es [a]
339replicateConcurrently n f = unsafeEff $ \es -> do
327replicateConcurrently n f = unsafeEff $ \es -> do
340 U.replicateConcurrently n (unEff f =<< cloneEnv es)
328 U.replicateConcurrently n (unEff f =<< cloneEnv es)
341
329
342-- | Lifted 'A.replicateConcurrently_'.
330-- | Lifted 'A.replicateConcurrently_'.
343−replicateConcurrently_ :: AsyncE :> es => Int -> Eff es a -> Eff es ()
331+replicateConcurrently_ :: Concurrent :> es => Int -> Eff es a -> Eff es ()
344replicateConcurrently_ n f = unsafeEff $ \es -> do
332replicateConcurrently_ n f = unsafeEff $ \es -> do
345 U.replicateConcurrently_ n (unEff f =<< cloneEnv es)
333 U.replicateConcurrently_ n (unEff f =<< cloneEnv es)
346
334
@@ -349,7 +337,7 @@ replicateConcurrently_ n f = unsafeEff $ \es -> do
349
337
350-- | Lifted 'U.pooledMapConcurrentlyN'.
338-- | Lifted 'U.pooledMapConcurrentlyN'.
351pooledMapConcurrentlyN
339pooledMapConcurrentlyN
352− :: (AsyncE :> es, Traversable t)
340+ :: (Concurrent :> es, Traversable t)
353 => Int
341 => Int
354 -> (a -> Eff es b)
342 -> (a -> Eff es b)
355 -> t a
343 -> t a
@@ -359,7 +347,7 @@ pooledMapConcurrentlyN threads f t = unsafeEff $ \es -> do
359
347
360-- | Lifted 'U.pooledMapConcurrently'.
348-- | Lifted 'U.pooledMapConcurrently'.
361pooledMapConcurrently
349pooledMapConcurrently
362− :: (AsyncE :> es, Traversable t)
350+ :: (Concurrent :> es, Traversable t)
363 => (a -> Eff es b)
351 => (a -> Eff es b)
364 -> t a
352 -> t a
365 -> Eff es (t b)
353 -> Eff es (t b)
@@ -368,7 +356,7 @@ pooledMapConcurrently f t = unsafeEff $ \es -> do
368
356
369-- | Lifted 'U.pooledMapConcurrentlyN'.
357-- | Lifted 'U.pooledMapConcurrentlyN'.
370pooledMapConcurrentlyN_
358pooledMapConcurrentlyN_
371− :: (AsyncE :> es, Foldable f)
359+ :: (Concurrent :> es, Foldable f)
372 => Int
360 => Int
373 -> (a -> Eff es b)
361 -> (a -> Eff es b)
374 -> f a
362 -> f a
@@ -378,7 +366,7 @@ pooledMapConcurrentlyN_ threads f t = unsafeEff $ \es -> do
378
366
379-- | Lifted 'U.pooledMapConcurrently_'.
367-- | Lifted 'U.pooledMapConcurrently_'.
380pooledMapConcurrently_
368pooledMapConcurrently_
381− :: (AsyncE :> es, Foldable f)
369+ :: (Concurrent :> es, Foldable f)
382 => (a -> Eff es b)
370 => (a -> Eff es b)
383 -> f a
371 -> f a
384 -> Eff es ()
372 -> Eff es ()
@@ -387,7 +375,7 @@ pooledMapConcurrently_ f t = unsafeEff $ \es -> do
387
375
388-- | Lifted 'U.pooledForConcurrentlyN'.
376-- | Lifted 'U.pooledForConcurrentlyN'.
389pooledForConcurrentlyN
377pooledForConcurrentlyN
390− :: (AsyncE :> es, Traversable t)
378+ :: (Concurrent :> es, Traversable t)
391 => Int
379 => Int
392 -> t a
380 -> t a
393 -> (a -> Eff es b)
381 -> (a -> Eff es b)
@@ -397,7 +385,7 @@ pooledForConcurrentlyN threads t f = unsafeEff $ \es -> do
397
385
398-- | Lifted 'U.pooledForConcurrently'.
386-- | Lifted 'U.pooledForConcurrently'.
399pooledForConcurrently
387pooledForConcurrently
400− :: (AsyncE :> es, Traversable t)
388+ :: (Concurrent :> es, Traversable t)
401 => t a
389 => t a
402 -> (a -> Eff es b)
390 -> (a -> Eff es b)
403 -> Eff es (t b)
391 -> Eff es (t b)
@@ -406,7 +394,7 @@ pooledForConcurrently t f = unsafeEff $ \es -> do
406
394
407-- | Lifted 'U.pooledForConcurrentlyN'.
395-- | Lifted 'U.pooledForConcurrentlyN'.
408pooledForConcurrentlyN_
396pooledForConcurrentlyN_
409− :: (AsyncE :> es, Foldable f)
397+ :: (Concurrent :> es, Foldable f)
410 => Int
398 => Int
411 -> f a
399 -> f a
412 -> (a -> Eff es b)
400 -> (a -> Eff es b)
@@ -416,7 +404,7 @@ pooledForConcurrentlyN_ threads t f = unsafeEff $ \es -> do
416
404
417-- | Lifted 'U.pooledForConcurrently_'.
405-- | Lifted 'U.pooledForConcurrently_'.
418pooledForConcurrently_
406pooledForConcurrently_
419− :: (AsyncE :> es, Foldable f)
407+ :: (Concurrent :> es, Foldable f)
420 => f a
408 => f a
421 -> (a -> Eff es b)
409 -> (a -> Eff es b)
422 -> Eff es ()
410 -> Eff es ()
@@ -424,22 +412,22 @@ pooledForConcurrently_ t f = unsafeEff $ \es -> do
424 U.pooledForConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es)
412 U.pooledForConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es)
425
413
426-- | Lifted 'U.pooledReplicateConcurrentlyN'.
414-- | Lifted 'U.pooledReplicateConcurrentlyN'.
427−pooledReplicateConcurrentlyN :: AsyncE :> es => Int -> Int -> Eff es a -> Eff es [a]
415+pooledReplicateConcurrentlyN :: Concurrent :> es => Int -> Int -> Eff es a -> Eff es [a]
428pooledReplicateConcurrentlyN threads n f = unsafeEff $ \es -> do
416pooledReplicateConcurrentlyN threads n f = unsafeEff $ \es -> do
429 U.pooledReplicateConcurrentlyN threads n (unEff f =<< cloneEnv es)
417 U.pooledReplicateConcurrentlyN threads n (unEff f =<< cloneEnv es)
430
418
431-- | Lifted 'U.pooledReplicateConcurrently'.
419-- | Lifted 'U.pooledReplicateConcurrently'.
432−pooledReplicateConcurrently :: AsyncE :> es => Int -> Eff es a -> Eff es [a]
420+pooledReplicateConcurrently :: Concurrent :> es => Int -> Eff es a -> Eff es [a]
433pooledReplicateConcurrently n f = unsafeEff $ \es -> do
421pooledReplicateConcurrently n f = unsafeEff $ \es -> do
434 U.pooledReplicateConcurrently n (unEff f =<< cloneEnv es)
422 U.pooledReplicateConcurrently n (unEff f =<< cloneEnv es)
435
423
436-- | Lifted 'U.pooledReplicateConcurrentlyN_'.
424-- | Lifted 'U.pooledReplicateConcurrentlyN_'.
437−pooledReplicateConcurrentlyN_ :: AsyncE :> es => Int -> Int -> Eff es a -> Eff es ()
425+pooledReplicateConcurrentlyN_ :: Concurrent :> es => Int -> Int -> Eff es a -> Eff es ()
438pooledReplicateConcurrentlyN_ threads n f = unsafeEff $ \es -> do
426pooledReplicateConcurrentlyN_ threads n f = unsafeEff $ \es -> do
439 U.pooledReplicateConcurrentlyN_ threads n (unEff f =<< cloneEnv es)
427 U.pooledReplicateConcurrentlyN_ threads n (unEff f =<< cloneEnv es)
440
428
441-- | Lifted 'U.pooledReplicateConcurrently_'.
429-- | Lifted 'U.pooledReplicateConcurrently_'.
442−pooledReplicateConcurrently_ :: AsyncE :> es => Int -> Eff es a -> Eff es ()
430+pooledReplicateConcurrently_ :: Concurrent :> es => Int -> Eff es a -> Eff es ()
443pooledReplicateConcurrently_ n f = unsafeEff $ \es -> do
431pooledReplicateConcurrently_ n f = unsafeEff $ \es -> do
444 U.pooledReplicateConcurrently_ n (unEff f =<< cloneEnv es)
432 U.pooledReplicateConcurrently_ n (unEff f =<< cloneEnv es)
445
433
@@ -447,7 +435,7 @@ pooledReplicateConcurrently_ n f = unsafeEff $ \es -> do
447-- Conc
435-- Conc
448
436
449-- | Lifted 'U.Conc'.
437-- | Lifted 'U.Conc'.
450−data Conc es a where
438+data Conc :: [Effect] -> Type -> Type where
451 Action :: Eff es a -> Conc es a
439 Action :: Eff es a -> Conc es a
452 Apply :: Conc es (v -> a) -> Conc es v -> Conc es a
440 Apply :: Conc es (v -> a) -> Conc es v -> Conc es a
453 LiftA2 :: (x -> y -> a) -> Conc es x -> Conc es y -> Conc es a
441 LiftA2 :: (x -> y -> a) -> Conc es x -> Conc es y -> Conc es a
@@ -479,7 +467,7 @@ conc :: Eff es a -> Conc es a
479conc = Action
467conc = Action
480
468
481-- | Lifted 'U.runConc'.
469-- | Lifted 'U.runConc'.
482−runConc :: AsyncE :> es => Conc es a -> Eff es a
470+runConc :: Concurrent :> es => Conc es a -> Eff es a
483runConc m = unsafeEff $ \es -> U.runConc (unliftConc es m)
471runConc m = unsafeEff $ \es -> U.runConc (unliftConc es m)
484 where
472 where
485 unliftConc :: Env es -> Conc es a -> U.Conc IO a
473 unliftConc :: Env es -> Conc es a -> U.Conc IO a
@@ -500,20 +488,20 @@ newtype Concurrently es a = Concurrently { runConcurrently :: Eff es a }
500instance Functor (Concurrently es) where
488instance Functor (Concurrently es) where
501 fmap f (Concurrently a) = Concurrently (fmap f a)
489 fmap f (Concurrently a) = Concurrently (fmap f a)
502
490
503−instance AsyncE :> es => Applicative (Concurrently es) where
491+instance Concurrent :> es => Applicative (Concurrently es) where
504 pure = Concurrently . pure
492 pure = Concurrently . pure
505 Concurrently fs <*> Concurrently as =
493 Concurrently fs <*> Concurrently as =
506 Concurrently ((\(f, a) -> f a) <$> concurrently fs as)
494 Concurrently ((\(f, a) -> f a) <$> concurrently fs as)
507
495
508−instance AsyncE :> es => Alternative (Concurrently es) where
496+instance Concurrent :> es => Alternative (Concurrently es) where
509 empty = Concurrently . unsafeEff_ . forever $ threadDelay maxBound
497 empty = Concurrently . unsafeEff_ . forever $ threadDelay maxBound
510 Concurrently as <|> Concurrently bs =
498 Concurrently as <|> Concurrently bs =
511 Concurrently (either id id <$> race as bs)
499 Concurrently (either id id <$> race as bs)
512
500
513−instance (AsyncE :> es, Semigroup a) => Semigroup (Concurrently es a) where
501+instance (Concurrent :> es, Semigroup a) => Semigroup (Concurrently es a) where
514 (<>) = liftA2 (<>)
502 (<>) = liftA2 (<>)
515
503
516−instance (AsyncE :> es, Monoid a) => Monoid (Concurrently es a) where
504+instance (Concurrent :> es, Monoid a) => Monoid (Concurrently es a) where
517 mempty = pure mempty
505 mempty = pure mempty
518
506
519----------------------------------------
507----------------------------------------
@@ -531,10 +519,9 @@ liftAsyncWithUnmask
531 :: (((forall b. IO b -> IO b) -> IO a) -> IO (Async a))
519 :: (((forall b. IO b -> IO b) -> IO a) -> IO (Async a))
532 -> ((forall b. Eff es b -> Eff es b) -> Eff es a)
520 -> ((forall b. Eff es b -> Eff es b) -> Eff es a)
533 -> Eff es (Async a)
521 -> Eff es (Async a)
534−liftAsyncWithUnmask fork action = do
522+liftAsyncWithUnmask fork action = unsafeEff $ \es -> do
535− unsafeWithLiftMapIO $ \liftMap -> unsafeEff $ \es -> do
536− esA <- cloneEnv es
523+ esA <- cloneEnv es
537− fork $ \unmask -> unEff (action $ liftMap unmask) esA
524+ fork $ \unmask -> unEff (action $ unsafeLiftMapIO unmask) esA
538
525
539liftWithAsync
526liftWithAsync
540 :: (IO a -> (Async a -> IO b) -> IO b)
527 :: (IO a -> (Async a -> IO b) -> IO b)
@@ -551,8 +538,7 @@ liftWithAsyncWithUnmask
551 -> ((forall c. Eff es c -> Eff es c) -> Eff es a)
538 -> ((forall c. Eff es c -> Eff es c) -> Eff es a)
552 -> (Async a -> Eff es b)
539 -> (Async a -> Eff es b)
553 -> Eff es b
540 -> Eff es b
554−liftWithAsyncWithUnmask withA action k = do
541+liftWithAsyncWithUnmask withA action k = unsafeEff $ \es -> do
555− unsafeWithLiftMapIO $ \liftMap -> unsafeEff $ \es -> do
556− esA <- cloneEnv es
542+ esA <- cloneEnv es
557− withA (\unmask -> unEff (action $ liftMap unmask) esA)
543+ withA (\unmask -> unEff (action $ unsafeLiftMapIO unmask) esA)
558− (\a -> unEff (k a) es)
544+ (\a -> unEff (k a) es)
effectful/src/Effectful/Concurrent/Chan.hsnew file+45
@@ -0,0 +1,45 @@
1+-- | Lifted version of "Control.Concurrent.Chan".
2+module Effectful.Concurrent.Chan
3+ ( Concurrent
4+ , runConcurrent
5+
6+ -- * Chan
7+ , Chan
8+ , newChan
9+ , writeChan
10+ , readChan
11+ , dupChan
12+ , getChanContents
13+ , writeList2Chan
14+ ) where
15+
16+import Control.Concurrent.Chan (Chan)
17+import qualified Control.Concurrent.Chan as C
18+
19+import Effectful.Concurrent.Effect
20+import Effectful.Dispatch.Static
21+import Effectful.Monad
22+
23+-- | Lifted 'C.newChan'.
24+newChan :: Concurrent :> es => Eff es (Chan a)
25+newChan = unsafeEff_ C.newChan
26+
27+-- | Lifted 'C.writeChan'.
28+writeChan :: Concurrent :> es => Chan a -> a -> Eff es ()
29+writeChan c = unsafeEff_ . C.writeChan c
30+
31+-- | Lifted 'C.readChan'.
32+readChan :: Concurrent :> es => Chan a -> Eff es a
33+readChan = unsafeEff_ . C.readChan
34+
35+-- | Lifted 'C.dupChan'.
36+dupChan :: Concurrent :> es => Chan a -> Eff es (Chan a)
37+dupChan = unsafeEff_ . C.dupChan
38+
39+-- | Lifted 'C.getChanContents'.
40+getChanContents :: Concurrent :> es => Chan a -> Eff es [a]
41+getChanContents = unsafeEff_ . C.getChanContents
42+
43+-- | Lifted 'C.writeList2Chan'.
44+writeList2Chan :: Concurrent :> es => Chan a -> [a] -> Eff es ()
45+writeList2Chan c = unsafeEff_ . C.writeList2Chan c
effectful/src/Effectful/Concurrent/Effect.hsnew file+79
@@ -0,0 +1,79 @@
1+module Effectful.Concurrent.Effect
2+ ( Concurrent
3+ , runConcurrent
4+ ) where
5+
6+import Effectful.Dispatch.Static
7+import Effectful.Monad
8+
9+-- | Provide the ability to run 'Eff' computations concurrently in multiple
10+-- threads and communicate between them.
11+--
12+-- /Warning:/ unless you stick to high level functions from the
13+-- 'Effectful.Concurrent.Async.withAsync' family, the 'Concurrent' effect makes
14+-- it possible to escape the scope of any scoped effect operation. Consider the
15+-- following:
16+--
17+-- >>> import qualified Effectful.Reader as R
18+-- >>> let printAsk msg = liftIO . putStrLn . (msg ++) . (": " ++) =<< R.ask
19+-- >>> :{
20+-- runEff . R.runReader "GLOBAL" . runConcurrent $ do
21+-- a <- R.local (const "LOCAL") $ do
22+-- a <- async $ do
23+-- printAsk "child (first)"
24+-- threadDelay 20000
25+-- printAsk "child (second)"
26+-- threadDelay 10000
27+-- printAsk "parent (inside)"
28+-- pure a
29+-- printAsk "parent (outside)"
30+-- wait a
31+-- :}
32+-- child (first): LOCAL
33+-- parent (inside): LOCAL
34+-- parent (outside): GLOBAL
35+-- child (second): LOCAL
36+--
37+-- Note that the asynchronous computation doesn't respect the scope of
38+-- 'Effectful.Reader.local', i.e. the child thread still behaves like it's
39+-- inside the 'Effectful.Reader.local' block, even though the parent thread
40+-- already got out of it.
41+--
42+-- This is because the value provided by the 'Effectful.Reader.Reader' effect is
43+-- thread local, i.e. each thread manages its own version of it. For the
44+-- 'Effectful.Reader.Reader' it is the only reasonable behavior, it wouldn't be
45+-- very useful if its "read only" value was affected by calls to
46+-- 'Effectful.Reader.local' from its parent or child threads.
47+--
48+-- However, the cut isn't so clear if it comes to effects that provide access to
49+-- a mutable state. That's why primitive @State@ and @Writer@ effects come in
50+-- two flavors, local and shared:
51+--
52+-- >>> import qualified Effectful.State.Local as SL
53+-- >>> :{
54+-- runEff . SL.execState "Hi" . runConcurrent $ do
55+-- replicateConcurrently_ 3 $ SL.modify (++ "!")
56+-- :}
57+-- "Hi"
58+--
59+-- >>> import qualified Effectful.State.Shared as SS
60+-- >>> :{
61+-- runEff . SS.execState "Hi" . runConcurrent $ do
62+-- replicateConcurrently_ 3 $ SS.modify (++ "!")
63+-- :}
64+-- "Hi!!!"
65+--
66+-- In the first example state modification made concurrently are not reflected
67+-- in the parent thread because the value is thread local, but in the second
68+-- example they are, because the value is shared.
69+--
70+data Concurrent :: Effect where
71+ Concurrent :: Concurrent m r
72+
73+-- | Run the 'Concurrent' effect.
74+runConcurrent :: IOE :> es => Eff (Concurrent : es) a -> Eff es a
75+runConcurrent = evalData (DataA Concurrent)
76+
77+-- $setup
78+-- >>> import Effectful.Concurrent
79+-- >>> import Effectful.Concurrent.Async
effectful/src/Effectful/Concurrent/MVar.hsnew file+108
@@ -0,0 +1,108 @@
1+-- | Lifted version of "Control.Concurrent.MVar".
2+module Effectful.Concurrent.MVar
3+ ( Concurrent
4+ , runConcurrent
5+
6+ -- * MVar
7+ , MVar
8+ , newEmptyMVar
9+ , newMVar
10+ , takeMVar
11+ , putMVar
12+ , readMVar
13+ , swapMVar
14+ , tryTakeMVar
15+ , tryPutMVar
16+ , isEmptyMVar
17+ , withMVar
18+ , withMVarMasked
19+ , modifyMVar
20+ , modifyMVar_
21+ , modifyMVarMasked
22+ , modifyMVarMasked_
23+ , tryReadMVar
24+ , mkWeakMVar
25+ ) where
26+
27+import System.Mem.Weak (Weak)
28+import Control.Concurrent.MVar (MVar)
29+import qualified Control.Concurrent.MVar as M
30+
31+import Effectful.Concurrent.Effect
32+import Effectful.Dispatch.Static
33+import Effectful.Monad
34+
35+-- | Lifted 'M.newEmptyMVar'.
36+newEmptyMVar :: Concurrent :> es => Eff es (MVar a)
37+newEmptyMVar = unsafeEff_ M.newEmptyMVar
38+
39+-- | Lifted 'M.newMVar'.
40+newMVar :: Concurrent :> es => a -> Eff es (MVar a)
41+newMVar = unsafeEff_ . M.newMVar
42+
43+-- | Lifted 'M.takeMVar'.
44+takeMVar :: Concurrent :> es => MVar a -> Eff es a
45+takeMVar = unsafeEff_ . M.takeMVar
46+
47+-- | Lifted 'M.putMVar'.
48+putMVar :: Concurrent :> es => MVar a -> a -> Eff es ()
49+putMVar var = unsafeEff_ . M.putMVar var
50+
51+-- | Lifted 'M.readMVar'.
52+readMVar :: Concurrent :> es => MVar a -> Eff es a
53+readMVar = unsafeEff_ . M.readMVar
54+
55+-- | Lifted 'M.swapMVar'.
56+swapMVar :: Concurrent :> es => MVar a -> a -> Eff es a
57+swapMVar var = unsafeEff_ . M.swapMVar var
58+
59+-- | Lifted 'M.tryTakeMVar'.
60+tryTakeMVar :: Concurrent :> es => MVar a -> Eff es (Maybe a)
61+tryTakeMVar = unsafeEff_ . M.tryTakeMVar
62+
63+-- | Lifted 'M.tryPutMVar'.
64+tryPutMVar :: Concurrent :> es => MVar a -> a -> Eff es Bool
65+tryPutMVar var = unsafeEff_ . M.tryPutMVar var
66+
67+-- | Lifted 'M.isEmptyMVar'.
68+isEmptyMVar :: Concurrent :> es => MVar a -> Eff es Bool
69+isEmptyMVar = unsafeEff_ . M.isEmptyMVar
70+
71+-- | Lifted 'M.tryReadMVar'.
72+tryReadMVar :: Concurrent :> es => MVar a -> Eff es (Maybe a)
73+tryReadMVar = unsafeEff_ . M.tryReadMVar
74+
75+-- | Lifted 'M.withMVar'.
76+withMVar :: Concurrent :> es => MVar a -> (a -> Eff es b) -> Eff es b
77+withMVar var f = unsafeUnliftIO $ \unlift -> do
78+ M.withMVar var $ unlift . f
79+
80+-- | Lifted 'M.withMVarMasked'.
81+withMVarMasked :: Concurrent :> es => MVar a -> (a -> Eff es b) -> Eff es b
82+withMVarMasked var f = unsafeUnliftIO $ \unlift -> do
83+ M.withMVarMasked var $ unlift . f
84+
85+-- | Lifted 'M.modifyMVar_'.
86+modifyMVar_ :: Concurrent :> es => MVar a -> (a -> Eff es a) -> Eff es ()
87+modifyMVar_ var f = unsafeUnliftIO $ \unlift -> do
88+ M.modifyMVar_ var $ unlift . f
89+
90+-- | Lifted 'M.modifyMVar'.
91+modifyMVar :: Concurrent :> es => MVar a -> (a -> Eff es (a, b)) -> Eff es b
92+modifyMVar var f = unsafeUnliftIO $ \unlift -> do
93+ M.modifyMVar var $ unlift . f
94+
95+-- | Lifted 'M.modifyMVarMasked_'.
96+modifyMVarMasked_ :: Concurrent :> es => MVar a -> (a -> Eff es a) -> Eff es ()
97+modifyMVarMasked_ var f = unsafeUnliftIO $ \unlift -> do
98+ M.modifyMVarMasked_ var $ unlift . f
99+
100+-- | Lifted 'M.modifyMVarMasked'.
101+modifyMVarMasked :: Concurrent :> es => MVar a -> (a -> Eff es (a, b)) -> Eff es b
102+modifyMVarMasked var f = unsafeUnliftIO $ \unlift -> do
103+ M.modifyMVarMasked var $ unlift . f
104+
105+-- | Lifted 'M.mkWeakMVar'.
106+mkWeakMVar :: Concurrent :> es => MVar a -> Eff es () -> Eff es (Weak (MVar a))
107+mkWeakMVar var f = unsafeUnliftIO $ \unlift -> do
108+ M.mkWeakMVar var $ unlift f
effectful/src/Effectful/Concurrent/QSem.hsnew file+30
@@ -0,0 +1,30 @@
1+-- | Lifted version of "Control.Concurrent.QSem".
2+module Effectful.Concurrent.QSem
3+ ( Concurrent
4+ , runConcurrent
5+
6+ -- * QSem
7+ , QSem
8+ , newQSem
9+ , waitQSem
10+ , signalQSem
11+ ) where
12+
13+import Control.Concurrent.QSem (QSem)
14+import qualified Control.Concurrent.QSem as Q
15+
16+import Effectful.Concurrent.Effect
17+import Effectful.Dispatch.Static
18+import Effectful.Monad
19+
20+-- | Lifted 'Q.newQSem'.
21+newQSem :: Concurrent :> es => Int -> Eff es QSem
22+newQSem = unsafeEff_ . Q.newQSem
23+
24+-- | Lifted 'Q.waitQSem'.
25+waitQSem :: Concurrent :> es => QSem -> Eff es ()
26+waitQSem = unsafeEff_ . Q.waitQSem
27+
28+-- | Lifted 'Q.signalQSem'.
29+signalQSem :: Concurrent :> es => QSem -> Eff es ()
30+signalQSem = unsafeEff_ . Q.signalQSem
effectful/src/Effectful/Concurrent/QSemN.hsnew file+30
@@ -0,0 +1,30 @@
1+-- | Lifted version of "Control.Concurrent.QSemN".
2+module Effectful.Concurrent.QSemN
3+ ( Concurrent
4+ , runConcurrent
5+
6+ -- * QSemN
7+ , QSemN
8+ , newQSemN
9+ , waitQSemN
10+ , signalQSemN
11+ ) where
12+
13+import Control.Concurrent.QSemN (QSemN)
14+import qualified Control.Concurrent.QSemN as Q
15+
16+import Effectful.Concurrent.Effect
17+import Effectful.Dispatch.Static
18+import Effectful.Monad
19+
20+-- | Lifted 'Q.newQSemN'.
21+newQSemN :: Concurrent :> es => Int -> Eff es QSemN
22+newQSemN = unsafeEff_ . Q.newQSemN
23+
24+-- | Lifted 'Q.waitQSemN'.
25+waitQSemN :: Concurrent :> es => QSemN -> Int -> Eff es ()
26+waitQSemN x = unsafeEff_ . Q.waitQSemN x
27+
28+-- | Lifted 'Q.signalQSemN'.
29+signalQSemN :: Concurrent :> es => QSemN -> Int -> Eff es ()
30+signalQSemN x = unsafeEff_ . Q.signalQSemN x
effectful/src/Effectful/Concurrent/STM.hsnew file+146
@@ -0,0 +1,146 @@
1+-- | Lifted version of "Control.Concurrent.STM".
2+module Effectful.Concurrent.STM
3+ ( Concurrent
4+ , runConcurrent
5+
6+ -- * Core
7+ , STM.STM
8+ , atomically
9+ , STM.retry
10+ , STM.orElse
11+ , STM.check
12+ , STM.throwSTM
13+ , STM.catchSTM
14+
15+ -- * TVar
16+ , STM.TVar
17+ , newTVarIO
18+ , readTVarIO
19+ , STM.newTVar
20+ , STM.readTVar
21+ , STM.writeTVar
22+ , STM.modifyTVar
23+ , STM.modifyTVar'
24+ , STM.swapTVar
25+ , registerDelay
26+ , mkWeakTVar
27+
28+ -- * TMVar
29+ , STM.TMVar
30+ , STM.newTMVar
31+ , STM.newEmptyTMVar
32+ , newTMVarIO
33+ , newEmptyTMVarIO
34+ , STM.takeTMVar
35+ , STM.putTMVar
36+ , STM.readTMVar
37+ , STM.tryReadTMVar
38+ , STM.swapTMVar
39+ , STM.tryTakeTMVar
40+ , STM.tryPutTMVar
41+ , STM.isEmptyTMVar
42+ , mkWeakTMVar
43+
44+ -- * TChan
45+ , STM.TChan
46+ , STM.newTChan
47+ , newTChanIO
48+ , STM.newBroadcastTChan
49+ , newBroadcastTChanIO
50+ , STM.dupTChan
51+ , STM.cloneTChan
52+ , STM.readTChan
53+ , STM.tryReadTChan
54+ , STM.peekTChan
55+ , STM.tryPeekTChan
56+ , STM.writeTChan
57+ , STM.unGetTChan
58+ , STM.isEmptyTChan
59+
60+ -- * TQueue
61+ , STM.TQueue
62+ , STM.newTQueue
63+ , newTQueueIO
64+ , STM.readTQueue
65+ , STM.tryReadTQueue
66+ , STM.peekTQueue
67+ , STM.tryPeekTQueue
68+ , STM.flushTQueue
69+ , STM.writeTQueue
70+ , STM.unGetTQueue
71+ , STM.isEmptyTQueue
72+
73+ -- * TBQueue
74+ , STM.TBQueue
75+ , STM.newTBQueue
76+ , newTBQueueIO
77+ , STM.readTBQueue
78+ , STM.tryReadTBQueue
79+ , STM.peekTBQueue
80+ , STM.tryPeekTBQueue
81+ , STM.flushTBQueue
82+ , STM.writeTBQueue
83+ , STM.unGetTBQueue
84+ , STM.lengthTBQueue
85+ , STM.isEmptyTBQueue
86+ , STM.isFullTBQueue
87+ ) where
88+
89+import Control.Concurrent.STM (STM, TVar, TMVar, TChan, TQueue, TBQueue)
90+import qualified Control.Concurrent.STM as STM
91+import System.Mem.Weak (Weak)
92+import GHC.Natural (Natural)
93+
94+import Effectful.Concurrent.Effect
95+import Effectful.Dispatch.Static
96+import Effectful.Monad
97+
98+-- | Lifted version of 'STM.atomically'
99+atomically :: Concurrent :> es => STM a -> Eff es a
100+atomically = unsafeEff_ . STM.atomically
101+
102+-- | Lifted version of 'STM.newTVarIO'
103+newTVarIO :: Concurrent :> es => a -> Eff es (TVar a)
104+newTVarIO = unsafeEff_ . STM.newTVarIO
105+
106+-- | Lifted version of 'STM.readTVarIO'
107+readTVarIO :: Concurrent :> es => TVar a -> Eff es a
108+readTVarIO = unsafeEff_ . STM.readTVarIO
109+
110+-- | Lifted version of 'STM.registerDelay'
111+registerDelay :: Concurrent :> es => Int -> Eff es (TVar Bool)
112+registerDelay = unsafeEff_ . STM.registerDelay
113+
114+-- | Lifted version of 'STM.mkWeakTVar'
115+mkWeakTVar :: Concurrent :> es => TVar a -> Eff es () -> Eff es (Weak (TVar a))
116+mkWeakTVar var final = unsafeUnliftIO $ \unlift -> do
117+ STM.mkWeakTVar var $ unlift final
118+
119+-- | Lifted version of 'STM.newTMVarIO'
120+newTMVarIO :: Concurrent :> es => a -> Eff es (TMVar a)
121+newTMVarIO = unsafeEff_ . STM.newTMVarIO
122+
123+-- | Lifted version of 'STM.newEmptyTMVarIO'
124+newEmptyTMVarIO :: Concurrent :> es => Eff es (TMVar a)
125+newEmptyTMVarIO = unsafeEff_ STM.newEmptyTMVarIO
126+
127+-- | Lifted version of 'STM.mkWeakTMVar'
128+mkWeakTMVar :: Concurrent :> es => TMVar a -> Eff es () -> Eff es (Weak (TMVar a))
129+mkWeakTMVar var final = unsafeUnliftIO $ \unlift -> do
130+ STM.mkWeakTMVar var $ unlift final
131+
132+-- | Lifted version of 'STM.newTChanIO'
133+newTChanIO :: Concurrent :> es => Eff es (TChan a)
134+newTChanIO = unsafeEff_ STM.newTChanIO
135+
136+-- | Lifted version of 'STM.newBroadcastTChanIO'
137+newBroadcastTChanIO :: Concurrent :> es => Eff es (TChan a)
138+newBroadcastTChanIO = unsafeEff_ STM.newBroadcastTChanIO
139+
140+-- | Lifted version of 'STM.newTQueueIO'
141+newTQueueIO :: Concurrent :> es => Eff es (TQueue a)
142+newTQueueIO = unsafeEff_ STM.newTQueueIO
143+
144+-- | Lifted version of 'STM.newTBQueueIO'
145+newTBQueueIO :: Concurrent :> es => Natural -> Eff es (TBQueue a)
146+newTBQueueIO = unsafeEff_ . STM.newTBQueueIO
effectful/src/Effectful/Environment.hsnew file+71
@@ -0,0 +1,71 @@
1+module Effectful.Environment
2+ ( Environment
3+ , runEnvironment
4+
5+ -- * Querying the environment
6+ , getArgs
7+ , getProgName
8+ , getExecutablePath
9+ , getEnv
10+ , getEnvironment
11+ , lookupEnv
12+
13+ -- * Modifying the environment
14+ , setEnv
15+ , unsetEnv
16+ , withArgs
17+ , withProgName
18+ ) where
19+
20+import qualified System.Environment as E
21+
22+import Effectful.Dispatch.Static hiding (getEnv)
23+import Effectful.Monad
24+
25+-- | An effect for querying and modifying the system environment.
26+data Environment :: Effect where
27+ Environment :: Environment m r
28+
29+-- | Run the 'Environment' effect.
30+runEnvironment :: IOE :> es => Eff (Environment : es) a -> Eff es a
31+runEnvironment = evalData (DataA Environment)
32+
33+-- | Lifted 'E.getArgs'.
34+getArgs :: Environment :> es => Eff es [String]
35+getArgs = unsafeEff_ E.getArgs
36+
37+-- | Lifted 'E.getEnv'.
38+getEnv :: Environment :> es => String -> Eff es String
39+getEnv = unsafeEff_ . E.getEnv
40+
41+-- | Lifted 'E.getEnvironment'.
42+getEnvironment :: Environment :> es => Eff es [(String, String)]
43+getEnvironment = unsafeEff_ E.getEnvironment
44+
45+-- | Lifted 'E.getExecutablePath'.
46+getExecutablePath :: Environment :> es => Eff es FilePath
47+getExecutablePath = unsafeEff_ E.getExecutablePath
48+
49+-- | Lifted 'E.getProgName'.
50+getProgName :: Environment :> es => Eff es String
51+getProgName = unsafeEff_ E.getProgName
52+
53+-- | Lifted 'E.lookupEnv'.
54+lookupEnv :: Environment :> es => String -> Eff es (Maybe String)
55+lookupEnv = unsafeEff_ . E.lookupEnv
56+
57+-- | Lifted 'E.setEnv'.
58+setEnv :: Environment :> es => String -> String -> Eff es ()
59+setEnv n = unsafeEff_ . E.setEnv n
60+
61+-- | Lifted 'E.unsetEnv'.
62+unsetEnv :: Environment :> es => String -> Eff es ()
63+unsetEnv = unsafeEff_ . E.unsetEnv
64+
65+-- | Lifted 'E.withArgs'.
66+withArgs :: Environment :> es => [String] -> Eff es a -> Eff es a
67+withArgs = unsafeLiftMapIO . E.withArgs
68+
69+-- | Lifted 'E.withProgName'.
70+withProgName :: Environment :> es => String -> Eff es a -> Eff es a
71+withProgName = unsafeLiftMapIO . E.withProgName
effectful/src/Effectful/FileSystem.hsnew file+347
@@ -0,0 +1,347 @@
1+module Effectful.FileSystem
2+ ( FileSystem
3+ , runFileSystem
4+
5+ -- * Actions on directories
6+ , createDirectory
7+ , createDirectoryIfMissing
8+ , removeDirectory
9+ , removeDirectoryRecursive
10+ , removePathForcibly
11+ , renameDirectory
12+ , listDirectory
13+ , getDirectoryContents
14+
15+ -- ** Current working directory
16+ , getCurrentDirectory
17+ , setCurrentDirectory
18+ , withCurrentDirectory
19+
20+ -- * Pre-defined directories
21+ , getHomeDirectory
22+ , getXdgDirectory
23+ , getXdgDirectoryList
24+ , getAppUserDataDirectory
25+ , getUserDocumentsDirectory
26+ , getTemporaryDirectory
27+
28+ -- * Actions on files
29+ , removeFile
30+ , renameFile
31+ , renamePath
32+ , copyFile
33+ , copyFileWithMetadata
34+ , getFileSize
35+ , canonicalizePath
36+ , makeAbsolute
37+ , makeRelativeToCurrentDirectory
38+
39+ -- * Existence tests
40+ , doesPathExist
41+ , doesFileExist
42+ , doesDirectoryExist
43+ , findExecutable
44+ , findExecutables
45+ , findExecutablesInDirectories
46+ , findFile
47+ , findFiles
48+ , findFileWith
49+ , findFilesWith
50+
51+ -- * Symbolic links
52+ , createFileLink
53+ , createDirectoryLink
54+ , removeDirectoryLink
55+ , pathIsSymbolicLink
56+ , getSymbolicLinkTarget
57+
58+ -- * Permissions
59+ , getPermissions
60+ , setPermissions
61+ , copyPermissions
62+
63+ -- * Timestamps
64+ , getAccessTime
65+ , getModificationTime
66+ , setAccessTime
67+ , setModificationTime
68+
69+ -- * Re-exports
70+
71+ -- ** Pre-defined directories
72+ , D.XdgDirectory(..)
73+ , D.XdgDirectoryList(..)
74+
75+ -- ** Existence tests
76+ , D.exeExtension
77+
78+ -- ** Permissions
79+ , D.Permissions
80+ , D.emptyPermissions
81+ , D.readable
82+ , D.writable
83+ , D.executable
84+ , D.searchable
85+ , D.setOwnerReadable
86+ , D.setOwnerWritable
87+ , D.setOwnerExecutable
88+ , D.setOwnerSearchable
89+ ) where
90+
91+import Data.Time (UTCTime)
92+import qualified System.Directory as D
93+
94+import Effectful.Dispatch.Static
95+import Effectful.Monad
96+
97+-- | An effect for interacting with the filesystem.
98+data FileSystem :: Effect where
99+ FileSystem :: FileSystem m r
100+
101+-- | Run the 'FileSystem' effect.
102+runFileSystem :: IOE :> es => Eff (FileSystem : es) a -> Eff es a
103+runFileSystem = evalData (DataA FileSystem)
104+
105+----------------------------------------
106+-- Actions on directories
107+
108+-- | Lifted 'D.createDirectory'.
109+createDirectory :: FileSystem :> es => FilePath -> Eff es ()
110+createDirectory = unsafeEff_ . D.createDirectory
111+
112+-- | Lifted 'D.createDirectoryIfMissing'.
113+createDirectoryIfMissing :: FileSystem :> es => Bool -> FilePath -> Eff es ()
114+createDirectoryIfMissing doCreateParents =
115+ unsafeEff_ . D.createDirectoryIfMissing doCreateParents
116+
117+-- | Lifted 'D.removeDirectory'.
118+removeDirectory :: FileSystem :> es => FilePath -> Eff es ()
119+removeDirectory = unsafeEff_ . D.removeDirectory
120+
121+-- | Lifted 'D.removeDirectoryRecursive'.
122+removeDirectoryRecursive :: FileSystem :> es => FilePath -> Eff es ()
123+removeDirectoryRecursive = unsafeEff_ . D.removeDirectoryRecursive
124+
125+-- | Lifted 'D.removePathForcibly'.
126+removePathForcibly :: FileSystem :> es => FilePath -> Eff es ()
127+removePathForcibly = unsafeEff_ . D.removePathForcibly
128+
129+-- | Lifted 'D.renameDirectory'.
130+renameDirectory :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
131+renameDirectory old = unsafeEff_ . D.renameDirectory old
132+
133+-- | Lifted 'D.listDirectory'.
134+listDirectory :: FileSystem :> es => FilePath -> Eff es [FilePath]
135+listDirectory = unsafeEff_ . D.listDirectory
136+
137+-- | Lifted 'D.getDirectoryContents'.
138+getDirectoryContents :: FileSystem :> es => FilePath -> Eff es [FilePath]
139+getDirectoryContents = unsafeEff_ . D.getDirectoryContents
140+
141+----------------------------------------
142+-- Current working directory
143+
144+-- | Lifted 'D.getCurrentDirectory'.
145+getCurrentDirectory :: FileSystem :> es => Eff es FilePath
146+getCurrentDirectory = unsafeEff_ D.getCurrentDirectory
147+
148+-- | Lifted 'D.setCurrentDirectory'.
149+setCurrentDirectory :: FileSystem :> es => FilePath -> Eff es ()
150+setCurrentDirectory = unsafeEff_ . D.setCurrentDirectory
151+
152+-- | Lifted 'D.withCurrentDirectory'.
153+withCurrentDirectory :: FileSystem :> es => FilePath -> Eff es a -> Eff es a
154+withCurrentDirectory path = unsafeLiftMapIO (D.withCurrentDirectory path)
155+
156+----------------------------------------
157+-- Pre-defined directories
158+
159+-- | Lifted 'D.getHomeDirectory'.
160+getHomeDirectory :: FileSystem :> es => Eff es FilePath
161+getHomeDirectory = unsafeEff_ D.getHomeDirectory
162+
163+-- | Lifted 'D.getXdgDirectory'.
164+getXdgDirectory
165+ :: FileSystem :> es
166+ => D.XdgDirectory
167+ -> FilePath
168+ -> Eff es FilePath
169+getXdgDirectory xdgDir = unsafeEff_ . D.getXdgDirectory xdgDir
170+
171+-- | Lifted 'D.getXdgDirectoryList'.
172+getXdgDirectoryList
173+ :: FileSystem :> es
174+ => D.XdgDirectoryList
175+ -> Eff es [FilePath]
176+getXdgDirectoryList = unsafeEff_ . D.getXdgDirectoryList
177+
178+-- | Lifted 'D.getAppUserDataDirectory'.
179+getAppUserDataDirectory :: FileSystem :> es => FilePath -> Eff es FilePath
180+getAppUserDataDirectory = unsafeEff_ . D.getAppUserDataDirectory
181+
182+-- | Lifted 'D.getUserDocumentsDirectory'.
183+getUserDocumentsDirectory :: FileSystem :> es => Eff es FilePath
184+getUserDocumentsDirectory = unsafeEff_ D.getUserDocumentsDirectory
185+
186+-- | Lifted 'D.getTemporaryDirectory'.
187+getTemporaryDirectory :: FileSystem :> es => Eff es FilePath
188+getTemporaryDirectory = unsafeEff_ D.getTemporaryDirectory
189+
190+----------------------------------------
191+-- Actions on files
192+
193+-- | Lifted 'D.removeFile'.
194+removeFile :: FileSystem :> es => FilePath -> Eff es ()
195+removeFile = unsafeEff_ . D.removeFile
196+
197+-- | Lifted 'D.renameFile'.
198+renameFile :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
199+renameFile old = unsafeEff_ . D.renameFile old
200+
201+-- | Lifted 'D.renamePath'.
202+renamePath :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
203+renamePath old = unsafeEff_ . D.renamePath old
204+
205+-- | Lifted 'D.copyFile'.
206+copyFile :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
207+copyFile src = unsafeEff_ . D.copyFile src
208+
209+-- | Lifted 'D.copyFileWithMetadata'.
210+copyFileWithMetadata :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
211+copyFileWithMetadata src = unsafeEff_ . D.copyFileWithMetadata src
212+
213+-- | Lifted 'D.getFileSize'.
214+getFileSize :: FileSystem :> es => FilePath -> Eff es Integer
215+getFileSize = unsafeEff_ . D.getFileSize
216+
217+-- | Lifted 'D.canonicalizePath'.
218+canonicalizePath :: FileSystem :> es => FilePath -> Eff es FilePath
219+canonicalizePath = unsafeEff_ . D.canonicalizePath
220+
221+-- | Lifted 'D.makeAbsolute'.
222+makeAbsolute :: FileSystem :> es => FilePath -> Eff es FilePath
223+makeAbsolute = unsafeEff_ . D.makeAbsolute
224+
225+-- | Lifted 'D.makeRelativeToCurrentDirectory'.
226+makeRelativeToCurrentDirectory
227+ :: FileSystem :> es
228+ => FilePath
229+ -> Eff es FilePath
230+makeRelativeToCurrentDirectory = unsafeEff_ . D.makeRelativeToCurrentDirectory
231+
232+----------------------------------------
233+-- Existence tests
234+
235+-- | Lifted 'D.doesPathExist'.
236+doesPathExist :: FileSystem :> es => FilePath -> Eff es Bool
237+doesPathExist = unsafeEff_ . D.doesPathExist
238+
239+-- | Lifted 'D.doesFileExist'.
240+doesFileExist :: FileSystem :> es => FilePath -> Eff es Bool
241+doesFileExist = unsafeEff_ . D.doesFileExist
242+
243+-- | Lifted 'D.doesDirectoryExist'.
244+doesDirectoryExist :: FileSystem :> es => FilePath -> Eff es Bool
245+doesDirectoryExist = unsafeEff_ . D.doesDirectoryExist
246+
247+-- | Lifted 'D.findExecutable'.
248+findExecutable :: FileSystem :> es => String -> Eff es (Maybe FilePath)
249+findExecutable = unsafeEff_ . D.findExecutable
250+
251+-- | Lifted 'D.findExecutables'.
252+findExecutables :: FileSystem :> es => String -> Eff es [FilePath]
253+findExecutables = unsafeEff_ . D.findExecutables
254+
255+-- | Lifted 'D.findExecutablesInDirectories'.
256+findExecutablesInDirectories
257+ :: FileSystem :> es
258+ => [FilePath]
259+ -> String
260+ -> Eff es [FilePath]
261+findExecutablesInDirectories dirs =
262+ unsafeEff_ . D.findExecutablesInDirectories dirs
263+
264+-- | Lifted 'D.findFile'.
265+findFile :: FileSystem :> es => [FilePath] -> String -> Eff es (Maybe FilePath)
266+findFile dirs = unsafeEff_ . D.findFile dirs
267+
268+-- | Lifted 'D.findFiles'.
269+findFiles :: FileSystem :> es => [FilePath] -> String -> Eff es [FilePath]
270+findFiles dirs = unsafeEff_ . D.findFiles dirs
271+
272+-- | Lifted 'D.findFileWith'.
273+findFileWith
274+ :: FileSystem :> es
275+ => (FilePath -> Eff es Bool)
276+ -> [FilePath]
277+ -> String
278+ -> Eff es (Maybe FilePath)
279+findFileWith p dirs n = unsafeUnliftIO $ \unlift -> do
280+ D.findFileWith (unlift . p) dirs n
281+
282+-- | Lifted 'D.findFilesWith'.
283+findFilesWith
284+ :: FileSystem :> es
285+ => (FilePath -> Eff es Bool)
286+ -> [FilePath]
287+ -> String
288+ -> Eff es [FilePath]
289+findFilesWith p dirs ns = unsafeUnliftIO $ \unlift -> do
290+ D.findFilesWith (unlift . p) dirs ns
291+
292+----------------------------------------
293+-- Symbolic links
294+
295+-- | Lifted 'D.createFileLink'.
296+createFileLink :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
297+createFileLink target = unsafeEff_ . D.createFileLink target
298+
299+-- | Lifted 'D.createDirectoryLink'.
300+createDirectoryLink :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
301+createDirectoryLink target = unsafeEff_ . D.createDirectoryLink target
302+
303+-- | Lifted 'D.removeDirectoryLink'.
304+removeDirectoryLink :: FileSystem :> es => FilePath -> Eff es ()
305+removeDirectoryLink = unsafeEff_ . D.removeDirectoryLink
306+
307+-- | Lifted 'D.pathIsSymbolicLink'.
308+pathIsSymbolicLink :: FileSystem :> es => FilePath -> Eff es Bool
309+pathIsSymbolicLink = unsafeEff_ . D.pathIsSymbolicLink
310+
311+-- | Lifted 'D.getSymbolicLinkTarget'.
312+getSymbolicLinkTarget :: FileSystem :> es => FilePath -> Eff es FilePath
313+getSymbolicLinkTarget = unsafeEff_ . D.getSymbolicLinkTarget
314+
315+----------------------------------------
316+-- Permissions
317+
318+-- | Lifted 'D.getPermissions'.
319+getPermissions :: FileSystem :> es => FilePath -> Eff es D.Permissions
320+getPermissions = unsafeEff_ . D.getPermissions
321+
322+-- | Lifted 'D.setPermissions'.
323+setPermissions :: FileSystem :> es => FilePath -> D.Permissions -> Eff es ()
324+setPermissions path = unsafeEff_ . D.setPermissions path
325+
326+-- | Lifted 'D.copyPermissions'.
327+copyPermissions :: FileSystem :> es => FilePath -> FilePath -> Eff es ()
328+copyPermissions src = unsafeEff_ . D.copyPermissions src
329+
330+----------------------------------------
331+-- Timestamps
332+
333+-- | Lifted 'D.getAccessTime'.
334+getAccessTime :: FileSystem :> es => FilePath -> Eff es UTCTime
335+getAccessTime = unsafeEff_ . D.getAccessTime
336+
337+-- | Lifted 'D.getModificationTime'.
338+getModificationTime :: FileSystem :> es => FilePath -> Eff es UTCTime
339+getModificationTime = unsafeEff_ . D.getModificationTime
340+
341+-- | Lifted 'D.setAccessTime'.
342+setAccessTime :: FileSystem :> es => FilePath -> UTCTime -> Eff es ()
343+setAccessTime path = unsafeEff_ . D.setAccessTime path
344+
345+-- | Lifted 'D.setModificationTime'.
346+setModificationTime :: FileSystem :> es => FilePath -> UTCTime -> Eff es ()
347+setModificationTime path = unsafeEff_ . D.setModificationTime path
effectful/src/Effectful/FileSystem/Effect.hsnew file+15
@@ -0,0 +1,15 @@
1+module Effectful.FileSystem.Effect
2+ ( FileSystem
3+ , runFileSystem
4+ ) where
5+
6+import Effectful.Dispatch.Static
7+import Effectful.Monad
8+
9+-- | An effect for interacting with the filesystem.
10+data FileSystem :: Effect where
11+ FileSystem :: FileSystem m r
12+
13+-- | Run the 'FileSystem' effect.
14+runFileSystem :: IOE :> es => Eff (FileSystem : es) a -> Eff es a
15+runFileSystem = evalData (DataA FileSystem)
effectful/src/Effectful/FileSystem/IO.hsnew file+143
@@ -0,0 +1,143 @@
1+-- | Lifted version of "System.IO".
2+module Effectful.FileSystem.IO
3+ ( FileSystem
4+ , runFileSystem
5+
6+ -- * IO
7+ , IOMode (..)
8+ , Handle
9+ , IO.stdin
10+ , IO.stdout
11+ , IO.stderr
12+ , withFile
13+ , withBinaryFile
14+ , openFile
15+ , hClose
16+ , hFlush
17+ , hFileSize
18+ , hSetFileSize
19+ , hIsEOF
20+ , IO.BufferMode (..)
21+ , hSetBuffering
22+ , hGetBuffering
23+ , hSeek
24+ , IO.SeekMode (..)
25+ , hTell
26+ , hIsOpen
27+ , hIsClosed
28+ , hIsReadable
29+ , hIsWritable
30+ , hIsSeekable
31+ , hIsTerminalDevice
32+ , hSetEcho
33+ , hGetEcho
34+ , hWaitForInput
35+ , hReady
36+ ) where
37+
38+import qualified System.IO as IO
39+import System.IO (Handle, IOMode (..))
40+
41+import Effectful.Dispatch.Static
42+import Effectful.FileSystem.Effect
43+import Effectful.Monad
44+
45+-- | Lifted version of 'IO.withFile'.
46+withFile
47+ :: FileSystem :> es
48+ => FilePath
49+ -> IOMode
50+ -> (Handle -> Eff es a)
51+ -> Eff es a
52+withFile fp mode inner = unsafeUnliftIO $ \unlift -> do
53+ IO.withFile fp mode $ unlift . inner
54+
55+-- | Lifted version of 'IO.withBinaryFile'.
56+withBinaryFile
57+ :: FileSystem :> es
58+ => FilePath
59+ -> IOMode
60+ -> (Handle -> Eff es a)
61+ -> Eff es a
62+withBinaryFile fp mode inner = unsafeUnliftIO $ \unlift -> do
63+ IO.withBinaryFile fp mode $ unlift . inner
64+
65+-- | Lifted version of 'IO.openFile'
66+openFile :: FileSystem :> es => FilePath -> IOMode -> Eff es Handle
67+openFile fp = unsafeEff_ . IO.openFile fp
68+
69+-- | Lifted version of 'IO.hClose'
70+hClose :: FileSystem :> es => Handle -> Eff es ()
71+hClose = unsafeEff_ . IO.hClose
72+
73+-- | Lifted version of 'IO.hFlush'
74+hFlush :: FileSystem :> es => Handle -> Eff es ()
75+hFlush = unsafeEff_ . IO.hFlush
76+
77+-- | Lifted version of 'IO.hFileSize'
78+hFileSize :: FileSystem :> es => Handle -> Eff es Integer
79+hFileSize = unsafeEff_ . IO.hFileSize
80+
81+-- | Lifted version of 'IO.hSetFileSize'
82+hSetFileSize :: FileSystem :> es => Handle -> Integer -> Eff es ()
83+hSetFileSize h = unsafeEff_ . IO.hSetFileSize h
84+
85+-- | Lifted version of 'IO.hIsEOF'
86+hIsEOF :: FileSystem :> es => Handle -> Eff es Bool
87+hIsEOF = unsafeEff_ . IO.hIsEOF
88+
89+-- | Lifted version of 'IO.hSetBuffering'
90+hSetBuffering :: FileSystem :> es => Handle -> IO.BufferMode -> Eff es ()
91+hSetBuffering h = unsafeEff_ . IO.hSetBuffering h
92+
93+-- | Lifted version of 'IO.hGetBuffering'
94+hGetBuffering :: FileSystem :> es => Handle -> Eff es IO.BufferMode
95+hGetBuffering = unsafeEff_ . IO.hGetBuffering
96+
97+-- | Lifted version of 'IO.hSeek'
98+hSeek :: FileSystem :> es => Handle -> IO.SeekMode -> Integer -> Eff es ()
99+hSeek h s = unsafeEff_ . IO.hSeek h s
100+
101+-- | Lifted version of 'IO.hTell'
102+hTell :: FileSystem :> es => Handle -> Eff es Integer
103+hTell = unsafeEff_ . IO.hTell
104+
105+-- | Lifted version of 'IO.hIsOpen'
106+hIsOpen :: FileSystem :> es => Handle -> Eff es Bool
107+hIsOpen = unsafeEff_ . IO.hIsOpen
108+
109+-- | Lifted version of 'IO.hIsClosed'
110+hIsClosed :: FileSystem :> es => Handle -> Eff es Bool
111+hIsClosed = unsafeEff_ . IO.hIsClosed
112+
113+-- | Lifted version of 'IO.hIsReadable'
114+hIsReadable :: FileSystem :> es => Handle -> Eff es Bool
115+hIsReadable = unsafeEff_ . IO.hIsReadable
116+
117+-- | Lifted version of 'IO.hIsWritable'
118+hIsWritable :: FileSystem :> es => Handle -> Eff es Bool
119+hIsWritable = unsafeEff_ . IO.hIsWritable
120+
121+-- | Lifted version of 'IO.hIsSeekable'
122+hIsSeekable :: FileSystem :> es => Handle -> Eff es Bool
123+hIsSeekable = unsafeEff_ . IO.hIsSeekable
124+
125+-- | Lifted version of 'IO.hIsTerminalDevice'
126+hIsTerminalDevice :: FileSystem :> es => Handle -> Eff es Bool
127+hIsTerminalDevice = unsafeEff_ . IO.hIsTerminalDevice
128+
129+-- | Lifted version of 'IO.hSetEcho'
130+hSetEcho :: FileSystem :> es => Handle -> Bool -> Eff es ()
131+hSetEcho h = unsafeEff_ . IO.hSetEcho h
132+
133+-- | Lifted version of 'IO.hGetEcho'
134+hGetEcho :: FileSystem :> es => Handle -> Eff es Bool
135+hGetEcho = unsafeEff_ . IO.hGetEcho
136+
137+-- | Lifted version of 'IO.hWaitForInput'
138+hWaitForInput :: FileSystem :> es => Handle -> Int -> Eff es Bool
139+hWaitForInput h = unsafeEff_ . IO.hWaitForInput h
140+
141+-- | Lifted version of 'IO.hReady'
142+hReady :: FileSystem :> es => Handle -> Eff es Bool
143+hReady = unsafeEff_ . IO.hReady
effectful/src/Effectful/Process.hsnew file+182
@@ -0,0 +1,182 @@
1+{-# LANGUAGE CPP #-}
2+-- | Lifted version of "System.Process".
3+module Effectful.Process
4+ ( Process
5+ , runProcess
6+
7+ -- * Running sub-processes
8+ , createProcess
9+ , createProcess_
10+ , P.shell
11+ , P.proc
12+ , P.CreateProcess(..)
13+ , P.CmdSpec(..)
14+ , P.StdStream(..)
15+ , P.ProcessHandle
16+
17+ -- ** Simpler functions for common tasks
18+ , callProcess
19+ , callCommand
20+ , spawnProcess
21+ , spawnCommand
22+ , readCreateProcess
23+ , readProcess
24+ , readCreateProcessWithExitCode
25+ , readProcessWithExitCode
26+ , withCreateProcess
27+ , cleanupProcess
28+
29+ -- ** Related utilities
30+ , P.showCommandForUser
31+ , P.Pid
32+ , getPid
33+#if MIN_VERSION_process(1,6,12)
34+ , getCurrentPid
35+#endif
36+
37+ -- * Process completion
38+ , waitForProcess
39+ , getProcessExitCode
40+ , terminateProcess
41+ , interruptProcessGroupOf
42+
43+ -- * Interprocess communication
44+ , createPipe
45+ , createPipeFd
46+ ) where
47+
48+import System.Exit (ExitCode)
49+import System.IO (Handle)
50+import System.Posix.Internals (FD)
51+import qualified System.Process as P
52+
53+import Effectful.Dispatch.Static
54+import Effectful.Monad
55+
56+-- | An effect for running child processes using the @process@ library.
57+data Process :: Effect where
58+ Process :: Process m r
59+
60+runProcess :: IOE :> es => Eff (Process : es) a -> Eff es a
61+runProcess = evalData (DataA Process)
62+
63+----------------------------------------
64+-- Running sub-processes
65+
66+-- | Lifted 'P.createProcess'.
67+createProcess
68+ :: Process :> es
69+ => P.CreateProcess
70+ -> Eff es (Maybe Handle, Maybe Handle, Maybe Handle, P.ProcessHandle)
71+createProcess = unsafeEff_ . P.createProcess
72+
73+-- | Lifted 'P.createProcess_'.
74+createProcess_
75+ :: Process :> es
76+ => String
77+ -> P.CreateProcess
78+ -> Eff es (Maybe Handle, Maybe Handle, Maybe Handle, P.ProcessHandle)
79+createProcess_ msg = unsafeEff_ . P.createProcess_ msg
80+
81+----------------------------------------
82+-- Simpler functions for common tasks
83+
84+-- | Lifted 'P.callProcess'.
85+callProcess :: Process :> es => FilePath -> [String] -> Eff es ()
86+callProcess fp = unsafeEff_ . P.callProcess fp
87+
88+-- | Lifted 'P.callCommand'.
89+callCommand :: Process :> es => String -> Eff es ()
90+callCommand = unsafeEff_ . P.callCommand
91+
92+-- | Lifted 'P.spawnProcess'.
93+spawnProcess :: Process :> es => FilePath -> [String] -> Eff es P.ProcessHandle
94+spawnProcess fp = unsafeEff_ . P.spawnProcess fp
95+
96+-- | Lifted 'P.spawnCommand'.
97+spawnCommand :: Process :> es => String -> Eff es P.ProcessHandle
98+spawnCommand = unsafeEff_ . P.spawnCommand
99+
100+-- | Lifted 'P.readCreateProcess'.
101+readCreateProcess :: Process :> es => P.CreateProcess -> String -> Eff es String
102+readCreateProcess cp = unsafeEff_ . P.readCreateProcess cp
103+
104+-- | Lifted 'P.readProcess'.
105+readProcess :: Process :> es => FilePath -> [String] -> String -> Eff es String
106+readProcess fp args = unsafeEff_ . P.readProcess fp args
107+
108+-- | Lifted 'P.readCreateProcessWithExitCode'.
109+readCreateProcessWithExitCode
110+ :: Process :> es
111+ => P.CreateProcess
112+ -> String
113+ -> Eff es (ExitCode, String, String)
114+readCreateProcessWithExitCode cp = unsafeEff_ . P.readCreateProcessWithExitCode cp
115+
116+-- | Lifted 'P.readProcessWithExitCode'.
117+readProcessWithExitCode
118+ :: Process :> es
119+ => FilePath
120+ -> [String]
121+ -> String
122+ -> Eff es (ExitCode, String, String)
123+readProcessWithExitCode fp args = unsafeEff_ . P.readProcessWithExitCode fp args
124+
125+-- | Lifted 'P.withCreateProcess'.
126+withCreateProcess
127+ :: Process :> es
128+ => P.CreateProcess
129+ -> (Maybe Handle -> Maybe Handle -> Maybe Handle -> P.ProcessHandle -> Eff es a)
130+ -> Eff es a
131+withCreateProcess cp cb = unsafeUnliftIO $ \unlift -> do
132+ P.withCreateProcess cp $ \inh outh errh ph -> unlift $ cb inh outh errh ph
133+
134+-- | Lifted 'P.cleanupProcess'.
135+cleanupProcess
136+ :: Process :> es
137+ => (Maybe Handle, Maybe Handle, Maybe Handle, P.ProcessHandle)
138+ -> Eff es ()
139+cleanupProcess = unsafeEff_ . P.cleanupProcess
140+
141+----------------------------------------
142+-- Related utilities
143+
144+-- | Lifted 'P.getPid'.
145+getPid :: Process :> es => P.ProcessHandle -> Eff es (Maybe P.Pid)
146+getPid = unsafeEff_ . P.getPid
147+
148+#if MIN_VERSION_process(1,6,12)
149+-- | Lifted 'P.getCurrentPid'.
150+getCurrentPid :: Process :> es => Eff es P.Pid
151+getCurrentPid = unsafeEff_ P.getCurrentPid
152+#endif
153+
154+----------------------------------------
155+-- Process completion
156+
157+-- | Lifted 'P.waitForProcess'.
158+waitForProcess :: Process :> es => P.ProcessHandle -> Eff es ExitCode
159+waitForProcess = unsafeEff_ . P.waitForProcess
160+
161+-- | Lifted 'P.getProcessExitCode'.
162+getProcessExitCode :: Process :> es => P.ProcessHandle -> Eff es (Maybe ExitCode)
163+getProcessExitCode = unsafeEff_ . P.getProcessExitCode
164+
165+-- | Lifted 'P.terminateProcess'.
166+terminateProcess :: Process :> es => P.ProcessHandle -> Eff es ()
167+terminateProcess = unsafeEff_ . P.terminateProcess
168+
169+-- | Lifted 'P.interruptProcessGroupOf'.
170+interruptProcessGroupOf :: Process :> es => P.ProcessHandle -> Eff es ()
171+interruptProcessGroupOf = unsafeEff_ . P.interruptProcessGroupOf
172+
173+----------------------------------------
174+-- Interprocess communication
175+
176+-- | Lifted 'P.createPipe'.
177+createPipe :: Process :> es => Eff es (Handle, Handle)
178+createPipe = unsafeEff_ P.createPipe
179+
180+-- | Lifted 'P.createPipeFd'.
181+createPipeFd :: Process :> es => Eff es (FD, FD)
182+createPipeFd = unsafeEff_ P.createPipeFd
src/Effectful/Resource.hs → effectful/src/Effectful/Resource.hsrenamed+31−7
@@ -11,15 +11,21 @@ module Effectful.Resource
11 , R.register
11 , R.register
12 , R.release
12 , R.release
13 , R.unprotect
13 , R.unprotect
14+
15+ -- * Internal state
16+ , R.InternalState
17+ , getInternalState
18+ , runInternalState
19+ , R.createInternalState
20+ , R.closeInternalState
14 ) where
21 ) where
15
22
16import Control.Exception
23import Control.Exception
17import qualified Control.Monad.Trans.Resource as R
24import qualified Control.Monad.Trans.Resource as R
18import qualified Control.Monad.Trans.Resource.Internal as RI
25import qualified Control.Monad.Trans.Resource.Internal as RI
19
26
20−import Effectful.Internal.Effect
27+import Effectful.Dispatch.Static
21−import Effectful.Internal.Env
22−import Effectful.Internal.Monad
28+import Effectful.Monad
23
29
24-- | Data tag for a resource effect.
30-- | Data tag for a resource effect.
25newtype Resource :: Effect where
31newtype Resource :: Effect where
@@ -31,15 +37,33 @@ runResource m = unsafeEff $ \es0 -> do
31 size0 <- sizeEnv es0
37 size0 <- sizeEnv es0
32 istate <- R.createInternalState
38 istate <- R.createInternalState
33 mask $ \restore -> do
39 mask $ \restore -> do
34− es <- unsafeConsEnv (IdE (Resource istate)) noRelinker es0
40+ es <- unsafeConsEnv (DataA (Resource istate)) noRelinker es0
35 a <- restore (unEff m es) `catch` \e -> do
41 a <- restore (unEff m es) `catch` \e -> do
36− _ <- unsafeTailEnv size0 es
42+ unsafeTailEnv size0 es
37 RI.stateCleanupChecked (Just e) istate
43 RI.stateCleanupChecked (Just e) istate
38 throwIO e
44 throwIO e
39− _ <- unsafeTailEnv size0 es
45+ unsafeTailEnv size0 es
40 RI.stateCleanupChecked Nothing istate
46 RI.stateCleanupChecked Nothing istate
41 pure a
47 pure a
42
48
49+----------------------------------------
50+-- Internal state
51+
52+-- | Get the 'R.InternalState' of the current 'Resource' effect.
53+getInternalState :: Resource :> es => Eff es R.InternalState
54+getInternalState = do
55+ DataA (Resource istate) <- getData
56+ pure istate
57+
58+-- | Run the 'Resource' effect with existing 'R.InternalState'.
59+--
60+-- /Note:/ the 'R.InternalState' will not be closed at the end.
61+runInternalState :: R.InternalState -> Eff (Resource : es) a -> Eff es a
62+runInternalState istate = evalData (DataA (Resource istate))
63+
64+----------------------------------------
65+-- Orphan instance
66+
43instance (IOE :> es, Resource :> es) => R.MonadResource (Eff es) where
67instance (IOE :> es, Resource :> es) => R.MonadResource (Eff es) where
44 liftResourceT (RI.ResourceT m) = unsafeEff $ \es -> do
68 liftResourceT (RI.ResourceT m) = unsafeEff $ \es -> do
45− getEnv es >>= \(IdE (Resource istate)) -> m istate
69+ getEnv es >>= \(DataA (Resource istate)) -> m istate
effectful/src/Effectful/Temporary.hsnew file+70
@@ -0,0 +1,70 @@
1+module Effectful.Temporary
2+ ( Temporary
3+ , runTemporary
4+ , withSystemTempFile
5+ , withSystemTempDirectory
6+ , withTempFile
7+ , withTempDirectory
8+ ) where
9+
10+import System.IO
11+import qualified UnliftIO.Temporary as T
12+
13+import Effectful.Dispatch.Static
14+import Effectful.Monad
15+
16+-- | An effect for interacting with temporary files.
17+data Temporary :: Effect where
18+ Temporary :: Temporary m r
19+
20+-- | Run the 'Temporary' effect.
21+runTemporary :: IOE :> es => Eff (Temporary : es) a -> Eff es a
22+runTemporary = evalData (DataA Temporary)
23+
24+-- | Lifted 'T.withSystemTempFile'.
25+withSystemTempFile
26+ :: Temporary :> es
27+ => String
28+ -- ^ File name template. See 'openTempFile'.
29+ -> (FilePath -> Handle -> Eff es a)
30+ -- ^ Callback that can use the file.
31+ -> Eff es a
32+withSystemTempFile template action = unsafeUnliftIO $ \unlift -> do
33+ T.withSystemTempFile template $ \fp handle -> unlift $ action fp handle
34+
35+-- | Lifted 'T.withSystemTempDirectory'.
36+withSystemTempDirectory
37+ :: Temporary :> es
38+ => String
39+ -- ^ Directory name template. See 'openTempFile'.
40+ -> (FilePath -> Eff es a)
41+ -- ^ Callback that can use the directory.
42+ -> Eff es a
43+withSystemTempDirectory template action = unsafeUnliftIO $ \unlift -> do
44+ T.withSystemTempDirectory template $ \fp -> unlift $ action fp
45+
46+-- | Lifted 'T.withTempFile'.
47+withTempFile
48+ :: Temporary :> es
49+ => FilePath
50+ -- ^ Temp dir to create the file in.
51+ -> String
52+ -- ^ File name template. See 'openTempFile'.
53+ -> (FilePath -> Handle -> Eff es a)
54+ -- ^ Callback that can use the file.
55+ -> Eff es a
56+withTempFile tmpDir template action = unsafeUnliftIO $ \unlift -> do
57+ T.withTempFile tmpDir template $ \fp handle -> unlift $ action fp handle
58+
59+-- | Lifted 'T.withTempDirectory'.
60+withTempDirectory
61+ :: Temporary :> es
62+ => FilePath
63+ -- ^ Temp directory to create the directory in.
64+ -> String
65+ -- ^ Directory name template. See 'openTempFile'.
66+ -> (FilePath -> Eff es a)
67+ -- ^ Callback that can use the directory.
68+ -> Eff es a
69+withTempDirectory tmpDir template action = unsafeUnliftIO $ \unlift -> do
70+ T.withTempDirectory tmpDir template $ \fp -> unlift $ action fp
effectful/src/Effectful/Timeout.hsnew file+28
@@ -0,0 +1,28 @@
1+module Effectful.Timeout
2+ ( Timeout
3+ , runTimeout
4+ , timeout
5+ ) where
6+
7+import qualified System.Timeout as T
8+
9+import Effectful.Dispatch.Static
10+import Effectful.Monad
11+
12+-- | An effect for timing out computations.
13+data Timeout :: Effect where
14+ Timeout :: Timeout m r
15+
16+-- | Run the 'Timeout' effect.
17+runTimeout :: IOE :> es => Eff (Timeout : es) a -> Eff es a
18+runTimeout = evalData (DataA Timeout)
19+
20+-- | Lifted 'T.timeout'.
21+timeout
22+ :: Timeout :> es
23+ => Int
24+ -- ^ The timeout in microseconds (1/10^6 seconds).
25+ -> Eff es a
26+ -- ^ The computation the timeout applies to.
27+ -> Eff es (Maybe a)
28+timeout = unsafeLiftMapIO . T.timeout
tests/AsyncTests.hs → effectful/tests/AsyncTests.hsrenamed+6−7
@@ -2,13 +2,12 @@ module AsyncTests (asyncTests) where
2
2
3import Control.Concurrent (threadDelay)
3import Control.Concurrent (threadDelay)
4import Control.Monad
4import Control.Monad
5−import Control.Monad.IO.Class
6import Test.Tasty
5import Test.Tasty
7import Test.Tasty.HUnit
6import Test.Tasty.HUnit
8import qualified Data.Set as S
7import qualified Data.Set as S
9
8
10import Effectful
9import Effectful
11−import Effectful.Async
10+import Effectful.Concurrent.Async
12import Effectful.Error
11import Effectful.Error
13import Effectful.State.Dynamic
12import Effectful.State.Dynamic
14
13
@@ -24,7 +23,7 @@ asyncTests = testGroup "Async"
24 ]
23 ]
25
24
26test_localState :: Assertion
25test_localState :: Assertion
27−test_localState = runEff . runAsyncE . evalLocalState x $ do
26+test_localState = runEff . runConcurrent . evalLocalState x $ do
28 replicateConcurrently_ 2 $ do
27 replicateConcurrently_ 2 $ do
29 r <- goDownward 0
28 r <- goDownward 0
30 U.assertEqual "expected result" x r
29 U.assertEqual "expected result" x r
@@ -42,7 +41,7 @@ test_localState = runEff . runAsyncE . evalLocalState x $ do
42 else goDownward $ acc + 1
41 else goDownward $ acc + 1
43
42
44test_sharedState :: Assertion
43test_sharedState :: Assertion
45−test_sharedState = runEff . runAsyncE . evalSharedState (S.empty @Int) $ do
44+test_sharedState = runEff . runConcurrent . evalSharedState (S.empty @Int) $ do
46 concurrently_ (addWhen even x) (addWhen odd x)
45 concurrently_ (addWhen even x) (addWhen odd x)
47 U.assertEqual "expected result" (S.fromList [1..x]) =<< get
46 U.assertEqual "expected result" (S.fromList [1..x]) =<< get
48 where
47 where
@@ -58,7 +57,7 @@ test_sharedState = runEff . runAsyncE . evalSharedState (S.empty @Int) $ do
58 addWhen f $ n - 1
57 addWhen f $ n - 1
59
58
60test_errorHandling :: Assertion
59test_errorHandling :: Assertion
61−test_errorHandling = runEff . runAsyncE . evalSharedState (0::Int) $ do
60+test_errorHandling = runEff . runConcurrent . evalSharedState (0::Int) $ do
62 r <- runError $ concurrently_
61 r <- runError $ concurrently_
63 (liftIO (threadDelay 10000) >> throwError err)
62 (liftIO (threadDelay 10000) >> throwError err)
64 (modify (+x))
63 (modify (+x))
@@ -74,7 +73,7 @@ test_errorHandling = runEff . runAsyncE . evalSharedState (0::Int) $ do
74 err = "thrown from async"
73 err = "thrown from async"
75
74
76test_asyncWithUnmask :: Assertion
75test_asyncWithUnmask :: Assertion
77−test_asyncWithUnmask = runEff . runAsyncE . evalLocalState "initial" $ do
76+test_asyncWithUnmask = runEff . runConcurrent . evalLocalState "initial" $ do
78 x <- asyncWithUnmask $ \unmask -> do
77 x <- asyncWithUnmask $ \unmask -> do
79 liftIO $ threadDelay 10000
78 liftIO $ threadDelay 10000
80 r1 <- get @String -- 2
79 r1 <- get @String -- 2
@@ -89,7 +88,7 @@ test_asyncWithUnmask = runEff . runAsyncE . evalLocalState "initial" $ do
89 (inner1, inner2, outer)
88 (inner1, inner2, outer)
90
89
91test_pooledWorkers :: Assertion
90test_pooledWorkers :: Assertion
92−test_pooledWorkers = runEff . runAsyncE . evalLocalState (0::Int) $ do
91+test_pooledWorkers = runEff . runConcurrent . evalLocalState (0::Int) $ do
93 x <- pooledForConcurrentlyN threads [1..n] $ \k -> do
92 x <- pooledForConcurrentlyN threads [1..n] $ \k -> do
94 r <- get @Int
93 r <- get @Int
95 modify @Int (+1)
94 modify @Int (+1)
tests/ConcurrencyTests.hs → effectful/tests/ConcurrencyTests.hsrenamed−1
@@ -2,7 +2,6 @@ module ConcurrencyTests (concurrencyTests) where
2
2
3import Control.Concurrent (threadDelay)
3import Control.Concurrent (threadDelay)
4import Control.Monad
4import Control.Monad
5−import Control.Monad.IO.Class
6import Test.Tasty
5import Test.Tasty
7import Test.Tasty.HUnit
6import Test.Tasty.HUnit
8import UnliftIO
7import UnliftIO
effectful/tests/EnvironmentTests.hsnew file+48
@@ -0,0 +1,48 @@
1+module EnvironmentTests (environmentTests) where
2+
3+import Test.Tasty
4+import Test.Tasty.HUnit
5+import System.IO.Error (isDoesNotExistError)
6+
7+import Effectful
8+import Effectful.Environment
9+import qualified Utils as U
10+
11+environmentTests :: TestTree
12+environmentTests = testCaseSteps "Environment" $ \step -> do
13+ -- These tests need to be run sequentially because of
14+ -- https://github.com/arybczak/effectful/issues/39.
15+ step "set and get an environment variable"
16+ test_setAndGet
17+ step "unset and try to get an environment variable"
18+ test_unsetAndGet
19+ step "execute effects with custom arguments"
20+ test_withArgs
21+ step "execute effects with custom program name"
22+ test_withProg
23+
24+test_setAndGet :: Assertion
25+test_setAndGet = runEff . runEnvironment $ do
26+ let expected = "value"
27+ n = "EFFECTFUL_TEST1"
28+ setEnv n expected
29+ v <- getEnv n
30+ U.assertEqual "environment variable not set" expected v
31+
32+test_unsetAndGet :: Assertion
33+test_unsetAndGet = runEff . runEnvironment $ do
34+ let n = "EFFECTFUL_TEST2"
35+ unsetEnv n
36+ U.assertThrows "environment variable is set" isDoesNotExistError (getEnv n)
37+
38+test_withArgs :: Assertion
39+test_withArgs = runEff . runEnvironment $ do
40+ let expected = ["effectful-test"]
41+ args <- withArgs expected getArgs
42+ U.assertEqual "correct arguments" expected args
43+
44+test_withProg :: Assertion
45+test_withProg = runEff . runEnvironment $ do
46+ let expected = "effectful-test"
47+ n <- withProgName expected getProgName
48+ U.assertEqual "correct program name" expected n
tests/ErrorTests.hs → effectful/tests/ErrorTests.hsrenamed+2−3
@@ -1,9 +1,7 @@
1module ErrorTests (errorTests) where
1module ErrorTests (errorTests) where
2
2
3−import Control.Monad.IO.Class
4import Test.Tasty
3import Test.Tasty
5import Test.Tasty.HUnit
4import Test.Tasty.HUnit
6−import GHC.Stack (getCallStack)
7
5
8import Effectful
6import Effectful
9import Effectful.Error
7import Effectful.Error
@@ -32,4 +30,5 @@ nestedErr :: (HasCallStack, NestedErr :> es) => Eff es ()
32nestedErr = send NestedErr
30nestedErr = send NestedErr
33
31
34runNestedErr :: Error String :> es => Eff (NestedErr : es) a -> Eff es a
32runNestedErr :: Error String :> es => Eff (NestedErr : es) a -> Eff es a
33+runNestedErr = interpret $ \_ -> \case
35−runNestedErr = interpret $ \NestedErr -> throwError "nested error"
34+ NestedErr -> throwError "nested error"
tests/Main.hs → effectful/tests/Main.hsrenamed+6
@@ -4,13 +4,19 @@ import Test.Tasty
4
4
5import AsyncTests
5import AsyncTests
6import ConcurrencyTests
6import ConcurrencyTests
7+import EnvironmentTests
7import ErrorTests
8import ErrorTests
8import StateTests
9import StateTests
10+import TimeoutTests
11+import UnliftTests
9
12
10main :: IO ()
13main :: IO ()
11main = defaultMain $ testGroup "effectful"
14main = defaultMain $ testGroup "effectful"
12 [ asyncTests
15 [ asyncTests
13 , concurrencyTests
16 , concurrencyTests
17+ , environmentTests
14 , errorTests
18 , errorTests
15 , stateTests
19 , stateTests
20+ , timeoutTests
21+ , unliftTests
16 ]
22 ]
tests/StateTests.hs → effectful/tests/StateTests.hsrenamed+2−1
@@ -97,6 +97,7 @@ test_localEffects = runEff $ do
97 where
97 where
98 expected :: Int
98 expected :: Int
99 expected = 4
99 expected = 4
100+
100----------------------------------------
101----------------------------------------
101-- Helpers
102-- Helpers
102
103
@@ -113,7 +114,7 @@ putInt = send . PutInt
113runHasInt :: Int -> Eff (HasInt : es) a -> Eff es a
114runHasInt :: Int -> Eff (HasInt : es) a -> Eff es a
114runHasInt n =
115runHasInt n =
115 -- reinterpret with redundant local effects
116 -- reinterpret with redundant local effects
116− reinterpret (evalState () . evalState n . evalState True) $ \case
117+ reinterpret (evalState () . evalState n . evalState True) $ \_ -> \case
117 GetInt -> get
118 GetInt -> get
118 PutInt i -> put i
119 PutInt i -> put i
119
120
effectful/tests/TimeoutTests.hsnew file+25
@@ -0,0 +1,25 @@
1+module TimeoutTests (timeoutTests) where
2+
3+import Control.Concurrent (threadDelay)
4+import Test.Tasty
5+import Test.Tasty.HUnit
6+
7+import Effectful
8+import Effectful.Timeout
9+import qualified Utils as U
10+
11+timeoutTests :: TestTree
12+timeoutTests = testGroup "Timeout"
13+ [ testCase "return before timeout" test_returnBeforeTimeout
14+ , testCase "timeout before return" test_timeoutBeforeReturn
15+ ]
16+
17+test_returnBeforeTimeout :: Assertion
18+test_returnBeforeTimeout = runEff $ do
19+ result <- runTimeout $ timeout 1000 $ return ()
20+ U.assertEqual "return value" (Just ()) result
21+
22+test_timeoutBeforeReturn :: Assertion
23+test_timeoutBeforeReturn = runEff $ do
24+ result <- runTimeout $ timeout 0 $ liftIO $ threadDelay 1000
25+ U.assertEqual "no return value" Nothing result
effectful/tests/UnliftTests.hsnew file+93
@@ -0,0 +1,93 @@
1+module UnliftTests (unliftTests) where
2+
3+import Control.Exception
4+import Test.Tasty
5+import Test.Tasty.HUnit
6+import qualified UnliftIO.Async as A
7+
8+import Effectful
9+import qualified Utils as U
10+
11+unliftTests :: TestTree
12+unliftTests = testGroup "Unlift"
13+ [ testCase "Reset strategy in new thread" test_resetStrategy
14+ , testCase "SeqUnlift in new thread" test_seqUnliftInNewThread
15+ , testGroup "Ephemeral strategy"
16+ [ testCase "Invalid limit" test_ephemeralInvalid
17+ , testCase "Uses in same thread" test_ephemeralSameThread
18+ , testCase "Uses in multiple threads" test_ephemeralMultipleThreads
19+ ]
20+ , testGroup "Persistent strategy"
21+ [ testCase "Invalid limit" test_persistentInvalid
22+ , testCase "Uses in same thread" test_persistentSameThread
23+ , testCase "Uses in multiple threads" test_persistentMultipleThreads
24+ ]
25+ ]
26+
27+test_resetStrategy :: Assertion
28+test_resetStrategy = runEff $ do
29+ s <- withUnliftStrategy (ConcUnlift Ephemeral Unlimited) $ do
30+ withEffToIO $ \runInIO -> do
31+ inThread $ runInIO unliftStrategy
32+ U.assertEqual "correct strategy" SeqUnlift s
33+
34+test_seqUnliftInNewThread :: Assertion
35+test_seqUnliftInNewThread = runEff $ do
36+ assertThrowsUnliftError "InvalidUseOfSeqUnlift error" $ do
37+ withUnliftStrategy SeqUnlift $ do
38+ withEffToIO $ \runInIO -> do
39+ inThread $ runInIO $ return ()
40+
41+test_ephemeralInvalid :: Assertion
42+test_ephemeralInvalid = runEff $ do
43+ assertThrowsUnliftError "InvalidNumberOfUses error" $ do
44+ withUnliftStrategy (ConcUnlift Ephemeral $ Limited 0) $ do
45+ withEffToIO $ \_ -> return ()
46+
47+test_ephemeralSameThread :: Assertion
48+test_ephemeralSameThread = runEff $ do
49+ assertThrowsUnliftError "ExceededNumberOfUses error" $ do
50+ withUnliftStrategy (ConcUnlift Ephemeral $ Limited 1) $ do
51+ withEffToIO $ \runInIO -> inThread $ do
52+ runInIO $ return ()
53+ runInIO $ return ()
54+
55+test_ephemeralMultipleThreads :: Assertion
56+test_ephemeralMultipleThreads = runEff $ do
57+ assertThrowsUnliftError "ExceededNumberOfUses error" $ do
58+ withUnliftStrategy (ConcUnlift Ephemeral $ Limited 1) $ do
59+ withEffToIO $ \runInIO -> do
60+ inThread $ runInIO $ return ()
61+ inThread $ runInIO $ return ()
62+
63+test_persistentInvalid :: Assertion
64+test_persistentInvalid = runEff $ do
65+ assertThrowsUnliftError "InvalidNumberOfThreads error" $ do
66+ withUnliftStrategy (ConcUnlift Persistent $ Limited 0) $ do
67+ withEffToIO $ \_ -> return ()
68+
69+test_persistentSameThread :: Assertion
70+test_persistentSameThread = runEff $ do
71+ withUnliftStrategy (ConcUnlift Persistent $ Limited 1) $ do
72+ withEffToIO $ \runInIO -> inThread $ do
73+ runInIO $ return ()
74+ runInIO $ return ()
75+
76+test_persistentMultipleThreads :: Assertion
77+test_persistentMultipleThreads = runEff $ do
78+ assertThrowsUnliftError "ExceededNumberOfThreads error" $ do
79+ withUnliftStrategy (ConcUnlift Persistent $ Limited 1) $ do
80+ withEffToIO $ \runInIO -> do
81+ inThread $ runInIO $ return ()
82+ inThread $ runInIO $ return ()
83+
84+----------------------------------------
85+-- Helpers
86+
87+assertThrowsUnliftError
88+ :: IOE :> es
89+ => String -> Eff es a -> Eff es ()
90+assertThrowsUnliftError err = U.assertThrows err (\ErrorCall{} -> True)
91+
92+inThread :: IO a -> IO a
93+inThread k = A.async k >>= A.wait
tests/Utils.hs → effectful/tests/Utils.hsrenamed+17−1
@@ -2,11 +2,12 @@ module Utils
2 ( assertBool
2 ( assertBool
3 , assertEqual
3 , assertEqual
4 , assertFailure
4 , assertFailure
5+ , assertThrows
5 , Ex(..)
6 , Ex(..)
6 ) where
7 ) where
7
8
8import Control.Exception
9import Control.Exception
9−import Control.Monad.IO.Class
10+import Control.Monad
10import GHC.Stack
11import GHC.Stack
11import qualified Test.Tasty.HUnit as T
12import qualified Test.Tasty.HUnit as T
12
13
@@ -26,5 +27,20 @@ assertEqual msg expected given = liftIO $ T.assertEqual msg expected given
26assertFailure :: (HasCallStack, IOE :> es) => String -> Eff es a
27assertFailure :: (HasCallStack, IOE :> es) => String -> Eff es a
27assertFailure msg = liftIO $ T.assertFailure msg
28assertFailure msg = liftIO $ T.assertFailure msg
28
29
30+assertThrows
31+ :: (Exception e, IOE :> es)
32+ => String
33+ -> (e -> Bool)
34+ -> Eff es a
35+ -> Eff es ()
36+assertThrows msg p k = withEffToIO $ \runInIO -> do
37+ let k' = do
38+ void $ runInIO k
39+ T.assertFailure msg
40+
41+ k' `catch` \e -> if p e
42+ then return ()
43+ else throwIO e
44+
29data Ex = Ex deriving (Eq, Show)
45data Ex = Ex deriving (Eq, Show)
30instance Exception Ex
46instance Exception Ex
src/Effectful/Error.hsdeleted−103
@@ -1,103 +0,0 @@
1−{- | Support for checked exceptions.
2−
3−The 'Error' effect provided by this module is a suitable replacement for the
4−'Control.Monad.Except.ExceptT' monad transformer found in the @mtl@ library. It
5−is __not__ intended to be a general mechanism for catching errors, that's what
6−functions from the "Control.Monad.Catch" module are for.
7−
8−For example, if you want to catch an unchecked exception like
9−'Control.Exception.SomeException' or 'Control.Exception.ErrorCall' you could use
10−'Control.Monad.Catch.catch':
11−
12−>>> import qualified Control.Monad.Catch as E
13−>>> :{
14− let boom :: Eff es String
15− boom = error "BOOM!"
16− in
17− runEff $ boom `E.catch` \(e :: ErrorCall) -> pure "caught some error"
18−:}
19−"caught some error"
20−
21−-}
22−module Effectful.Error
23− ( Error
24− , runError
25− , throwError
26− , catchError
27− , tryError
28− ) where
29−
30−import Control.Exception
31−import Data.Typeable
32−import Data.Unique
33−import GHC.Stack
34−
35−import Effectful.Internal.Effect
36−import Effectful.Internal.Env
37−import Effectful.Internal.Monad
38−
39−data Error e :: Effect where
40− Error :: Unique -> Error e m r
41−
42−-- | TODO: write about possibility of an error escaping the scope of 'runError'
43−-- when misused with 'AsyncE'.
44−runError
45− :: forall e es a. Typeable e
46− => Eff (Error e : es) a
47− -> Eff es (Either (CallStack, e) a)
48−runError m = unsafeEff $ \es0 -> mask $ \release -> do
49− -- A unique tag is picked so that different runError handlers for the same
50− -- type don't catch each other's exceptions.
51− tag <- newUnique
52− size0 <- sizeEnv es0
53− es <- unsafeConsEnv (IdE (Error @e tag)) noRelinker es0
54− r <- tryErrorIO tag (release $ unEff m es) `onException` unsafeTailEnv size0 es
55− _ <- unsafeTailEnv size0 es
56− pure r
57−
58−throwError
59− :: forall e es a. (HasCallStack, Typeable e, Error e :> es)
60− => e
61− -> Eff es a
62−throwError e = readerEffectM @(Error e) $ \(IdE (Error tag)) -> unsafeEff_ $ do
63− throwIO $ ErrorEx tag callStack e
64−
65−catchError
66− :: forall e es a. (Typeable e, Error e :> es)
67− => Eff es a
68− -> (CallStack -> e -> Eff es a)
69− -> Eff es a
70−catchError m handler = do
71− readerEffectM @(Error e) $ \(IdE (Error tag)) -> unsafeEff $ \es -> do
72− size <- sizeEnv es
73− catchErrorIO tag (unEff m es) $ \cs e -> do
74− checkSizeEnv size es
75− unEff (handler cs e) es
76−
77−tryError
78− :: forall e es a. (Typeable e, Error e :> es)
79− => Eff es a
80− -> Eff es (Either (CallStack, e) a)
81−tryError m = (Right <$> m) `catchError` \es e -> pure $ Left (es, e)
82−
83−----------------------------------------
84−-- Helpers
85−
86−data ErrorEx e = ErrorEx Unique CallStack e
87−instance Typeable e => Show (ErrorEx e) where
88− showsPrec p (ErrorEx _ cs e)
89− = ("Effectful.Error.ErrorEx (" ++)
90− . showsPrec p (typeOf e)
91− . (") " ++)
92− . showsPrec p cs
93−instance Typeable e => Exception (ErrorEx e)
94−
95−catchErrorIO :: Typeable e => Unique -> IO a -> (CallStack -> e -> IO a) -> IO a
96−catchErrorIO tag m handler = do
97− m `catch` \err@(ErrorEx etag e cs) -> do
98− if tag == etag
99− then handler e cs
100− else throwIO err
101−
102−tryErrorIO :: Typeable e => Unique -> IO a -> IO (Either (CallStack, e) a)
103−tryErrorIO tag m = catchErrorIO tag (Right <$> m) $ \es e -> pure $ Left (es, e)
src/Effectful/Fail.hsdeleted−6
@@ -1,6 +0,0 @@
1−module Effectful.Fail
2− ( Fail
3− , runFail
4− ) where
5−
6−import Effectful.Internal.Monad
src/Effectful/Handler.hsdeleted−290
@@ -1,290 +0,0 @@
1−module Effectful.Handler
2− ( -- * Sending operations to the handler
3− send
4−
5− -- * Handling effects
6−
7− -- ** Basic handlers
8− , interpret
9− , interpretM
10−
11− -- ** Derived handlers
12− , reinterpret
13− , reinterpretM
14−
15− -- ** Handling local 'Eff' operations
16− , LocalEnv
17−
18− -- *** Unlifts
19− , localSeqUnlift
20− , localSeqUnliftIO
21− , localUnlift
22− , localUnliftIO
23−
24− -- *** Lifts
25− , withLiftMap
26− , withLiftMapIO
27−
28− -- *** Bidirectional lifts
29− , localLiftUnlift
30− , localLiftUnliftIO
31− ) where
32−
33−import Control.Monad.IO.Unlift
34−import GHC.Stack
35−import qualified Control.Exception as E
36−
37−import Effectful.Internal.Effect
38−import Effectful.Internal.Env
39−import Effectful.Internal.Monad
40−
41−----------------------------------------
42−-- Handler
43−
44−-- | Opaque representation of the 'Eff' environment at the point of calling the
45−-- 'send' function, i.e. right before the control is passed to the effect
46−-- handler.
47−newtype LocalEnv es = LocalEnv (Env es)
48−
49−data Handler (e :: Effect) = forall handlerEs. Handler
50− { _env :: Env handlerEs
51− , _handle :: forall a localEs. HasCallStack
52− => LocalEnv localEs
53− -> e (Eff localEs) a
54− -> Eff handlerEs a
55− }
56−
57−runHandler :: Env es -> Handler e -> Eff (e : es) a -> IO a
58−runHandler es0 e m = do
59− size0 <- sizeEnv es0
60− E.bracket (unsafeConsEnv e relinker es0)
61− (unsafeTailEnv size0)
62− (\es -> unEff m es)
63− where
64− relinker :: Relinker Handler e
65− relinker = Relinker $ \relink Handler{..} -> do
66− env <- relink _env
67− pure Handler { _env = env, .. }
68−
69−----------------------------------------
70−-- Sending operations
71−
72−-- | Send an operation of a given effect to its handler for execution.
73−send :: (HasCallStack, e :> es) => e (Eff es) a -> Eff es a
74−send op = unsafeEff $ \es -> do
75− Handler{..} <- getEnv es
76− unEff (_handle (LocalEnv es) op) _env
77−
78−----------------------------------------
79−-- Interpretation
80−
81−-- | Interpret a first order effect.
82−interpret
83− :: (forall r localEs. HasCallStack => e (Eff localEs) r -> Eff es r)
84− -- ^ The effect handler.
85− -> Eff (e : es) a
86− -> Eff es a
87−interpret handler m = unsafeEff $ \es -> do
88− les <- forkEnv es
89− runHandler es (Handler les $ \_ -> handler) m
90−
91−-- | Interpret a higher order effect.
92−--
93−-- /Note:/ 'LocalEnv' is for handling local 'Eff' operations using a function
94−-- from the 'localUnlift' family.
95−interpretM
96− :: (forall r localEs. HasCallStack => LocalEnv localEs -> e (Eff localEs) r -> Eff es r)
97− -- ^ The effect handler.
98− -> Eff (e : es) a
99− -> Eff es a
100−interpretM handler m = unsafeEff $ \es -> do
101− les <- forkEnv es
102− runHandler es (Handler les handler) m
103−
104−----------------------------------------
105−-- Reinterpretation
106−
107−-- | Interpret a first order effect using other effects.
108−reinterpret
109− :: (Eff handlerEs a -> Eff es b)
110− -- ^ Introduction of effects encapsulated within the handler.
111− -> (forall r localEs. HasCallStack => e (Eff localEs) r -> Eff handlerEs r)
112− -- ^ The effect handler.
113− -> Eff (e : es) a
114− -> Eff es b
115−reinterpret runHandlerEs handler m = unsafeEff $ \es -> do
116− les0 <- forkEnv es
117− (`unEff` les0) . runHandlerEs . unsafeEff $ \les -> do
118− runHandler es (Handler les $ \_ -> handler) m
119−
120−-- | Interpret a higher order effect using other effects.
121−--
122−-- /Note:/ 'LocalEnv' is for handling local 'Eff' operations using a function
123−-- from the 'localUnlift' family.
124−reinterpretM
125− :: (Eff handlerEs a -> Eff es b)
126− -- ^ Introduction of effects encapsulated within the handler.
127− -> (forall r localEs. HasCallStack => LocalEnv localEs -> e (Eff localEs) r -> Eff handlerEs r)
128− -- ^ The effect handler.
129− -> Eff (e : es) a
130− -> Eff es b
131−reinterpretM runHandlerEs handler m = unsafeEff $ \es -> do
132− les0 <- forkEnv es
133− (`unEff` les0) . runHandlerEs . unsafeEff $ \les -> do
134− runHandler es (Handler les handler) m
135−
136−----------------------------------------
137−-- Unlifts
138−
139−-- | Create a local unlifting function with the 'SeqUnlift' strategy. For the
140−-- general version see 'localUnlift'.
141−localSeqUnlift
142− :: LocalEnv localEs
143− -- ^ Local environment.
144− -> ((forall r. Eff localEs r -> Eff es r) -> Eff es a)
145− -- ^ Continuation with the unlifting function in scope.
146− -> Eff es a
147−localSeqUnlift env = localUnlift env SeqUnlift
148−
149−-- | Create a local unlifting function with the 'SeqUnlift' strategy. For the
150−-- general version see 'localUnliftIO'.
151−localSeqUnliftIO
152− :: IOE :> es
153− => LocalEnv localEs
154− -- ^ Local environment.
155− -> ((forall r. Eff localEs r -> IO r) -> IO a)
156− -- ^ Continuation with the unlifting function in scope.
157− -> Eff es a
158−localSeqUnliftIO env = localUnliftIO env SeqUnlift
159−
160−-- | Create a local unlifting function with the given strategy.
161−localUnlift
162− :: LocalEnv localEs
163− -- ^ Local environment.
164− -> UnliftStrategy
165− -> ((forall r. Eff localEs r -> Eff es r) -> Eff es a)
166− -- ^ Continuation with the unlifting function in scope.
167− -> Eff es a
168−localUnlift (LocalEnv les) strategy k = case strategy of
169− SeqUnlift -> unsafeEff $ \es -> do
170− unsafeSeqUnliftEff les $ \unlift -> do
171− (`unEff` es) $ k $ unsafeEff_ . unlift
172− ConcUnlift p l -> unsafeEff $ \es -> do
173− unsafeConcUnliftEff les p l $ \unlift -> do
174− (`unEff` es) $ k $ unsafeEff_ . unlift
175−
176−-- | Create a local unlifting function with the given strategy.
177−localUnliftIO
178− :: IOE :> es
179− => LocalEnv localEs
180− -- ^ Local environment.
181− -> UnliftStrategy
182− -> ((forall r. Eff localEs r -> IO r) -> IO a)
183− -- ^ Continuation with the unlifting function in scope.
184− -> Eff es a
185−localUnliftIO (LocalEnv les) strategy k = case strategy of
186− SeqUnlift -> liftIO $ unsafeSeqUnliftEff les k
187− ConcUnlift p l -> liftIO $ unsafeConcUnliftEff les p l k
188−
189−-- | Utility for lifting 'Eff' operations of type
190−--
191−-- @'Eff' es a -> 'Eff' es b@
192−--
193−-- to
194−--
195−-- @forall localEs. 'Eff' localEs a -> 'Eff' localEs b@
196−--
197−-- /Note:/ the operation must not run its argument in a separate thread,
198−-- attempting to do so will result in a runtime error.
199−withLiftMap
200− :: IOE :> es
201− => ((forall a b localEs. (Eff es a -> Eff es b) -> Eff localEs a -> Eff localEs b) -> Eff es r)
202− -- ^ Continuation with the lifting function in scope.
203− -> Eff es r
204−withLiftMap k = unsafeWithLiftMapIO $ \liftMap -> do
205− unsafeEff $ \es -> (`unEff` es) $ k $ \f -> do
206− liftMap $ (`unEff` es) . f . liftIO
207−
208−-- | Utility for lifting 'IO' operations of type
209−--
210−-- @'IO' a -> 'IO' b@
211−--
212−-- to
213−--
214−-- @forall localEs. 'Eff' localEs a -> 'Eff' localEs b@
215−--
216−-- /Note:/ the operation must not run its argument in a separate thread,
217−-- attempting to do so will result in a runtime error.
218−--
219−-- Useful e.g. for lifting the unmasking function in
220−-- 'Control.Exception.mask'-like operations:
221−--
222−-- >>> :{
223−-- data Fork :: Effect where
224−-- ForkWithUnmask :: ((forall a. m a -> m a) -> m ()) -> Fork m ThreadId
225−-- :}
226−--
227−-- >>> :{
228−-- runFork :: IOE :> es => Eff (Fork : es) a -> Eff es a
229−-- runFork = interpretM $ \env (ForkWithUnmask m) -> withLiftMapIO $ \liftMap -> do
230−-- localUnliftIO env (ConcUnlift Ephemeral $ Limited 1) $ \unlift -> do
231−-- forkIOWithUnmask $ \unmask -> unlift $ m $ liftMap unmask
232−-- :}
233−withLiftMapIO
234− :: IOE :> es
235− => ((forall a b localEs. (IO a -> IO b) -> Eff localEs a -> Eff localEs b) -> Eff es r)
236− -- ^ Continuation with the lifting function in scope.
237− -> Eff es r
238−withLiftMapIO = unsafeWithLiftMapIO
239−
240−----------------------------------------
241−-- Bidirectional lifts
242−
243−-- | Create a local lifting and unlifting function with the given strategy.
244−--
245−-- Useful for lifting complicated 'Eff' operations where the monadic action
246−-- shows in both positive (as a result) and negative (as an argument) position.
247−--
248−-- /Note:/ depending on the operation you're lifting 'localUnlift' along with
249−-- 'withLiftMap' might be enough and is more efficient.
250−localLiftUnlift
251− :: IOE :> es
252− => LocalEnv localEs
253− -- ^ Local environment.
254− -> UnliftStrategy
255− -> ((forall r. Eff es r -> Eff localEs r) -> (forall r. Eff localEs r -> Eff es r) -> Eff es a)
256− -- ^ Continuation with the lifting and unlifting function in scope.
257− -> Eff es a
258−localLiftUnlift (LocalEnv les) strategy k = case strategy of
259− SeqUnlift -> unsafeEff $ \es -> do
260− unsafeSeqUnliftEff es $ \unliftEs -> do
261− unsafeSeqUnliftEff les $ \unliftLocalEs -> do
262− (`unEff` es) $ k (unsafeEff_ . unliftEs) (liftIO . unliftLocalEs)
263− ConcUnlift p l -> unsafeEff $ \es -> do
264− unsafeConcUnliftEff es p l $ \unliftEs -> do
265− unsafeConcUnliftEff les p l $ \unliftLocalEs -> do
266− (`unEff` es) $ k (unsafeEff_ . unliftEs) (liftIO . unliftLocalEs)
267−
268−-- | Create a local unlifting function with the given strategy along with an
269−-- unrestricted lifting function.
270−--
271−-- Useful for lifting complicated 'IO' operations where the monadic action shows
272−-- in both positive (as a result) and negative (as an argument) position.
273−--
274−-- /Note:/ depending on the operation you're lifting 'localUnliftIO' along with
275−-- 'withLiftMapIO' might be enough and is more efficient.
276−localLiftUnliftIO
277− :: IOE :> es
278− => LocalEnv localEs
279− -- ^ Local environment.
280− -> UnliftStrategy
281− -> ((forall r. IO r -> Eff localEs r) -> (forall r. Eff localEs r -> IO r) -> IO a)
282− -- ^ Continuation with the lifting and unlifting function in scope.
283− -> Eff es a
284−localLiftUnliftIO (LocalEnv les) strategy k = case strategy of
285− SeqUnlift -> liftIO $ unsafeSeqUnliftEff les $ k unsafeEff_
286− ConcUnlift p l -> liftIO $ unsafeConcUnliftEff les p l $ k unsafeEff_
287−
288−-- $setup
289−-- >>> import Control.Concurrent
290−-- >>> import Effectful
src/Effectful/Internal/Monad.hsdeleted−434
@@ -1,434 +0,0 @@
1−{-# LANGUAGE UndecidableInstances #-}
2−{-# OPTIONS_GHC -Wno-noncanonical-monad-instances #-}
3−{-# OPTIONS_HADDOCK not-home #-}
4−-- | The 'Eff' monad.
5−--
6−-- This module is intended for internal use only, and may change without warning
7−-- in subsequent releases.
8−module Effectful.Internal.Monad
9− ( -- * Monad
10− Eff
11− , runPureEff
12−
13− -- ** Access to the internal representation
14− , unEff
15− , unsafeEff
16− , unsafeEff_
17−
18− -- * Fail
19− , Fail
20− , runFail
21−
22− -- * IO
23− , IOE
24− , runEff
25−
26− -- * Primitive
27− , Prim
28− , runPrim
29−
30− -- ** Unlift strategies
31− , UnliftStrategy(..)
32− , Persistence(..)
33− , Limit(..)
34− , unliftStrategy
35− , withUnliftStrategy
36−
37− --- *** Low-level helpers
38− , unsafeWithLiftMapIO
39− , unsafeSeqUnliftEff
40− , unsafeConcUnliftEff
41−
42− -- * Primitive effects
43−
44− -- ** Running
45− , runEffect
46− , evalEffect
47− , execEffect
48−
49− -- ** Modification
50− , getEffect
51− , putEffect
52− , stateEffect
53− , localEffect
54− , readerEffectM
55− , stateEffectM
56− ) where
57−
58−import Control.Applicative (liftA2)
59−import Control.Concurrent (myThreadId)
60−import Control.Exception
61−import Control.Monad.Base
62−import Control.Monad.Fix
63−import Control.Monad.IO.Class
64−import Control.Monad.IO.Unlift
65−import Control.Monad.Primitive
66−import Control.Monad.Trans.Control
67−import Data.Unique
68−import GHC.Exts (oneShot)
69−import GHC.IO (IO(..))
70−import System.IO.Unsafe (unsafeDupablePerformIO)
71−import qualified Control.Monad.Catch as E
72−
73−import Effectful.Internal.Effect
74−import Effectful.Internal.Env
75−import Effectful.Internal.Unlift
76−import Effectful.Internal.Utils
77−
78−type role Eff nominal representational
79−
80−-- | The 'Eff' monad provides the implementation of an operation that performs
81−-- an arbitrary set of effects. In @'Eff' es a@, @es@ is a type-level list that
82−-- contains all the effects that the operation may perform. For example, an
83−-- operation that produces an 'Integer' by consuming a 'String' from the global
84−-- environment and acting upon a single mutable cell containing a 'Bool' would
85−-- have the following type:
86−--
87−-- @
88−-- 'Eff' '['Effectful.Reader.Reader' 'String', 'Effectful.State.State' 'Bool'] 'Integer'
89−-- @
90−--
91−-- Normally, a concrete list of effects is not used to parameterize 'Eff'.
92−-- Instead, the '(:>)' type class is used to express constraints on the list of
93−-- effects without coupling an operation to a concrete list of effects. For
94−-- example, the above example would more commonly be expressed with the
95−-- following type:
96−--
97−-- @
98−-- ('Effectful.Reader.Reader' 'String' ':>' es, 'Effectful.State.State' 'Bool' ':>' es) => 'Eff' es 'Integer'
99−-- @
100−--
101−-- This abstraction allows the operation to be used in functions that may
102−-- perform other effects, and it also allows the effects to be handled in any
103−-- order.
104−newtype Eff (es :: [Effect]) a = Eff (Env es -> IO a)
105− deriving (Monoid, Semigroup)
106−
107−-- | Run a pure 'Eff' operation.
108−--
109−-- For running operations with side effects see 'runEff'.
110−runPureEff :: Eff '[] a -> a
111−runPureEff (Eff m) =
112− -- unsafePerformIO is safe here since IOE was not on the stack, so no IO with
113− -- side effects was performed (unless someone sneakily introduced side effects
114− -- with unsafeEff, but then all bets are off).
115− --
116− -- Moreover, internals don't allocate any resources that require explicit
117− -- cleanup actions to run, so the "Dupable" part should also be just fine.
118− unsafeDupablePerformIO $ m =<< emptyEnv
119−
120−----------------------------------------
121−-- Access to the internal representation
122−
123−-- | Peel off the constructor of 'Eff'.
124−unEff :: Eff es a -> Env es -> IO a
125−unEff (Eff m) = m
126−
127−-- | Access the underlying 'IO' monad along with the environment.
128−unsafeEff :: (Env es -> IO a) -> Eff es a
129−unsafeEff m = Eff (oneShot m)
130−
131−-- | Access the underlying 'IO' monad.
132−unsafeEff_ :: IO a -> Eff es a
133−unsafeEff_ m = unsafeEff $ \_ -> m
134−
135−-- | Utility for lifting 'IO' operations of type
136−--
137−-- @'IO' a -> 'IO' b@
138−--
139−-- to
140−--
141−-- @forall localEs. 'Eff' localEs a -> 'Eff' localEs b@
142−--
143−-- /Note:/ the 'IO' operation must not run its argument in a separate thread,
144−-- attempting to do so will result in a runtime error.
145−unsafeWithLiftMapIO
146− :: ((forall a b localEs. (IO a -> IO b) -> Eff localEs a -> Eff localEs b) -> Eff es r)
147− -> Eff es r
148−unsafeWithLiftMapIO k = k $ \mapIO m -> unsafeEff $ \es -> do
149− unsafeSeqUnliftEff es $ \unlift -> mapIO $ unlift m
150−
151−-- | Lower 'Eff' operations into 'IO' ('SeqUnlift').
152−unsafeSeqUnliftEff :: Env es -> ((forall r. Eff es r -> IO r) -> IO a) -> IO a
153−unsafeSeqUnliftEff es k = do
154− tid0 <- myThreadId
155− k $ \m -> do
156− tid <- myThreadId
157− if tid `eqThreadId` tid0
158− then unEff m es
159− else error
160− $ "If you want to use the unlifting function to run Eff operations "
161− ++ "in multiple threads, have a look at UnliftStrategy (ConcUnlift)."
162−
163−-- | Lower 'Eff' operations into 'IO' ('ConcUnlift').
164−unsafeConcUnliftEff
165− :: Env es
166− -> Persistence
167− -> Limit
168− -> ((forall r. Eff es r -> IO r) -> IO a)
169− -> IO a
170−unsafeConcUnliftEff es Ephemeral (Limited uses) k =
171− unsafeEphemeralConcUnliftIO uses k es unEff
172−unsafeConcUnliftEff es Ephemeral Unlimited k =
173− unsafeEphemeralConcUnliftIO maxBound k es unEff
174−unsafeConcUnliftEff es Persistent (Limited threads) k =
175− unsafePersistentConcUnliftIO False threads k es unEff
176−unsafeConcUnliftEff es Persistent Unlimited k =
177− unsafePersistentConcUnliftIO True maxBound k es unEff
178−
179−----------------------------------------
180−-- Base
181−
182−instance Functor (Eff es) where
183− fmap f (Eff m) = unsafeEff $ \es -> f <$> m es
184− a <$ Eff fb = unsafeEff $ \es -> a <$ fb es
185−
186−instance Applicative (Eff es) where
187− pure = unsafeEff_ . pure
188− Eff mf <*> Eff mx = unsafeEff $ \es -> mf es <*> mx es
189− Eff ma *> Eff mb = unsafeEff $ \es -> ma es *> mb es
190− Eff ma <* Eff mb = unsafeEff $ \es -> ma es <* mb es
191− liftA2 f (Eff ma) (Eff mb) = unsafeEff $ \es -> liftA2 f (ma es) (mb es)
192−
193−instance Monad (Eff es) where
194− return = unsafeEff_ . pure
195− Eff m >>= k = unsafeEff $ \es -> m es >>= \a -> unEff (k a) es
196− -- https://gitlab.haskell.org/ghc/ghc/-/issues/20008
197− Eff ma >> Eff mb = unsafeEff $ \es -> ma es >> mb es
198−
199−instance MonadFix (Eff es) where
200− mfix f = unsafeEff $ \es -> mfix $ \a -> unEff (f a) es
201−
202−----------------------------------------
203−-- Exception
204−
205−instance E.MonadThrow (Eff es) where
206− throwM = unsafeEff_ . throwIO
207−
208−instance E.MonadCatch (Eff es) where
209− catch m handler = unsafeEff $ \es -> do
210− size <- sizeEnv es
211− unEff m es `catch` \e -> do
212− checkSizeEnv size es
213− unEff (handler e) es
214−
215−instance E.MonadMask (Eff es) where
216− mask k = unsafeEff $ \es -> mask $ \restore ->
217− unEff (k $ \m -> unsafeEff $ restore . unEff m) es
218−
219− uninterruptibleMask k = unsafeEff $ \es -> uninterruptibleMask $ \restore ->
220− unEff (k $ \m -> unsafeEff $ restore . unEff m) es
221−
222− generalBracket acquire release use = unsafeEff $ \es -> mask $ \restore -> do
223− size <- sizeEnv es
224− resource <- unEff acquire es
225− b <- restore (unEff (use resource) es) `catch` \e -> do
226− checkSizeEnv size es
227− _ <- unEff (release resource $ E.ExitCaseException e) es
228− throwIO e
229− checkSizeEnv size es
230− c <- unEff (release resource $ E.ExitCaseSuccess b) es
231− pure (b, c)
232−
233−----------------------------------------
234−-- Fail
235−
236−data Fail :: Effect where
237− Fail :: Unique -> Fail m r
238−
239−runFail :: Eff (Fail : es) a -> Eff es (Either String a)
240−runFail m = unsafeEff $ \es0 -> mask $ \release -> do
241− -- A unique tag is picked so that different runFail handlers don't catch each
242− -- other's exceptions.
243− tag <- newUnique
244− size0 <- sizeEnv es0
245− es <- unsafeConsEnv (IdE (Fail tag)) noRelinker es0
246− r <- tryFailIO tag (release $ unEff m es) `onException` unsafeTailEnv size0 es
247− _ <- unsafeTailEnv size0 es
248− pure r
249−
250−instance Fail :> es => MonadFail (Eff es) where
251− fail msg = readerEffectM $ \(IdE (Fail tag)) -> unsafeEff_ $ do
252− throwIO $ FailEx tag msg
253−
254−--------------------
255−
256−data FailEx = FailEx Unique String
257−instance Show FailEx where
258− showsPrec p (FailEx _ msg)
259− = ("Effectful.Internal.Monad.FailEx " ++)
260− . showsPrec p msg
261−instance Exception FailEx
262−
263−tryFailIO :: Unique -> IO a -> IO (Either String a)
264−tryFailIO tag m =
265− (Right <$> m) `catch` \err@(FailEx etag msg) -> do
266− if tag == etag
267− then pure $ Left msg
268− else throwIO err
269−
270−----------------------------------------
271−-- IO
272−
273−-- | Run arbitrary 'IO' operations via 'MonadIO' or 'MonadUnliftIO'.
274−newtype IOE :: Effect where
275− IOE :: UnliftStrategy -> IOE m r
276−
277−-- | Run an 'Eff' operation with side effects.
278−--
279−-- For running pure operations see 'runPureEff'.
280−runEff :: Eff '[IOE] a -> IO a
281−runEff m = unEff (evalEffect (IdE (IOE SeqUnlift)) m) =<< emptyEnv
282−
283−instance IOE :> es => MonadIO (Eff es) where
284− liftIO = unsafeEff_
285−
286−instance IOE :> es => MonadUnliftIO (Eff es) where
287− withRunInIO = unliftEff
288−
289−-- | Instance included for compatibility with existing code, usage of 'liftIO'
290−-- is preferrable.
291−instance IOE :> es => MonadBase IO (Eff es) where
292− liftBase = unsafeEff_
293−
294−-- | Instance included for compatibility with existing code, usage of
295−-- 'withRunInIO' is preferrable.
296−instance IOE :> es => MonadBaseControl IO (Eff es) where
297− type StM (Eff es) a = a
298− liftBaseWith = unliftEff
299− restoreM = pure
300−
301−----------------------------------------
302−-- Primitive
303−
304−-- | An effect to perform primitive state-transformer actions.
305−data Prim :: Effect where
306− Prim :: Prim m r
307−
308−-- | Run an 'Eff' operation with primitive state-transformer actions.
309−runPrim :: IOE :> es => Eff (Prim : es) a -> Eff es a
310−runPrim = evalEffect (IdE Prim)
311−
312−instance Prim :> es => PrimMonad (Eff es) where
313− type PrimState (Eff es) = PrimState IO
314− primitive = unsafeEff_ . IO
315−
316−----------------------------------------
317−-- Unlift strategies
318−
319−-- | The strategy to use when unlifting 'Eff' operations via 'withRunInIO' or
320−-- the 'Effectful.Interpreter.localUnlift' family.
321−data UnliftStrategy
322− = SeqUnlift
323− -- ^ The fastest strategy and a default setting for 'IOE'. An attempt to call
324− -- the unlifting function in threads distinct from its creator will result in
325− -- a runtime error.
326− | ConcUnlift Persistence Limit
327− -- ^ A strategy that makes it possible for the unlifting function to be called
328− -- in threads distinct from its creator. See 'Persistence' and 'Limit'
329− -- settings for more information.
330− deriving (Eq, Ord, Show)
331−
332−-- | Persistence setting for the 'ConcUnlift' strategy.
333−--
334−-- Different functions require different persistence strategies. Examples:
335−--
336−-- - Lifting 'pooledMapConcurrentlyN' from the @unliftio@ library requires the
337−-- 'Ephemeral' strategy as we don't want jobs to share environment changes
338−-- made by previous jobs run in the same worker thread.
339−--
340−-- - Lifting 'Control.Concurrent.forkIOWithUnmask' requires the 'Persistent'
341−-- strategy, otherwise the unmasking function would start with a fresh
342−-- environment each time it's called.
343−data Persistence
344− = Ephemeral
345− -- ^ Don't persist the environment between calls to the unlifting function in
346− -- threads distinct from its creator.
347− | Persistent
348− -- ^ Persist the environment between calls to the unlifting function within a
349− -- particular thread.
350− deriving (Eq, Ord, Show)
351−
352−-- | Limit setting for the 'ConcUnlift' strategy.
353−data Limit
354− = Limited Int
355− -- ^ Behavior dependent on the 'Persistence' setting.
356− --
357− -- For 'Ephemeral', it limits the amount of uses of the unlifting function in
358− -- threads distinct from its creator to @N@. The unlifting function will
359− -- create @N@ copies of the environment when called @N@ times and @K+1@ copies
360− -- when called @K < N@ times.
361− --
362− -- For 'Persistent', it limits the amount of threads, distinct from the
363− -- creator of the unlifting function, it can be called in to @N@. The amount
364− -- of calls to the unlifting function within a particular threads is
365− -- unlimited. The unlifting function will create @N@ copies of the environment
366− -- when called in @N@ threads and @K+1@ copies when called in @K < N@ threads.
367− | Unlimited
368− -- ^ Unlimited use of the unlifting function.
369− deriving (Eq, Ord, Show)
370−
371−-- | Get the current 'UnliftStrategy'.
372−unliftStrategy :: IOE :> es => Eff es UnliftStrategy
373−unliftStrategy = readerEffectM $ \(IdE (IOE unlift)) -> pure unlift
374−
375−-- | Locally override the 'UnliftStrategy' with a given value.
376−--
377−-- /Note:/ the strategy is always reset to 'SeqUnlift' for new threads.
378−withUnliftStrategy :: IOE :> es => UnliftStrategy -> Eff es a -> Eff es a
379−withUnliftStrategy unlift = localEffect $ \_ -> IdE (IOE unlift)
380−
381−-- | Helper for 'MonadBaseControl' and 'MonadUnliftIO' instances.
382−unliftEff :: IOE :> es => ((forall r. Eff es r -> IO r) -> IO a) -> Eff es a
383−unliftEff f = unliftStrategy >>= \case
384− SeqUnlift -> unsafeEff $ \es -> unsafeSeqUnliftEff es f
385− ConcUnlift p b -> withUnliftStrategy SeqUnlift $ do
386− unsafeEff $ \es -> unsafeConcUnliftEff es p b f
387−
388−----------------------------------------
389−-- Helpers
390−
391−runEffect :: handler e -> Eff (e : es) a -> Eff es (a, handler e)
392−runEffect e0 m = unsafeEff $ \es0 -> do
393− size0 <- sizeEnv es0
394− bracket (unsafeConsEnv e0 noRelinker es0)
395− (unsafeTailEnv size0)
396− (\es -> (,) <$> unEff m es <*> getEnv es)
397−
398−evalEffect :: handler e -> Eff (e : es) a -> Eff es a
399−evalEffect e m = unsafeEff $ \es0 -> do
400− size0 <- sizeEnv es0
401− bracket (unsafeConsEnv e noRelinker es0)
402− (unsafeTailEnv size0)
403− (\es -> unEff m es)
404−
405−execEffect :: handler e -> Eff (e : es) a -> Eff es (handler e)
406−execEffect e0 m = unsafeEff $ \es0 -> do
407− size0 <- sizeEnv es0
408− bracket (unsafeConsEnv e0 noRelinker es0)
409− (unsafeTailEnv size0)
410− (\es -> unEff m es *> getEnv es)
411−
412−getEffect :: e :> es => Eff es (handler e)
413−getEffect = unsafeEff $ \es -> getEnv es
414−
415−putEffect :: e :> es => handler e -> Eff es ()
416−putEffect e = unsafeEff $ \es -> unsafePutEnv e es
417−
418−stateEffect :: e :> es => (handler e -> (a, handler e)) -> Eff es a
419−stateEffect f = unsafeEff $ \es -> unsafeStateEnv f es
420−
421−localEffect :: e :> es => (handler e -> handler e) -> Eff es a -> Eff es a
422−localEffect f m = unsafeEff $ \es -> do
423− bracket (unsafeStateEnv (\e -> (e, f e)) es)
424− (\e -> unsafePutEnv e es)
425− (\_ -> unEff m es)
426−
427−readerEffectM :: e :> es => (handler e -> Eff es a) -> Eff es a
428−readerEffectM f = unsafeEff $ \es -> getEnv es >>= \e -> unEff (f e) es
429−
430−stateEffectM :: e :> es => (handler e -> Eff es (a, handler e)) -> Eff es a
431−stateEffectM f = unsafeEff $ \es -> mask $ \release -> do
432− (a, e) <- (\e -> release $ unEff (f e) es) =<< getEnv es
433− unsafePutEnv e es
434− pure a
src/Effectful/Reader.hsdeleted−32
@@ -1,32 +0,0 @@
1−-- | The 'Reader' effect.
2−module Effectful.Reader
3− ( Reader
4− , runReader
5− , ask
6− , asks
7− , local
8− ) where
9−
10−import Effectful.Internal.Effect
11−import Effectful.Internal.Monad
12−
13−-- | Provide access to a strict (WHNF), thread local, read only value of type
14−-- @r@.
15−newtype Reader r :: Effect where
16− Reader :: r -> Reader r m a
17−
18−runReader :: r -> Eff (Reader r : es) a -> Eff es a
19−runReader r = evalEffect (IdE (Reader r))
20−
21−ask :: Reader r :> es => Eff es r
22−ask = do
23− IdE (Reader r) <- getEffect
24− pure r
25−
26−asks :: Reader r :> es => (r -> a) -> Eff es a
27−asks f = do
28− IdE (Reader r) <- getEffect
29− pure $ f r
30−
31−local :: Reader r :> es => (r -> r) -> Eff es a -> Eff es a
32−local f = localEffect $ \(IdE (Reader r)) -> IdE (Reader (f r))
src/Effectful/State/Local.hsdeleted−67
@@ -1,67 +0,0 @@
1−-- | The 'State' effect.
2−--
3−-- Represented as a pure value underneath, therefore:
4−--
5−-- - thread local (if you need the state to be shareble, have a look at
6−-- "Effectful.State.Shared"),
7−--
8−-- - very fast.
9−--
10−module Effectful.State.Local
11− ( State
12− , runState
13− , evalState
14− , execState
15− , get
16− , gets
17− , put
18− , state
19− , modify
20− , stateM
21− , modifyM
22− ) where
23−
24−import Effectful.Internal.Effect
25−import Effectful.Internal.Monad
26−
27−-- | Provide access to a strict (WHNF), thread local, mutable state of type @s@.
28−newtype State s :: Effect where
29− State :: s -> State s m r
30−
31−runState :: s -> Eff (State s : es) a -> Eff es (a, s)
32−runState s0 m = do
33− (a, IdE (State s)) <- runEffect (IdE (State s0)) m
34− pure (a, s)
35−
36−evalState :: s -> Eff (State s : es) a -> Eff es a
37−evalState s = evalEffect (IdE (State s))
38−
39−execState :: s -> Eff (State s : es) a -> Eff es s
40−execState s0 m = do
41− IdE (State s) <- execEffect (IdE (State s0)) m
42− pure s
43−
44−get :: State s :> es => Eff es s
45−get = do
46− IdE (State s) <- getEffect
47− pure s
48−
49−gets :: State s :> es => (s -> a) -> Eff es a
50−gets f = f <$> get
51−
52−put :: State s :> es => s -> Eff es ()
53−put s = putEffect (IdE (State s))
54−
55−state :: State s :> es => (s -> (a, s)) -> Eff es a
56−state f = stateEffect $ \(IdE (State s0)) -> let (a, s) = f s0 in (a, IdE (State s))
57−
58−modify :: State s :> es => (s -> s) -> Eff es ()
59−modify f = state (\s -> ((), f s))
60−
61−stateM :: State s :> es => (s -> Eff es (a, s)) -> Eff es a
62−stateM f = stateEffectM $ \(IdE (State s0)) -> do
63− (a, s) <- f s0
64− pure (a, IdE (State s))
65−
66−modifyM :: State s :> es => (s -> Eff es s) -> Eff es ()
67−modifyM f = stateM (\s -> ((), ) <$> f s)
src/Effectful/State/Shared.hsdeleted−79
@@ -1,79 +0,0 @@
1−-- | The 'State' effect.
2−--
3−-- Represented as an 'MVar' underneath, therefore:
4−--
5−-- - shareable between multiple threads,
6−--
7−-- - slower than "Effectful.State.Local".
8−--
9−module Effectful.State.Shared
10− ( State
11− , runState
12− , evalState
13− , execState
14− , get
15− , gets
16− , put
17− , state
18− , modify
19− , stateM
20− , modifyM
21− ) where
22−
23−import Control.Concurrent.MVar
24−
25−import Effectful.Internal.Effect
26−import Effectful.Internal.Env
27−import Effectful.Internal.Monad
28−
29−-- | Provide access to a strict (WHNF), shareable, mutable state of type @s@.
30−newtype State s :: Effect where
31− State :: MVar s -> State s m r
32−
33−runState :: s -> Eff (State s : es) a -> Eff es (a, s)
34−runState s m = do
35− v <- unsafeEff_ $ newMVar s
36− a <- evalEffect (IdE (State v)) m
37− (a, ) <$> unsafeEff_ (readMVar v)
38−
39−evalState :: s -> Eff (State s : es) a -> Eff es a
40−evalState s m = do
41− v <- unsafeEff_ $ newMVar s
42− evalEffect (IdE (State v)) m
43−
44−execState :: s -> Eff (State s : es) a -> Eff es s
45−execState s m = do
46− v <- unsafeEff_ $ newMVar s
47− _ <- evalEffect (IdE (State v)) m
48− unsafeEff_ $ readMVar v
49−
50−get :: State s :> es => Eff es s
51−get = unsafeEff $ \es -> do
52− IdE (State v) <- getEnv es
53− readMVar v
54−
55−gets :: State s :> es => (s -> a) -> Eff es a
56−gets f = f <$> get
57−
58−put :: State s :> es => s -> Eff es ()
59−put s = unsafeEff $ \es -> do
60− IdE (State v) <- getEnv es
61− modifyMVar_ v $ \_ -> s `seq` pure s
62−
63−state :: State s :> es => (s -> (a, s)) -> Eff es a
64−state f = unsafeEff $ \es -> do
65− IdE (State v) <- getEnv es
66− modifyMVar v $ \s0 -> let (a, s) = f s0 in s `seq` pure (s, a)
67−
68−modify :: State s :> es => (s -> s) -> Eff es ()
69−modify f = state (\s -> ((), f s))
70−
71−stateM :: State s :> es => (s -> Eff es (a, s)) -> Eff es a
72−stateM f = unsafeEff $ \es -> do
73− IdE (State v) <- getEnv es
74− modifyMVar v $ \s0 -> do
75− (a, s) <- unEff (f s0) es
76− s `seq` pure (s, a)
77−
78−modifyM :: State s :> es => (s -> Eff es s) -> Eff es ()
79−modifyM f = stateM (\s -> ((), ) <$> f s)
src/Effectful/Writer/Local.hsdeleted−48
@@ -1,48 +0,0 @@
1−-- | The 'Writer' effect.
2−module Effectful.Writer.Local
3− ( Writer
4− , runWriter
5− , execWriter
6− , tell
7− , listen
8− , listens
9− ) where
10−
11−import Control.Exception
12−
13−import Effectful.Internal.Effect
14−import Effectful.Internal.Env
15−import Effectful.Internal.Monad
16−
17−-- | Provide access to a strict (WHNF), thread local, write only value of type
18−-- @w@.
19−newtype Writer w :: Effect where
20− Writer :: w -> Writer w m r
21−
22−runWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
23−runWriter m = do
24− (a, IdE (Writer w)) <- runEffect (IdE (Writer mempty)) m
25− pure (a, w)
26−
27−execWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
28−execWriter m = do
29− IdE (Writer w) <- execEffect (IdE (Writer mempty)) m
30− pure w
31−
32−tell :: (Writer w :> es, Monoid w) => w -> Eff es ()
33−tell w = stateEffect $ \(IdE (Writer w0)) -> ((), IdE (Writer (w0 <> w)))
34−
35−listen :: (Writer w :> es, Monoid w) => Eff es a -> Eff es (a, w)
36−listen m = unsafeEff $ \es -> mask $ \restore -> do
37− w0 <- unsafeStateEnv (\(IdE (Writer w)) -> (w, IdE (Writer mempty))) es
38− a <- restore (unEff m es) `onException` merge es w0
39− (a, ) <$> merge es w0
40− where
41− merge es w0 =
42− -- If an exception is thrown, restore w0 and keep parts of w1.
43− unsafeStateEnv (\(IdE (Writer w1)) -> (w1, IdE (Writer (w0 <> w1)))) es
44−
45−listens :: (Writer w :> es, Monoid w) => (w -> b) -> Eff es a -> Eff es (a, b)
46−listens f m = do
47− (a, w) <- listen m
48− pure (a, f w)
src/Effectful/Writer/Shared.hsdeleted−61
@@ -1,61 +0,0 @@
1−module Effectful.Writer.Shared
2− ( Writer
3− , runWriter
4− , execWriter
5− , tell
6− , listen
7− , listens
8− ) where
9−
10−import Control.Concurrent.MVar
11−import Control.Exception
12−
13−import Effectful.Internal.Effect
14−import Effectful.Internal.Env
15−import Effectful.Internal.Monad
16−
17−-- | Provide access to a strict (WHNF), shareable, write only value of type @w@.
18−newtype Writer w :: Effect where
19− Writer :: MVar w -> Writer w m r
20−
21−runWriter :: Monoid w => Eff (Writer w : es) a -> Eff es (a, w)
22−runWriter m = do
23− v <- unsafeEff_ $ newMVar mempty
24− a <- evalEffect (IdE (Writer v)) m
25− (a, ) <$> unsafeEff_ (readMVar v)
26−
27−execWriter :: Monoid w => Eff (Writer w : es) a -> Eff es w
28−execWriter m = do
29− v <- unsafeEff_ $ newMVar mempty
30− _ <- evalEffect (IdE (Writer v)) m
31− unsafeEff_ $ readMVar v
32−
33−tell :: (Writer w :> es, Monoid w) => w -> Eff es ()
34−tell w1 = unsafeEff $ \es -> do
35− IdE (Writer v) <- getEnv es
36− modifyMVar_ v $ \w0 -> let w = w0 <> w1 in w `seq` pure w
37−
38−listen :: (Writer w :> es, Monoid w) => Eff es a -> Eff es (a, w)
39−listen m = unsafeEff $ \es -> do
40− -- The mask is uninterruptible because modifyMVar_ v0 in the merge function
41− -- might block and if an async exception is received while waiting, w1 will be
42− -- lost.
43− uninterruptibleMask $ \restore -> do
44− v1 <- newMVar mempty
45− -- Replace thread local MVar with a fresh one for isolated listening.
46− v0 <- unsafeStateEnv (\(IdE (Writer v)) -> (v, IdE (Writer v1))) es
47− a <- restore (unEff m es) `onException` merge es v0 v1
48− (a, ) <$> merge es v0 v1
49− where
50− -- Merge results accumulated in the local MVar with the mainline. If an
51− -- exception was received while listening, merge results recorded so far.
52− merge es v0 v1 = do
53− unsafePutEnv (IdE (Writer v0)) es
54− w1 <- readMVar v1
55− modifyMVar_ v0 $ \w0 -> let w = w0 <> w1 in w `seq` pure w
56− pure w1
57−
58−listens :: (Writer w :> es, Monoid w) => (w -> b) -> Eff es a -> Eff es (a, b)
59−listens f m = do
60− (a, w) <- listen m
61− pure (a, f w)