From 7bb4233e1732ae445026808518ccb24758e3e106 Mon Sep 17 00:00:00 2001 From: Ilya Chernikov Date: Tue, 8 Jan 2019 12:18:39 +0100 Subject: [PATCH] Add mapping function for transformations with ResultsWithDiagnostics also improve chaining helpers --- .../script/experimental/api/errorHandling.kt | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/libraries/scripting/common/src/kotlin/script/experimental/api/errorHandling.kt b/libraries/scripting/common/src/kotlin/script/experimental/api/errorHandling.kt index 1418c28f8e3..ad191753641 100644 --- a/libraries/scripting/common/src/kotlin/script/experimental/api/errorHandling.kt +++ b/libraries/scripting/common/src/kotlin/script/experimental/api/errorHandling.kt @@ -60,18 +60,41 @@ sealed class ResultWithDiagnostics { * If receiver is success - executes [body] and merge diagnostic reports * otherwise returns the failure as is */ -suspend fun ResultWithDiagnostics.onSuccess(body: suspend (R1) -> ResultWithDiagnostics): ResultWithDiagnostics = +inline fun ResultWithDiagnostics.onSuccess(body: (R1) -> ResultWithDiagnostics): ResultWithDiagnostics = when (this) { is ResultWithDiagnostics.Success -> this.reports + body(this.value) is ResultWithDiagnostics.Failure -> this } +/** + * maps transformation ([body]) over iterable merging diagnostics + * return failure with merged diagnostics after first failed transformation + * and success with merged diagnostics and list of results if all transformations succeeded + */ +inline fun Iterable.mapSuccess(body: (T) -> ResultWithDiagnostics): ResultWithDiagnostics> { + val reports = ArrayList() + val results = ArrayList() + for (it in this) { + val result = body(it) + reports.addAll(result.reports) + when (result) { + is ResultWithDiagnostics.Success -> { + results.add(result.value) + } + else -> { + return ResultWithDiagnostics.Failure(reports) + } + } + } + return results.asSuccess(reports) +} + /** * Chains actions on failure: * If receiver is failure - executed [body] * otherwise returns the receiver as is */ -suspend fun ResultWithDiagnostics.onFailure(body: suspend (ResultWithDiagnostics) -> Unit): ResultWithDiagnostics { +inline fun ResultWithDiagnostics.onFailure(body: (ResultWithDiagnostics) -> Unit): ResultWithDiagnostics { if (this is ResultWithDiagnostics.Failure) { body(this) }