-
Notifications
You must be signed in to change notification settings - Fork 448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Arrow 2.0] Effect without suspending shift #2797
Conversation
Thanks, @nomisRev I think this is a significant improvement in both runtime and declarations. 👍 ❤️ |
Really great job 👏 |
This PR takes precedence over #2782 due to some new findings. I converted it back into a All code is complete, and all tests are present. So the code can be reviewed. I want to challenge the context(Shift<Error>)
suspend fun example(): Int = shift(Error) Naming that is more explicit about errors can be more descriptive: context(Raise<Error>)
suspend fun example(): Int = raise(Error) or context(CanFail<Error>)
suspend fun example(): Int = fail(Error) It's a bit imprecise because Open to all suggestions, or alternative names. I didn't suggest |
|
Since this was raised a couple of times, we could either favour failure-settings and keep only |
@i-walker we've started a small poll on KotlinLang, but we can easily hold other polls and accumulate the data. I think we've been able to gather some good feedback already, https://kotlinlang.slack.com/archives/C5UPMM0A0/p1661170633105679 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looking great and getting even simpler 👏 @nomisRev!
is Left -> f(this.value) | ||
is Right -> this | ||
} | ||
catch { f(it).bind() } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👏 nice work with catch
everyone!, this is slick
import kotlin.jvm.JvmMultifileClass | ||
import kotlin.jvm.JvmName | ||
|
||
public inline fun <E, A> either(@BuilderInference block: Shift<E>.() -> A): Either<E, A> = |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These impls are so much nicer and simpler now 👏
arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/continuations/Builders.kt
Show resolved
Hide resolved
} | ||
} | ||
|
||
public class IorShift<E> @PublishedApi internal constructor(semigroup: Semigroup<E>, private val effect: Shift<E>) : |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These may be an exception to what I said above, but it's also not a value class since it takes more than one arg.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sam issue, it can be implemented for StateShift<State, R>
if we have such a type. (Local prototype, shared with you on Slack). Can share gist here for everyone that is interested, otherwise I'll raise it as a follow-up PR.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you send in a gist link, please? 😄
arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/continuations/ErrorHandlers.kt
Outdated
Show resolved
Hide resolved
arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/continuations/Fold.kt
Outdated
Show resolved
Hide resolved
arrow-libs/core/arrow-core/src/commonTest/kotlin/arrow/core/continuations/EagerEffectSpec.kt
Show resolved
Hide resolved
…ow into effect-without-suspend-fold
import kotlin.jvm.JvmName | ||
|
||
/** Run the [Effect] by returning [Either.Right] of [A], or [Either.Left] of [E]. */ | ||
public suspend fun <E, A> Effect<E, A>.toEither(): Either<E, A> = either { invoke() } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should these functions be inline
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does the compiler take that into account if there is no lambda
to inline?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe so based on the decompiled bytecode:
inline suspend fun foo(): Int = 1
suspend fun main() {
println(foo())
}
decompiles inlining
byte var2 = 1;
System.out.println(var2);
in the code below.
public final class KPreludeKt {
@Nullable
public static final Object foo(@NotNull Continuation $completion) {
int $i$f$foo = false;
return Boxing.boxInt(1);
}
private static final Object foo$$forInline(Continuation $completion) {
int $i$f$foo = false;
return 1;
}
@Nullable
public static final Object main(@NotNull Continuation $completion) {
int $i$f$foo = false;
byte var2 = 1;
System.out.println(var2);
return Unit.INSTANCE;
}
// $FF: synthetic method
public static void main(String[] args) {
RunSuspendKt.runSuspend((Function1)2.INSTANCE);
}
}
And when it's not inlined:
suspend fun foo2(): Int = 1
suspend fun main() {
println(foo2())
}
then it expands with the regular overhead of continuation wrapping at var10000 = foo2($continuation);
public final class KPreludeNotInlineKt {
@Nullable
public static final Object foo2(@NotNull Continuation $completion) {
return Boxing.boxInt(1);
}
@Nullable
public static final Object main(@NotNull Continuation var0) {
main.1 $continuation;
label20: {
if (var0 instanceof main.1) {
$continuation = (main.1)var0;
if (($continuation.label & Integer.MIN_VALUE) != 0) {
$continuation.label -= Integer.MIN_VALUE;
break label20;
}
}
$continuation = new main.1(var0);
}
Object $result = $continuation.result;
Object var4 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
Object var10000;
switch ($continuation.label) {
case 0:
ResultKt.throwOnFailure($result);
$continuation.label = 1;
var10000 = foo2($continuation);
if (var10000 == var4) {
return var4;
}
break;
case 1:
ResultKt.throwOnFailure($result);
var10000 = $result;
break;
default:
throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
}
int var1 = ((Number)var10000).intValue();
System.out.println(var1);
return Unit.INSTANCE;
}
// $FF: synthetic method
public static void main(String[] args) {
RunSuspendKt.runSuspend((Function1)2.INSTANCE);
}
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
great work @nomisRev !
Oops. There was only a single approval. @serras do we need to protect the If there are any additional comments, feel free to post them here or in a new issue and we'll tackle them in as subsequent PR. 🙏 |
* Shift without suspend, inline all the rest * Add new error handlers signatures * Make ShiftCancellationException private
* The beginning of Arrow 2.0 * Resource Arrow 2.0 (#2786) * Flatten Resource ADT, maintain API * [Arrow 2.0] Effect without suspending shift (#2797) * Shift without suspend, inline all the rest * Add new error handlers signatures * Make ShiftCancellationException private * Rename Shift to Raise according to Slack Poll, and add some initial docs (#2827) * Remove all references to shift from new Arrow 2.0 code (#2834) * Remove all references to shift from new code * Update API files * Fixes merge conflict between main and arrow-2 (#2835) * Add Resource.allocated() to decompose Resource into it's allocate and… (#2820) * [2743] Migrate internal use of CircuitBreaker double to duration (#2748) * Fix typo (#2824) * Make the server disconnect test more general (#2822) * Update NonEmptyList.fromList deprecation to suggest `toOption()` instead (#2832) * Improve Either.getOrHandle() docs (#2833) * Improve allocated, and fix knit examples Co-authored-by: Jeff Martin <jeff@custommonkey.org> Co-authored-by: Martin Moore <martinmoorej@gmail.com> Co-authored-by: valery1707 <valery1707@gmail.com> Co-authored-by: Lukasz Kalnik <70261110+lukasz-kalnik-gcx@users.noreply.github.com> Co-authored-by: stylianosgakis <stylianos.gakis98@gmail.com> * Add Atomic module, and StateShift (#2817) * Two small deprecations * Add Atomic module, and StateShift. Implement ior through StateShift * Fix build * Fix atomic knit * Fix knit attempt #2 * Update API files * Remove references to shift * Change return type of raise to Nothing (#2839) * Change return type of raise to Nothing Implements #2805 * Update public api with ./gradlew apiDump * Suppress warnings for unreachable calls to fail in tests The test is verifying that no code will be executed after a call to raise, so it's actually testing the very behaviour that the compiler is warning us about. Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update API files * Increase timeout * Fix compiler bug with nested inline + while + return * Clean up ExitCase.fromError * Update API files@ * Feature/remove validated (#2795) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Remove CancellationExceptionNoTrace.kt after merge, and run apiDump * Add missing runnerJUnit5 for arrow-atomic JVM * Publish Arrow 2.0.0-SNAPSHOT (#2871) Co-authored-by: Javier Segovia Córdoba <7463564+JavierSegoviaCordoba@users.noreply.github.com> * Simplify optics to Traversal/Optional/Lens/Prism (#2873) * 'mapOrAccumulate' for Raise (#2872) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> * Fix problems with Atomic * Smaller timeouts * Remove Tuple10 to Tuple22, Const, Eval, computation blocks, and arrow-continuations (#2784) * Revert typo * Fix build * Fix ParMapJvmTest * Implement NonEmptyList using value class (#2911) * Fix merge w.r.t. Saga * apiDump * Test other return expression * change unalign signature (#2972) see discussion in #2960 (comment) #2960 (comment) --------- Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update after merge main * Fix :arrow-optics-ksp-plugin:compileKotlin * Fix Every instances * Move functions to arrow functions (#3014) * Bring back `Iso` (#3013) * Bring back Iso * API Dump --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Update BOM (#3019) * Fix andThen duplication (#3020) * Fix Knit * Fix weird problem with value classes * Update API docs * Update publish workflow Following the instructions in #3090 (comment) * No closing repo on snapshot * knit * Fix optics tests * Fix after merge * Refactor ParMapTest from Kotest Plugin to Kotlin-test runtime #3191 (#3221) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Refactor: Use Kotlin-test runtime for arrow-fx-stm tests (#3224) Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update all Gradle files to mention kotlin.test * Refactor ParZip2Test from Kotest Plugin to Kotlin-test runtime #3192 (#3222) Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Refactor ParZip3Test from Kotest Plugin to Kotlin-test runtime #3193 (#3223) Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Refactor GuaranteeCaseTest to use kotlin test (#3226) Closes #3190 * refactor: migrate NotEmptySetTest to kotlin-test (#3230) Co-authored-by: Alejandro Serrano <trupill@gmail.com> * refactor: migrate EagerEffectSpec to kotlin-test (#3233) Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Refactor NullableSpec from Kotest Plugin to Kotlin-test runtime (#3236) #3153 Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Refactor BracketCaseTest to use kotlin test (#3237) Closes #3186 Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Move arrow-functions tests to kotlin.test (#3243) * Inline `AtomicBoolean` (#3240) * Inline AtomicBoolean * Update API files --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * refactor: migrate MappersSpec to kotlin-test (#3248) * Refactor ResourceTestJvm from Kotest Plugin to Kotlin-test runtime (#3244) Closes #3213 * refactor: migrate FlowJvmTest to Kotlin-test (#3228) * Refactor ParZip9JvmTest from Kotest Plugin to Kotlin-test runtime (#3245) Closes #3211 * Refactor ParZip8JvmTest from Kotest Plugin to Kotlin-test runtime (#3246) Closes #3210 * refactor: migrate NumberInstancesTest to kotlin-test (#3232) * refactor: OptionTest to kotlin-test runtime (#3229) * Revert "Inline `AtomicBoolean` (#3240)" (#3279) This reverts commit a6f1e73. * Refactor ParZip6JvmTest from Kotest Plugin to Kotlin-test runtime (#3255) Closes #3208 * Refactor ParZip5JvmTest from Kotest Plugin to Kotlin-test runtime (#3256) Closes #3207 * Refactor ParZip3JvmTest from Kotest Plugin to Kotlin-test runtime (#3258) Closes #3205 * Refactor ParZip2JvmTest from Kotest Plugin to Kotlin-test runtime (#3259) Closes #3204 * Refactor ParMapJvmTest from Kotest Plugin to Kotlin-test runtime (#3260) Closes #3203 * Refactor ParZip4JvmTest from Kotest Plugin to Kotlin-test runtime (#3257) Closes #3206 * refactor: migrate RaiseAccumulateSpec to kotlin-test (#3250) * Refactor ParZip7JvmTest from Kotest Plugin to Kotlin-test runtime (#3247) Closes #3209 Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update ComparisonKtTest.kt (#3274) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> * Update OptionSpec.kt (#3271) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> * Update TraceJvmSpec.kt (#3276) * Update TraceJvmSpec.kt * Update TraceJvmSpec.kt --------- Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> * Update ParZip9Test.kt (#3265) * Update ParZip9Test.kt * Update ParZip9Test.kt * Update ParZip8Test.kt (#3266) * Update ParZip7Test.kt (#3267) * Update ParZip6Test.kt (#3268) * Update ParZip5Test.kt (#3269) * Update ParZip4Test.kt (#3270) * Refactor CountDownLatchSpec and CyclicBarrierSpec to use kotlin test (#3227) * Refactor CountDownLatchSpec to use kotlin test Closes #3187 * Refactor CyclicBarrierSpec to use kotlin test Closes #3188 --------- Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Refactor NonEmptyListTest to kotlin-test (#3231) * Add kotlin test dependency * Refactor NonEmptyList Test to use kotlin test --------- Co-authored-by: Alejandro Serrano <trupill@gmail.com> * refactor: migrate EffectSpec to kotlin-test (#3234) * Refactor FlowTest to use kotlin test (#3238) Closes #3189 Co-authored-by: Alejandro Serrano <trupill@gmail.com> * refactor: migrate IorSpec to kotlin-test (#3249) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> * refactor: migrate ResultSpec to kotlin-test (#3251) Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> * refactor: migrate StructuredConcurrencySpec to kotlin-test (#3252) * refactor: migrate TraceSpec to kotlin-test (#3253) * refactor: migrate GeneratorsTest to kotlin-test (#3254) * Refactor RaceNJvmTest from Kotest Plugin to Kotlin-test runtime (#3261) Closes #3212 Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update ArrowResponseEAdapterTest.kt (#3264) * Update ArrowResponseEAdapterTest.kt * Update ArrowResponseEAdapterTest.kt --------- Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update CollectionsSyntaxTests.kt (#3273) * Update CollectionsSyntaxTests.kt * Update CollectionsSyntaxTests.kt --------- Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> Co-authored-by: Alejandro Serrano <trupill@gmail.com> * Update NonFatalJvmTest.kt (#3277) * Update ArrowEitherCallAdapterTest.kt (#3278) * Update ArrowEitherCallAdapterTest.kt * Update ArrowEitherCallAdapterTest.kt * Move tests from `serialization` and `functions` completely to `kotlin.test` (#3289) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Fix problems with tests * Remove a bunch of warnings in `arrow-2` (#3282) Co-authored-by: serras <serras@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Finish transition to `kotlin.test` of `retrofit` and `fx-coroutines` (#3291) * Fix problems with concurrency in tests, take 8 * Port rest of `arrow-core` to `kotlin.test` (#3292) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Implement `fixedRate` using monotonic time source (#3294) Co-authored-by: serras <serras@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Port `optics` tests to `kotlin.test` (#3295) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Add or fix contracts in Raise (#3293) * Add or fix contracts in Raise * Make contracts less strict * Get back contract on Either * ignoreErrors should also be AT_MOST_ONCE --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Alternate `SingletonRaise` (#3328) Co-authored-by: Youssef Shoaib <canonballt@gmail.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: serras <serras@users.noreply.github.com> * Remove (unused) tests for high-arity module * Fix tests + Knit * Fix merge NullableSpec * Regression in Arb.list? * Fix test for nonEmptyList * Develocity warning * Fix merge problem with optics-ksp-plugin * Fix timeout in test --------- Co-authored-by: Simon Vergauwen <nomisRev@users.noreply.github.com> Co-authored-by: Sam Cooper <54266448+roomscape@users.noreply.github.com> Co-authored-by: Marc Moreno Ferrer <ignis.fatue@gmail.com> Co-authored-by: Javier Segovia Córdoba <7463564+JavierSegoviaCordoba@users.noreply.github.com> Co-authored-by: Alphonse Bendt <370821+abendt@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Andreas Storesund Madsen <andreas@asmadsen.no> Co-authored-by: molikuner <molikuner@gmail.com> Co-authored-by: Jonathan Lagneaux <lagneaux.j@gmail.com> Co-authored-by: Marcus Ilgner <mail@marcusilgner.com> Co-authored-by: Chris Black <2538545+chrsblck@users.noreply.github.com> Co-authored-by: Tejas Mate <hi.tejas@pm.me> Co-authored-by: HyunWoo Lee (Nunu Lee) <54518925+l2hyunwoo@users.noreply.github.com> Co-authored-by: serras <serras@users.noreply.github.com> Co-authored-by: Youssef Shoaib <canonballt@gmail.com>
This is proposal is second proposal alongside #2782 after some discussions with @raulraja based on some other experimental / explatory implementations.
Design choices
Removal of suspend from shift (Why
CancellationException
?)Both
EagerEffectScope
andEffectScope
implementshift
using a sub type ofCancellationException
since Arrow 1.x.x (before it was usingControlThrowable
). The reason is to maintain correct semantics with other Kotlin Coroutine code, and to respect semantics of language constructs.Effect
Effect
requiresshift
to rely onCancellationException
so that the we have proper short-circuit semantics when mixed with Kotlin Coroutines, such that following bracket laws are respected. Seekotlin.coroutines.cancellation
.EagerEffect
To not break semantics of language constructs we use
CancellationException
inEagerEffect
. Otherwise, without relying onCancellationException
finally
would never be called, andpromise.await()
would hang forever in the example below. Reference to an old impl/prototype here.Due to both implementations of
EffectScope
andEagerEffectScope
throwCancellationException
(in Arrow 1.x.x series) theshift
function does not requiresuspend
perse. So we can unify it under a singleShift
, and we do not longer require@RestrictSuspension
.This changes the
typealias
ofEffect
, andEagerEffect
to only differ insuspend
, and means that we can now write truly polymorphic code when we're inside the context ofShift
, since we can requiresuspend
only when we rely on its capabilities. (I'm using extension functions below to replace/emulate the not yet releasedcontext
receivers.)Additional information:
CancellationException
vsControlThrowable
Inline fold
Since we now have a single
Shift
, we can now also implement a singlefold
which isinline
so it allows forsuspend
to pass through! Below is the definition of our base implementation, and we can derive all implementations forEffect
,EagerEffect
,Either
, etc from it.What is interesting here is that
fold
isinline
, so depending on the caller it will allowsuspend
or not.This however means we can now also implement our
either
DSL asinline
, which means we no longer need to differentiate betweensuspend
andeager
.This allows us to remove an additional complexity pain-point from Arrow. Since there is quite some confusion as to why we need
eager
andsuspend operator fun invoke
. This newfold
implementation removes that limitation completely, and automatically works correctly depending on the callers context.Catch / Attempt
As an added benefit we can now implement
catch
forinline
forEither
, alongsidecatch
forEffect
andEagerEffect
. Because thecatch
implementation forEither
isinline
it still allows you to usesuspend
if desired.Conclusion
Because we removed
suspend
fromshift
we are able to:EagerShift
andShift
into a single typeinline
fold to unify internal implementation, and remove all internal complexity of low-level coroutinesinline
monadic builders, supporting both regular and suspending code seamlesslycatch
for suspending, and eager data types.Are there any downsides of removing
suspend
fromshift
??=> Non suspending function throwing (
CancellationException
)=> ... ?