FinalizeExtractResult
Collapsing the Result at the end of an extraction chain.
Overview
In Context-Generic Programming (CGP), every step of an
extraction chain returns a Result: the payload on the left, the narrowed
remainder on the right. At the last step the remainder is uninhabited, so the Err case cannot
happen, and FinalizeExtractResult says so.
This is the one you actually call. FinalizeExtract is the underlying
discharge, and it applies to a remainder you already hold; this applies to the Result a chain hands
you, which is the shape the last extract_field actually returns.
Definition
FinalizeExtractResult collapses the Result a chain's last step returns:
pub trait FinalizeExtractResult {
type Output;
fn finalize_extract_result(self) -> Self::Output;
}
Self is the Result and Output is the payload alone. The trait has one blanket impl, for any
Result<T, E> whose error half can be discharged, shown in Under the hood.
finalize_extract_result returns the Ok value directly and discharges the Err half through
FinalizeExtract, which cannot fail once the remainder is uninhabited.
Usage
It is not in the prelude, the one member of the extractor family that is not. Import it from
cgp::core::field::traits, and you will want it, because it closes a chain:
use cgp::core::field::traits::FinalizeExtractResult;
There is nothing to implement. The blanket impl covers every Result whose error half is
dischargeable, so it applies the moment a chain has tried every variant.
Examples
Closing a chain, which is the whole use:
use cgp::core::field::traits::{ExtractField, FinalizeExtractResult, HasExtractor};
use cgp::prelude::*;
#[derive(Debug, PartialEq)]
pub struct Circle {
pub radius: f64,
}
#[derive(Debug, PartialEq)]
pub struct Rectangle {
pub width: f64,
pub height: f64,
}
#[derive(ExtractField)]
pub enum Shape {
Circle(Circle),
Rectangle(Rectangle),
}
pub fn area(shape: Shape) -> f64 {
match shape.to_extractor().extract_field(PhantomData::<Symbol!("Circle")>) {
Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius,
Err(remainder) => {
let rect = remainder
.extract_field(PhantomData::<Symbol!("Rectangle")>)
.finalize_extract_result(); // no variants left, so this cannot fail
rect.width * rect.height
}
}
}
pub fn demo() {
assert_eq!(area(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 12.0);
}
The code needs neither .unwrap(), expect, nor a wildcard arm. The call compiles only because
both variants have been tried, which makes it a proof rather than an assertion; the
Common Mistakes section shows the call one step early.
When to use it
Use it to close every hand-written extraction chain, and prefer not writing the chain at all.
finalize_extract_resultat the end of a chain, which is where the lastextract_fieldleft you holding aResult.FinalizeExtractwhen a nestedmatchhas already unwrapped the remainder out of itsResult.- The dispatch combinators rather than a hand-written chain, since they generate it from the enum's own variant list, which keeps "add a variant" from breaking every call site.
.ok()or amatchwhen you are making a single attempt and do not intend to exhaust the enum. This trait does not resolve on such a single attempt.- A
matchwhen the enum is concrete.
Under the hood
The trait's one impl delegates to FinalizeExtract on the error half:
impl<T, E> FinalizeExtractResult for Result<T, E>
where
E: FinalizeExtract,
{
type Output = T;
fn finalize_extract_result(self) -> T {
match self {
Ok(value) => value,
Err(remainder) => remainder.finalize_extract(),
}
}
}
The soundness argument lives in FinalizeExtract: the remainder is uninhabited once every variant
is IsVoid, so the Err arm is discharged with an empty match and no execution path reaches it.
Because the bound is on E rather than on any CGP type in particular, the impl also covers a
Result whose error is Infallible or Void. That is occasionally useful
outside the extractor family, for collapsing a Result that a signature required but that cannot
fail.
Output is an associated type rather than a generic, so the call can sit at the end of a method
chain with nothing to annotate.
Common Mistakes
It is not in the prelude. Import it from cgp::core::field::traits. Without the import, a
complete chain on a one-variant enum:
let circle = shape
.to_extractor()
.extract_field(PhantomData::<Symbol!("Circle")>)
.finalize_extract_result();
fails as a missing method, though rustc does name the fix:
error[E0599]: no method named `finalize_extract_result` found for enum `Result<T, E>` in the current scope
...
help: trait `FinalizeExtractResult` which provides `finalize_extract_result` is implemented but not in scope; perhaps you want to import it
Calling it early does not compile. Any variant still possible leaves the remainder inhabited and
the bound unsatisfied. Trying only Rectangle:
let rect = shape
.to_extractor()
.extract_field(PhantomData::<Symbol!("Rectangle")>)
.finalize_extract_result();
reports the unsatisfied FinalizeExtract bound on the remainder:
error[E0599]: the method `finalize_extract_result` exists for enum `Result<Rectangle, __PartialShape<IsPresent, IsVoid>>`, but its trait bounds were not satisfied
...
= note: the following trait bounds were not satisfied:
`__PartialShape<IsPresent, IsVoid>: FinalizeExtract`
which is required by `Result<Rectangle, __PartialShape<IsPresent, IsVoid>>: FinalizeExtractResult`
It discards nothing and cannot panic. Unlike .unwrap(), it compiles to a single path: the
Err case is discharged at the type level.
It applies to any Result with a dischargeable error, not only to extraction remainders, which is
occasionally surprising when it resolves somewhere you did not expect.
Adding a variant breaks the call, by design: the final remainder becomes inhabited again and the bound stops being satisfied.
Related constructs
FinalizeExtract: the underlying discharge, and the full exhaustiveness argument.ExtractField: the narrowing that produces theResultthis collapses.HasExtractor: where a chain begins.FinalizeBuild: the record family's ending.- Type-level lists: where the uninhabited
Voidcomes from. - Dispatch combinators: the providers that build the chain for you.
#[derive(ExtractField)]: what makes an enum extractable.
The ideas behind it:
- Extensible variants: the exhaustiveness argument and the extensible visitor pattern.
Source
extract_field.rs:FinalizeExtractResultand the rest of the family
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.