Skip to main content

MapType

The marker trait that decides how one field of a partial type is stored.

info

Generated machinery​

You are not expected to implement MapType. Its four markers are supplied by the library, and the partial types parameterized by them are generated by #[derive(CgpData)] and its slices. What you do with this trait is recognize its markers, because they are what a builder or extractor error prints; this page explains what each one means. The one case for bounding on the trait is generic code of your own over a partial type's marker parameter.

Overview​

Context-Generic Programming (CGP) represents a half-built struct or a partly-extracted enum as a single type whose every field is independently wrapped: a field that is set carries its value, a field that is not carries nothing, a variant that has been ruled out carries an uninhabited type. Rather than hard-code those shapes, each field is parameterized by a marker, and the field's actual storage type is read out of the marker.

MapType is that marker's trait. It lets the builder and extractor families move a value through intermediate states without changing its runtime representation. A builder starts every field IsNothing and flips each to IsPresent as it is filled; an extractor starts every variant IsPresent and flips each to IsVoid as it is ruled out. Because a flip is a change of type parameter, the compiler tracks exactly which fields are filled, and refuses to finalize an incomplete one.

Definition​

MapType carries a single generic associated type and nothing else:

pub trait MapType {
type Map<T>;
}

Map<T> names the storage type the marker assigns to a field whose value type is T. So IsPresent::Map<String> is String, and IsNothing::Map<String> is (). The marker is the field's state, expressed as a type. Because Map<T> is a generic associated type, a bound that pins the storage reads M: MapType<Map<String> = String>, and one that leaves it open is plain M: MapType.

Usage​

Four state markers implement it, and they are the ones a partial type is parameterized by. Neither the trait nor its markers is in the prelude. Import MapType from cgp::core::field::traits and the markers from cgp::core::field::impls. The library also implements it for two list mappers that are not field states, TryPromoteProviders in PipeMonadic and ToBuildAndMergeHandler in BuildAndMergeOutputs, which MapFields uses to wrap every provider in a list.

impl MapType for IsPresent { type Map<T> = T; } // the field holds its value
impl MapType for IsNothing { type Map<T> = (); } // the field is absent
impl MapType for IsVoid { type Map<T> = Void; } // the case is impossible
impl MapType for IsOptional { type Map<T> = Option<T>; } // the field may or may not be there

The distinction between IsNothing and IsVoid is the one that matters and the one most easily blurred. IsNothing maps to (), which is inhabited: an absent field is a real state a value can be in, which is why a builder needs an explicit all-present impl to finalize. IsVoid maps to the uninhabited Void, so a value with every marker IsVoid cannot exist. That is exactly how an extractor discharges its remainder with an empty match. Records use the first, variants the second.

Three companions complete the picture, each on its own page: MapTypeRef does the same job for borrowed views, where the wrapping also introduces a lifetime, while TransformMap and TransformMapFields are the value-level side, carrying the functions that actually convert a field from one wrapping to another.

Examples​

What each standard marker stores, checked as type equalities, and generic code bounded on the trait:

use cgp::core::field::impls::{IsNothing, IsOptional, IsPresent, IsVoid};
use cgp::core::field::traits::MapType;
use cgp::core::field::types::Void;
use cgp::prelude::*;

// Each function compiles only if the projection is the type on its right.
pub fn present(value: <IsPresent as MapType>::Map<String>) -> String {
value
}

pub fn nothing(value: <IsNothing as MapType>::Map<String>) -> () {
value
}

pub fn void(value: <IsVoid as MapType>::Map<String>) -> Void {
value
}

pub fn optional(value: <IsOptional as MapType>::Map<String>) -> Option<String> {
value
}

// Generic over any marker, the way the builder and extractor families are.
pub fn store<M: MapType, T>(value: M::Map<T>) -> M::Map<T> {
value
}

// A bound that pins the storage names the generic associated type with its argument.
pub fn unwrap_present<M: MapType<Map<String> = String>>(value: M::Map<String>) -> String {
value
}

pub fn demo() {
assert_eq!(present("a".to_owned()), "a");
assert_eq!(optional(None), None);
assert_eq!(store::<IsOptional, u8>(Some(1)), Some(1));
assert_eq!(unwrap_present::<IsPresent>("b".to_owned()), "b");
}

Each of the first four functions compiles only because the projection is the type on its right, so the file is itself the table of what the markers store. You mostly meet the markers inside the partial types #[derive(CgpData)] generates, where a builder's type reads __PartialPerson<IsNothing, IsPresent> and tells you at a glance which fields are set. unwrap_present shows the bound that pins a generic associated type, with the argument written inside the equality.

When to use it​

You will name the markers far more often than the trait. IsPresent and IsNothing appear whenever you read a builder's type in an error; IsVoid whenever you read an extractor's. Recognizing them is the common case, and it is most of what this page is for.

The trait itself has narrower uses.

  • Bound on MapType when you write generic code over a partial type's marker parameter, which is what the builder and extractor families do internally, and what you would do writing your own partial-type machinery.
  • Implement TransformMap rather than this trait to define a new per-field conversion. That is the extension point of the whole scheme, and it is genuinely usable.
  • Do not implement MapType for a new marker expecting the rest of CGP to use it. The generated UpdateField impls are generic over any marker, so update_field moves a field into a custom state, and a TransformMap can convert to and from it. But finalizing, reading a set field, and the optional layer are written against the standard markers, so a fifth marker leaves every one of them unavailable.
  • Reach for the optional-field layer if what you want is defaulted or optional finalization. Both already exist, built on exactly this.

MapFields, the other trait with a similar name, is a different thing: it applies one marker across every entry of a type-level list, where this one names a single field's storage.

Under the hood​

A MapType impl is a type-level function and nothing more. The markers are zero-sized and carry no data; nothing here has a runtime representation, and the only values that exist are the field values being wrapped or unwrapped.

Where the function is applied is in a generated partial type. The derive adds one marker parameter per field and wraps each field's declared type in that parameter's projection:

///The partial builder for [`Person`].
pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> {
pub first_name: <__F0__ as MapType>::Map<String>,
pub last_name: <__F1__ as MapType>::Map<String>,
}

So the partial type's shape is fixed while its storage is decided per instantiation, and a state transition is a change of type argument. UpdateField performs one such transition on a value.

Common Mistakes​

IsNothing and IsVoid are not interchangeable. IsNothing is inhabited (()), IsVoid is not (Void). Records use the first, variants the second, and an error naming the wrong one usually means the two families have been crossed.

The markers are not in the prelude. Import all four, IsOptional included, from cgp::core::field::impls.

MapType and MapFields are different traits. One marker naming one field's storage, against one marker applied across a whole list. The names are close and the jobs are not. MapField, singular, with no s, is a third, unrelated thing again.

A new marker gets you update_field and nothing more. Implementing MapType is easy, and the generic UpdateField impls accept it, but the finalize impls, the HasField impls on a partial type, and the optional layer are written against the standard markers.

Map<T> is a generic associated type, so pinning it in a bound needs the Map<String> = String form rather than a plain associated-type equality.

  • MapTypeRef: the same idea for borrowed views, with a lifetime.
  • TransformMap: the per-field conversion function, and the extension point.
  • TransformMapFields: that conversion lifted across a whole record.
  • HasBuilder: uses IsPresent/IsNothing to track which fields are filled.
  • ExtractField: uses IsPresent/IsVoid to track which variants remain.
  • UpdateField: the primitive that moves a field from one marker to another.
  • MapFields: applies one marker across a whole type-level list.
  • #[derive(CgpData)]: generates the partial types these markers parameterize.
  • Type-level lists: where the uninhabited Void comes from.

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.