TryComputer
The fallible synchronous member of the handler family: a computer that can return an error.
Overview
In Context-Generic Programming (CGP), TryComputer is for synchronous computations that
can fail. CGP enables pluggable trait implementations in Rust, and TryComputer is the component
that lets a context plug in a fallible computation. A computation that parses a string,
looks up a key, or checks an invariant may not be able to produce its output, and it needs a way to
report the failure. Where Computer returns its Output directly, TryComputer
returns Result<Output, Error>, where Error is the abstract error type of the
context, the type the implementation runs against. It sits
one step from Computer on the fallibility axis of the handler family,
and one step from Handler, which is also async.
Returning the context's abstract error rather than a concrete one keeps a TryComputer provider
generic. A provider does not commit to anyhow::Error or std::io::Error: it returns the bare
Error, and the context decides the concrete type when it wires one. This is why the component has
HasErrorType as a supertrait: the
supertrait supplies that Error, and every fallible component in a context names the same one, so
their results compose with ?.
Definition
CanTryCompute is defined as:
#[cgp_component(TryComputer)]
#[prefix(@cgp.extra.handler in DefaultNamespace)]
#[derive_delegate(UseDelegate<Code>)]
#[derive_delegate(UseInputDelegate<Input>)]
#[use_type(HasErrorType.Error)]
pub trait CanTryCompute<Code, Input> {
type Output;
fn try_compute(&self, _code: PhantomData<Code>, input: Input) -> Result<Self::Output, Error>;
}
Its attributes:
#[cgp_component]— turns the trait into a component: its argument names the provider traitTryComputerthat implementations target and the wiring keyTryComputerComponent, whileCanTryComputestays the consumer trait callers use.#[prefix]— registers the component inDefaultNamespaceunder the path@cgp.extra.handler, so a context that joins that namespace binds its provider at@cgp.extra.handler.TryComputerComponentrather than at the bare key.#[derive_delegate]— generates the legacyUseDelegateandUseInputDelegateproviders, which dispatch on theCodetag and on theInputtype through an inner table; theopenstatement replaces both, dispatching on either parameter or on the pair.#[use_type]— addsHasErrorTypeas a supertrait and rewrites the bareErrorto<Self as HasErrorType>::Error. The trait's ownOutputstays written asSelf::Output.
Usage
TryComputer, TryComputerComponent, and the consumer trait CanTryCompute are imported from
cgp::extra::handler. The consumer method mirrors compute but returns a
Result:
fn try_compute(&self, _code: PhantomData<Code>, input: Input) -> Result<Self::Output, Error>;
A context gains the operation by wiring TryComputerComponent to a provider and by wiring an error
type, since the consumer trait has HasErrorType as a supertrait. A provider comes from one of
three places:
- A hand-written provider returns the context's
Error, usually raising a concrete error into it withCanRaiseError, as the example below does. - The promotion providers, imported from
cgp::extra::handler, answer it from a neighbouring member.Promote<P>wraps the output of aComputerinOk, andTryPromote<P>reads aComputerwhoseOutputisResult<T, Error>as success or failure.TryPromotealso works the other way, presenting aTryComputeras aComputerwhoseOutputis thatResult. #[cgp_computer]on a function returningResult<T, E>generates aComputerwhoseOutputis theResult, and wires it to thePromoteTryComputerbundle, whoseTryComputerComponententry isTryPromote. Socomputereturns the wholeResult, whiletry_computepropagates itsErr. The function'sEmust be the context's error type, because the bundle passes theErrthrough unconverted.
The component dispatches on both the Code tag and the Input type. Its by-reference sibling
TryComputerRef, documented on its own page, differs on one axis: its
try_compute_ref method borrows the input as &Input. The async and fallible counterpart is
Handler, and PromoteAsync<P> lifts a
TryComputer into one.
Examples
A TryComputer provider that parses a string into a number, raising the parse error into the
context's error:
use core::marker::PhantomData;
use core::num::ParseIntError;
use cgp::extra::handler::{TryComputer, TryComputerComponent};
use cgp::prelude::*;
use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent};
use cgp::extra::error::RaiseFrom;
use cgp::extra::handler::CanTryCompute;
#[cgp_impl(new ParseU64)]
#[uses(CanRaiseError<ParseIntError>)]
#[use_type(HasErrorType.Error)]
impl<Code> TryComputer<Code, String> {
type Output = u64;
fn try_compute(
&self,
_code: PhantomData<Code>,
input: String,
) -> Result<Self::Output, Error> {
input.parse().map_err(Self::raise_error)
}
}
#[derive(Debug, PartialEq)]
pub struct AppError(pub String);
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self {
AppError(e.to_string())
}
}
pub struct App;
delegate_components! {
App {
ErrorTypeProviderComponent: UseType<AppError>,
ErrorRaiserComponent: RaiseFrom,
TryComputerComponent: ParseU64,
}
}
check_components! {
App {
TryComputerComponent: ((), String),
}
}
pub fn demo() {
assert_eq!(App.try_compute(PhantomData::<()>, "12".to_owned()), Ok(12));
assert!(App.try_compute(PhantomData::<()>, "twelve".to_owned()).is_err());
}
ParseU64 names neither the context nor its error type. App supplies both: its error type is
AppError, and RaiseFrom raises the ParseIntError
through AppError's From impl. App is an environmental
context, and the component is
parameter-targeted: the computation
acts on the Input, while App decides the provider and the error type.
When to use it
Reach for TryComputer for a synchronous computation that can fail. It is the fallible middle
of the family: it receives providers promoted from a Computer and is itself
promoted into a Handler. Prefer TryComputerRef when the
computation only reads its input.
Reach for Computer instead when the computation cannot fail, since Promote
lifts a computer into a TryComputer and the computer stays usable in the infallible positions too,
and for Handler when the computation must also await. Write a TryComputer
provider by hand rather than a #[cgp_computer] function when the error has to be raised into the
context's error type, since the function's error type is passed through unconverted.
Related constructs
TryComputerRef— the by-reference variant that borrows its input.Computer— the infallible counterpart; promotes into aTryComputer.Handler— the async and fallible member.HasErrorType— the supertrait supplying theErrorthis returns.CanRaiseError— converts a concrete source error into that abstract error.#[cgp_computer]— builds a provider from a fallible function.- Handler combinators —
Promote,TryPromote,PromoteAsync, and the promotion bundles.
The ideas behind it:
- Handlers — the computation family and its sync, async, fallible, and input-passing axes.
- Modular error handling — the abstract error a fallible computer returns.
Source
TryComputerandTryComputerRef:try_compute.rsPromote,TryPromote, and the promotion bundles:cgp-handler/src/providers/- Re-exported through
cgp::extra::handler.
An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.