Skip to main content

FinalizeExtract

Discharging an extractor that has nothing left in it.

Overview​

In Context-Generic Programming (CGP), an extraction chain ends when every variant has been ruled out. At that point the remainder's type is uninhabited (a value of it cannot exist), and FinalizeExtract turns that fact into a usable ending.

It returns any type. That looks unsound and is not: the method can only be called on a value that cannot exist, so its body is an empty match and no execution path reaches it.

That closes a generic match without a wildcard arm or an unreachable!(). It is the mirror of FinalizeBuild, and the two are sound for opposite reasons: a build finalizes because the value is complete, an extraction because the value is impossible.

Definition​

pub trait FinalizeExtract {
fn finalize_extract<T>(self) -> T;
}

Self is the exhausted remainder, and finalize_extract consumes it to return whatever type T the surrounding code needs. That return is sound because the receiver is uninhabited: no value of it can exist, so no execution path reaches the method. The library implements the trait for the uninhabited Void and the standard Infallible, and the derive for the all-ruled-out configuration of each partial enum, owned and borrowed.

Usage​

It is not in the prelude. Import it from cgp::core::field::traits.

You will usually call FinalizeExtractResult instead, which collapses the Result a last extraction returns and calls this on the error half. Reaching for finalize_extract directly means you already hold the remainder rather than a Result.

The impls on partial enums come from #[derive(ExtractField)]; the library supplies the ones for Void and Infallible.

Examples​

Called directly, on a remainder a nested match has unwrapped:

use cgp::core::field::traits::{ExtractField, FinalizeExtract, 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 describe(shape: Shape) -> String {
match shape.to_extractor().extract_field(PhantomData::<Symbol!("Circle")>) {
Ok(circle) => format!("circle of radius {}", circle.radius),
Err(remainder) => match remainder.extract_field(PhantomData::<Symbol!("Rectangle")>) {
Ok(rect) => format!("{} by {} rectangle", rect.width, rect.height),
// Uninhabited: this arm can never run.
Err(remainder) => remainder.finalize_extract(),
},
}
}

pub fn demo() {
assert_eq!(describe(Shape::Circle(Circle { radius: 2.0 })), "circle of radius 2");
assert_eq!(
describe(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })),
"3 by 4 rectangle"
);
}

The last arm returns whatever the surrounding match needs, here a String, and the compiler accepts it because the value being matched cannot exist. The same chain written with finalize_extract_result on the last Result is shorter, and is the form most code uses.

When to use it​

Reach for FinalizeExtractResult unless you already hold a remainder. The two do the same job at different points in the chain.

  • FinalizeExtractResult to close a chain whose last step returned a Result, which is nearly always.
  • FinalizeExtract when a remainder has already been unwrapped out of its Result, typically inside a nested match.
  • The dispatch combinators rather than writing the chain at all: they generate it from the enum's variant list, which stops "add a variant" from breaking every call site by hand.
  • A match when the enum is concrete, where Rust's own exhaustiveness check already does this job.

Under the hood​

Everything turns on what IsVoid maps to. The MapType marker IsVoid maps a payload to the uninhabited Void, so once every variant's marker is IsVoid, every arm of the partial enum holds a Void and the whole type is uninhabited.

The derive supplies an impl on exactly that configuration, for the owned companion and, generic over the MapTypeRef marker, for the borrowed one. cargo cgp expand on the example's Shape shows both:

impl FinalizeExtract for __PartialShape<IsVoid, IsVoid> {
fn finalize_extract<__T__>(self) -> __T__ {
match self {}
}
}
impl<'__a__, __R__: MapTypeRef> FinalizeExtract
for __PartialRefShape<'__a__, __R__, IsVoid, IsVoid> {
fn finalize_extract<__T__>(self) -> __T__ {
match self {}
}
}

The library's own impls for Void and Infallible have the same one-line body. An empty match is legal because no value of the scrutinee's type can exist, and it satisfies any return type for the same reason. So a caller reaches finalize_extract only after trying every variant, and the compiler accepts the discharge without a fallback.

This is where the record and variant families diverge, and the difference decides the whole design. A record uses IsNothing for a missing field, which maps to () and is inhabited: an absent field is a real state a value can be in. A variant uses IsVoid, which is uninhabited: a ruled-out variant is a state no value can be in. That is why a builder needs an explicit all-present FinalizeBuild impl that moves each field into the struct, while an extractor discharges its remainder with an empty match.

Common Mistakes​

Finalizing early does not compile, and the error names the partial enum. The all-void impl does not apply while any marker is still IsPresent. Trying only Rectangle before finalizing:

match shape.to_extractor().extract_field(PhantomData::<Symbol!("Rectangle")>) {
Ok(rect) => rect.width,
Err(remainder) => remainder.finalize_extract(),
}

reports a missing method:

error[E0599]: no method named `finalize_extract` found for enum `__PartialShape<__F0__, __F1__>` in the current scope
...
| ^^^^^^^^^^^^^^^^ method not found in `__PartialShape<IsPresent, IsVoid>`

The marker still IsPresent is the variant left to try, here Circle.

It returns any type, which reads as unsound and is not. The generic return is sound only because the receiver is uninhabited; no value exists, so nothing executes.

Absence is IsVoid here and IsNothing in a builder. An error naming the wrong one usually means record and variant machinery have been crossed.

Adding a variant re-inhabits the final remainder, so every hand-written chain stops compiling. That is the guarantee, and the reason to prefer the dispatch combinators.

It also covers Infallible, which is occasionally useful when threading a chain through an error type that cannot occur.

It consumes the remainder, though there was never anything to consume.

The ideas behind it:

Source​


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.