From 77f00d2d84d9fe7b474f1f2d0e107bb6d91c3294 Mon Sep 17 00:00:00 2001 From: Him188 Date: Tue, 17 Nov 2020 09:41:00 +0800 Subject: [PATCH] Move CommandResolveResult.fold to extension, add CommandResolveResult.getOrElse --- .../command/resolve/CommandCallResolver.kt | 37 +++++++++++++------ .../internal/command/CommandManagerImpl.kt | 7 +--- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/backend/mirai-console/src/command/resolve/CommandCallResolver.kt b/backend/mirai-console/src/command/resolve/CommandCallResolver.kt index d592654be..b715bcd4c 100644 --- a/backend/mirai-console/src/command/resolve/CommandCallResolver.kt +++ b/backend/mirai-console/src/command/resolve/CommandCallResolver.kt @@ -32,22 +32,35 @@ public class CommandResolveResult private constructor( public val failure: CommandExecuteResult.Failure? get() = value.safeCast() - public inline fun fold( - onSuccess: (ResolvedCommandCall?) -> R, - onFailure: (CommandExecuteResult.Failure) -> R, - ): R { - contract { - callsInPlace(onSuccess, InvocationKind.AT_MOST_ONCE) - callsInPlace(onFailure, InvocationKind.AT_MOST_ONCE) - } - failure?.let(onFailure)?.let { return it } - return call.let(onSuccess) - } - public constructor(call: ResolvedCommandCall?) : this(call as Any?) public constructor(failure: CommandExecuteResult.Failure) : this(failure as Any) } +@OptIn(ExperimentalCommandDescriptors::class) +public inline fun CommandResolveResult.fold( + onSuccess: (ResolvedCommandCall?) -> R, + onFailure: (CommandExecuteResult.Failure) -> R, +): R { + contract { + callsInPlace(onSuccess, InvocationKind.AT_MOST_ONCE) + callsInPlace(onFailure, InvocationKind.AT_MOST_ONCE) + } + failure?.let(onFailure)?.let { return it } + return call.let(onSuccess) +} + + +@OptIn(ExperimentalCommandDescriptors::class) +public inline fun CommandResolveResult.getOrElse( + onFailure: (CommandExecuteResult.Failure) -> ResolvedCommandCall, +): ResolvedCommandCall { + contract { + callsInPlace(onFailure, InvocationKind.AT_MOST_ONCE) + } + failure?.let(onFailure)?.let { return it } + return call!! +} + /** * The resolver converting a [CommandCall] into [ResolvedCommandCall] based on registered [] * diff --git a/backend/mirai-console/src/internal/command/CommandManagerImpl.kt b/backend/mirai-console/src/internal/command/CommandManagerImpl.kt index a198b7ed6..92944888b 100644 --- a/backend/mirai-console/src/internal/command/CommandManagerImpl.kt +++ b/backend/mirai-console/src/internal/command/CommandManagerImpl.kt @@ -193,11 +193,8 @@ internal suspend fun executeCommandImpl( } val resolved = call - .resolve().fold( - onSuccess = { it }, - onFailure = { return it } - ) - .ifNull { return CommandExecuteResult.UnresolvedCommand(call) } + .resolve() + .getOrElse { return it } .let { raw -> raw.intercepted() .getOrElse { return CommandExecuteResult.Intercepted(call, raw, null, it) }