cgp v0.5.0
Version 0.5.0 of cgp, the library for Context-Generic Programming (CGP) that enables pluggable trait implementations in Rust, removes the Async trait and adds monadic computation, automatic dispatch over enums, and one derive for extensible data. This page lists every change a user can see and the steps that take a project there from v0.4.2.
Released on 2025-10-12.
- Release post: CGP v0.5.0 Release: Auto dispatchers, extensible datatype improvements, monadic computation, RTN emulation, modular serde, and more
- Crate:
cgp0.5.0 on crates.io - Changes: v0.4.2...v0.5.0
Summaryβ
The Async trait and the async aliases are removed, and a project recovers Send where it spawns a future through a proxy trait such as CanSendRun. #[derive(CgpData)] derives extensible records and variants in one step, #[cgp_auto_dispatch] implements a trait for an enum from its variants, and the new cgp-monad crate composes handlers that short-circuit. Symbol! replaces symbol! and can produce a &'static str, and cgp-field moves its exports into submodules.
Compatibilityβ
- Minimum Rust version: 1.89, up from 1.81.
- Released together: the workspace's 23 crates published on crates.io, all at 0.5.0.
- New crates:
cgp-monad, for monadic computation;cgp-field-extra, for the optional builder and defaults; andcgp-extra-macrowithcgp-extra-macro-lib, which hold#[cgp_computer],#[cgp_producer], and#[cgp_auto_dispatch]. - Removed crates:
cgp-async,cgp-sync, andcgp-inner; see the async removal andHasInner. - Features:
cgpandcgp-corelose theirfullfeature; see the features.
Upgradingβ
A project moving from v0.4.2 takes these steps, in this order:
- Change the version to
cgp = "0.5.0"on Rust 1.89 or newer, and deletefeatures = ["full"]from acgporcgp-coredependency, per the features. - Remove the
Asyncconstructs: replaceHasAsyncErrorType,CanRaiseAsyncError,CanWrapAsyncError, andHasAsyncRuntimeTypewith their plain counterparts, and deleteAsync,MaybeSend, andMaybeSyncbounds, per the removal. - Recover
Sendwhere a future is spawned through a proxy trait, per theSendbound, and name aCodewhereverCanRunis used, perCanRun. - Rename the type-level strings:
symbol!becomesSymbol!, andCharbecomesChars, perSymbol!andChars. - Update the imports of
cgp-fielditems and of the names that moved, per the field modules and the moved names. - Rewrite the handler code: promotions per the promotion chain,
Resulterrors per the error rule, and#[cgp_handler]per its replacement. - Rewrite the builder code that names a generated type or a trait that changed, per the partial types and
FinalizeBuild, and replaceHasInnerper its removal. - Build the crate and fix what the compiler reports.
Breaking changesβ
Async and the async aliases are removedβ
Async, MaybeSend, and MaybeSync are removed, together with the traits built on them, HasAsyncErrorType, CanRaiseAsyncError, CanWrapAsyncError, and HasAsyncRuntimeType (#149). The crates cgp-async and cgp-sync are removed too, and cgp-async-macro exports only #[async_trait]: its native_async and strip_async macros are gone.
- Old:
AsyncaliasedSend + Sync, andHasAsyncErrorTyperequired it of the context and of its error type. - New:
HasErrorType,CanRaiseError,CanWrapError, andHasRuntimeTypecarry noSendorSyncbound, andCanHandlerequiresHasErrorTypewhere it requiredHasAsyncErrorType. - What to do: replace each removed trait with its plain counterpart, and delete
Async,MaybeSend, andMaybeSyncfrom bounds. A project that still wants an old trait can copy its definition into its own crate.
#[async_trait] no longer requires Sendβ
#[async_trait] desugars an async fn in a trait to a function that returns impl Future<Output = T>, without a Send bound on the future (#149). Every async trait that cgp defines is affected, among them CanRun, CanComputeAsync, and CanHandle.
- Old: the desugared future was
impl Future<Output = T> + MaybeSend, so generic code could pass the future of a call such ascontext.run()totokio::spawn. - New: the future is
impl Future<Output = T>, and generic code can no longer show that it isSend. - What to do: where generic code must spawn a future, require a proxy trait whose method returns
impl Future + Send, such asCanSendRun. Implement its provider traitSendRunneron the concrete context by forwarding torun, where the compiler sees the concrete types. The release post works the pattern through in Emulating RTN. A trait of the project's own that promises aSendfuture needs a copy with the bound, for code that calls the traitscgpdefines.
CanRun takes a Code parameterβ
CanRun and its provider trait Runner take a Code type parameter, and run takes a PhantomData<Code> argument (#149). See CanRun.
- Old:
CanRun: HasAsyncErrorTypewithrun(&self), andRunner<Context>. - New:
CanRun<Code>: HasErrorTypewithrun(&self, _code: PhantomData<Code>), andRunner<Context, Code>. A bound written asCanRunwithout a parameter fails withE0107. - What to do: name a
Codetype, such as a marker struct, wherever the project usesCanRun, and passPhantomDatatorun. A context can choose a provider per code, because the component derivesUseDelegate<Code>.
cgp-field exports move into submodulesβ
The root of cgp-field, which cgp::core::field re-exports, stops re-exporting its items (#150). They are in three public modules instead: traits, impls, and types.
- Old:
cgp::core::field::HasField,cgp::core::field::UseField, andcgp::core::field::Cons. - New:
cgp::core::field::traits::HasField,cgp::core::field::impls::UseField, andcgp::core::field::types::Cons. - What to do: update each explicit import of a
cgp-fielditem. The traits are intraits; the providers, the field-state markers, and the casting traits are inimpls; andCons,Nil,Either,Void,Field,Index,Chars,Symbol, andLifeare intypes. A glob import ofcgp::preludeis unaffected for the names the prelude exports.
Several names move to other modulesβ
Four names change their import path, and a project that imports them explicitly updates the import:
TakeFieldleaves the prelude, and is imported fromcgp::core::field::traits(#148).Promote,PromoteRef, andTryPromoteleave the prelude, and are imported fromcgp::extra::handler(#137).HandleFieldValuemoves fromcgp::extra::handlertocgp::extra::dispatch(#139).#[cgp_computer]and#[cgp_producer]live in the newcgp-extra-macrocrate, so the pathcgp::core::macros::cgp_computerno longer resolves (#138). The prelude exports both.
symbol! becomes Symbol! and its expansion carries the lengthβ
symbol! is removed, and Symbol! takes its place with a different expansion (#151, #159, #173).
- Old:
symbol!("abc")expanded to the nestedChar<'a', Char<'b', Char<'c', Nil>>>, which the compiler printed asΞΉ<'a', ΞΉ<'b', ΞΉ<'c', Ξ΅>>>. - New:
Symbol!("abc")expands toSymbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>, with the length as the first parameter, and the compiler printsΟ<3, ΞΆ<'a', ΞΆ<'b', ΞΆ<'c', Ξ΅>>>>. TheHasFieldimpls that#[derive(HasField)]and the getter macros generate use the new type. - What to do: write
Symbol!forsymbol!, and give a type-level string that was written out by hand the new shape.
Char is renamed Charsβ
Chars holds one character of a type-level string and the rest of the string, and replaces Char (#165, #159). Its short name changes from ΞΉ to ΞΆ, which avoids the confusable_idents warning that ΞΉ raised beside a variable named i.
- Old:
Char<CHAR, Tail>, writtenΞΉ<CHAR, Tail>. - New:
Chars<CHAR, Tail>, writtenΞΆ<CHAR, Tail>. - What to do: rename each use. Neither
CharnorΞΉexists any more.
HasInner and cgp-inner are removedβ
The trait HasInner, its component, and the cgp-inner crate are removed, along with the cgp::extra::inner module (#170). UseField composes contexts more flexibly. Nothing replaces HasInner by name.
- Old:
HasInnerwithtype Innerandfn inner(&self) -> &Self::Inner. - New: a getter or an abstract type read from a field with
UseField. - What to do: read the inner context through
UseField, or copy the old trait into the project's own crate.
Generated partial types gain the __Partial prefixβ
The types that #[derive(BuildField)] and #[derive(ExtractField)] generate gain a __Partial prefix, which keeps them out of the user's namespace (#156).
- Old:
PartialPersonfor a structPerson, andPartialShapeandPartialRefShapefor an enumShape. - New:
__PartialPerson,__PartialShape, and__PartialRefShape. - What to do: rename each generated type that the code names. Most code reaches them only through
builder()and the traits.
FinalizeBuild takes its target from PartialDataβ
FinalizeBuild becomes a subtrait of the new PartialData, and its Output associated type is gone (#152). BuildField is now implemented for every type that implements UpdateField<Tag, IsPresent, Mapper = IsNothing> (#148).
- Old:
trait FinalizeBuild { type Output; fn finalize_build(self) -> Self::Output; }. - New:
trait FinalizeBuild: PartialData { fn finalize_build(self) -> Self::Target; }, withTargetthe record the partial type completes. - What to do: write
Targetwhere a bound namedFinalizeBuild::Output, and implementPartialDatafor a hand-written partial type. The derives generate both.
The handler promotion chain gains an async stepβ
Promote<Provider> lifts a provider one step: a Producer to a Computer, a Computer to a TryComputer, and an AsyncComputer to a Handler. The new PromoteAsync<Provider> lifts a Computer to an AsyncComputer and a TryComputer to a Handler (#136, #137). See Promote and PromoteAsync.
- Old:
Promote<P>turned aTryComputerinto aHandler,Promote<Promote<P>>turned aComputerinto one, and the aliasesPromote2andPromote3stacked two and three levels. - New:
PromoteAsync<P>turns aTryComputerinto aHandler, andPromoteAsync<Promote<P>>turns aComputerinto one.Promote2andPromote3are removed. - What to do: replace
Promote<P>withPromoteAsync<P>where it produced aHandlerfrom aTryComputer, andPromote<Promote<P>>withPromoteAsync<Promote<P>>.
TryPromote and function providers no longer convert errorsβ
TryPromote<Provider> requires the Result that its provider returns to carry Context::Error (#129, #136). The providers that #[cgp_computer] generates for a function that returns Result<T, E> promote through it, so they follow the same rule.
- Old:
TryPromoteand#[cgp_handler]converted any error typeEintoContext::ErrorthroughCanRaiseError<E>. - New:
Emust beContext::Error; a provider whoseEdiffers fails with a type mismatch. - What to do: return the context's error type from the function, or convert the error inside it before it returns.
#[cgp_handler] is folded into #[cgp_computer]β
#[cgp_handler] is removed, and #[cgp_computer] accepts an async function and generates the Handler that #[cgp_handler] generated (#137).
- Old:
#[cgp_handler] async fn double(x: u8) -> u8. - New:
#[cgp_computer] async fn double(x: u8) -> u8, which derives anAsyncComputerand promotes it to aHandler. - What to do: change the attribute name, and apply the error rule to a function that returns a
Result.
The full features are removedβ
cgp and cgp-core lose their full feature, which forwarded to the removed async features and to cgp-extra (#149). cgp-extra keeps its own default full feature, and cgp now depends on cgp-extra with its default features.
- Old:
cgp = { version = "0.4.2", features = ["full"] }resolved, anddefault-features = falseleft out the providers that need an allocator, such asDebugError. - New:
features = ["full"]fails to resolve, becausecgphas no such feature, andDebugErroris available even withdefault-features = false. - What to do: delete
"full"from the feature list.
New featuresβ
Derives and macrosβ
#[derive(CgpData)]derives the extensible-data traits for a struct or an enum. On a struct it derivesHasField,HasFields, and the builder traits, and on an enum it derivesHasFields,ExtractField, andFromVariant;#[derive(CgpRecord)]and#[derive(CgpVariant)]are its struct and enum forms (#154). See#[derive(CgpData)],#[derive(CgpRecord)], and#[derive(CgpVariant)].#[cgp_auto_dispatch]implements a trait for an enum whose variants all implement it.HasAreaforCircleandRectanglegivesShapean implementation, and neither the trait nor the enum needs to know about the other, so it works across crates. A method may takeself,&self, or&mut selfand extra arguments, and may beasync(#139, #142). See#[cgp_auto_dispatch].
Extensible recordsβ
UpdateField<Tag, M>replaces a wrapped field value in a partial record.BuildFieldis implemented through it, and#[derive(CgpData)]derives it (#148). SeeUpdateField.finalize_with_defaultcompletes a partial record.CanFinalizeWithDefaultfills each unset field fromDefault, andCanBuildWithDefault<Source>builds a record from a source record and defaults the rest (#128, #130). SeeCanFinalizeWithDefaultandCanBuildWithDefault.- The optional builder keeps one type while fields are set. The
IsOptionalmarker stores each field as anOption,HasOptionalBuilder::optional_builder()starts one,SetOptional::setfills a field, andFinalizeOptional::finalize_optionalreturns the record, or the name of the first missing field as a&'static str(#152). The traits are in the newcgp-field-extracrate, whichcgp::extra::fieldre-exports. SeeHasOptionalBuilder,SetOptional, andFinalizeOptional.
Extensible variants and visitorsβ
HasExtractorMutextracts from a mutable reference, and#[derive(ExtractField)]implements it for an enum (#135). SeeHasExtractorMut.MapTypeRefmaps a field type to a reference type. The markersIsRef,IsMut, andIsOwnedimplement it (#132, #135). SeeMapTypeRef.- The matchers cover a mutable reference and an input with extra arguments.
MatchWithHandlersMutandMatchWithValueHandlersMutmatch a&mutvalue.MatchFirstWithHandlers,MatchFirstWithValueHandlers, and theirRefandMutforms match the first element of a tuple(Value, Args)and passArgson (#134, #135, #161).ExtractFirstFieldAndHandleandHandleFirstFieldValueare the providers they use. SeeMatchFirstWithHandlersandMatchWithValueHandlers.
Monadic computationβ
- The
cgp-monadcrate composes computations that short-circuit.PipeMonadic<M, Providers>runs providers in order under the monadM.ErrMonadicpasses on theOkvalue and stops at anErr,OkMonadicdoes the opposite, andIdentMonadiccomposes plainly.BindOkandBindErrlift a provider overResult, andOkMonadicTransandErrMonadicTransstack monads. The traits behind them areMonadicBind,ContainsValue,LiftValue, andMonadicTrans(#127, #129).DispatchMatchers<Handlers>is now an alias forPipeMonadic<OkMonadic, Handlers>, andcgp::extra::monadre-exports the crate. SeePipeMonadic,BindOk,BindErr, andMonadicBind.
Handlersβ
AsyncComputeris the asynchronous counterpart ofComputer.CanComputeAsync<Code, Input>returns anOutputwithout aResult, andHandlerremains the asynchronous counterpart ofTryComputer.AsyncComputerRefandCanComputeAsyncReftake a reference (#136). SeeAsyncComputerandAsyncComputerRef.#[cgp_computer]accepts anasyncfunction and derives anAsyncComputerfor it (#137).ComposeHandlers<A, B>runs one provider and passes its output to the next, forComputer,TryComputer,AsyncComputer, andHandler.PipeHandlersis built on it (#129, #136). SeeComposeHandlers.- Five promotion providers collect what a provider can be promoted to:
PromoteComputer,PromoteTryComputer,PromoteProducer,PromoteAsyncComputer, andPromoteHandler, each a table of the promotions for one kind of provider (#137). SeePromoteComputerandPromoteHandler. UseField<Tag>is aComputerand anAsyncComputer. It runs theCanComputeorCanComputeAsyncimplementation of the field named byTag(#132, #136). SeeUseField.NoCodeis a value of typePhantomData<()>for calling a handler that has no code (#132).ErrorOnly<E>is a context that carries only an error type, withHasErrorType::Error = E(#129).CanSendRun<Code>and its provider traitSendRunnerreturn aSendfuture (#149); see theSendbound.
Type-level strings and lifetimesβ
StaticStringproduces a&'static strfrom aSymbol!type.<Symbol!("hello") as StaticString>::VALUEis"hello"in a const context, which the length thatSymbol!now carries makes possible (#159). SeeStaticString.Life<'a>writes a lifetime as a type (#145, #166). SeeLife.
Improvementsβ
- A getter method may take a first argument other than
self:#[cgp_getter]and#[cgp_auto_getter]acceptfn foo_bar(foo: &Self::Foo) -> &Self::Bar, andUseField<Tag>implements the provider whenSelf::Foohas the field (#169). See#[cgp_getter]and#[cgp_auto_getter]. - A component trait may declare lifetime parameters, which
IsProviderForcarries asLife<'a>andcheck_components!accepts (#145). A component such astrait CanGreet<'a>compiles where v0.4.2 rejected it. - A bare identifier sets the provider name:
#[cgp_getter(FooGetter)]and#[cgp_type(FooTypeProvider)]mean the same asprovider: FooGetterandprovider: FooTypeProvider(#143, #163). See#[cgp_type]. - The prelude exports the new names:
Chars,Symbol,Life,CgpData,CgpRecord,CgpVariant,UpdateField,PartialData,MapTypeRef,IsRef,IsMut,HasExtractorMut,AsyncComputer,#[cgp_auto_dispatch], and theMatchWithValueHandlersandMatchFirstWithValueHandlersproviders, souse cgp::prelude::*reaches them (#154, #137, #139). DelegateComponent<Name: ?Sized>accepts an unsized name:impl DelegateComponent<str> for Tablecompiles, where v0.4.2 failed withE0277(#147). SeeDelegateComponent.
Fixesβ
newwith an array key:delegate_components!declares a struct named bynewonce, where an entry such as[FooKey, BarKey]: UseDelegate<new InnerComponents { β¦ }>declared it once per key and failed withE0428(#164). Seedelegate_components!.CanUseComponentfor an unsized parameter: a context whose provider implementsIsProviderForforstrsatisfiesCanUseComponent<Component, str>, where v0.4.2 failed withE0277(#166). SeeCanUseComponent.
An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See How AI is used in this project.